diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dnacopy/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dnacopy/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dnacopy/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..701e64e535c03274c35882af067c4460458a3eef --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-dose via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-dose -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-dose_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-dose_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-dose_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/app/bioconductor-dose_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/app/bioconductor-dose_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6d59c1cb57f4b98d0e8202272870422c32e463e8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/app/bioconductor-dose_server.py @@ -0,0 +1,736 @@ +import subprocess +import tempfile +import shutil +from pathlib import Path +from typing import Optional, Literal, List +import logging + +# Set up logging +logging.basicConfig(level=logging.INFO) +log = logging.getLogger(__name__) + +# Mock the mcp.tool decorator for standalone execution +class mcp: + def tool(func): + return func + +# Define a common type for p-value adjustment methods +PAdjustMethod = Literal["holm", "hochberg", "hommel", "bonferroni", "BH", "BY", "fdr", "none"] + +@mcp.tool +def enrich_do( + gene_list_file: Path, + organism_db: str, + output_prefix: str, + key_type: str = "ENTREZID", + pvalue_cutoff: float = 0.05, + qvalue_cutoff: float = 0.2, + p_adjust_method: PAdjustMethod = "BH", + universe_file: Optional[Path] = None, + min_gssize: int = 10, + max_gssize: int = 500, + readable: bool = False, +) -> dict: + """ + Performs Disease Ontology (DO) enrichment analysis on a given gene list. + + This tool requires an R environment with 'DOSE', 'clusterProfiler', 'enrichplot', + and the specified organism database (e.g., 'org.Hs.eg.db') installed. + + Args: + gene_list_file: Path to a file containing a list of gene IDs, one per line. + organism_db: Name of the Bioconductor organism annotation package (e.g., "org.Hs.eg.db"). + output_prefix: Prefix for all output files (e.g., 'my_analysis/do_enrichment'). + key_type: The type of gene identifier in the input file (e.g., "ENTREZID", "SYMBOL", "ENSEMBL"). + pvalue_cutoff: Cutoff for p-value significance. + qvalue_cutoff: Cutoff for q-value (FDR) significance. + p_adjust_method: Method for p-value adjustment. + universe_file: Optional path to a file containing background gene IDs. + min_gssize: Minimum size of the gene sets to be considered. + max_gssize: Maximum size of the gene sets to be considered. + readable: If True, maps gene IDs to gene symbols in the output. + + Returns: + A dictionary containing the executed command, stdout, stderr, and paths to output files. + """ + # --- Input Validation --- + if not gene_list_file.is_file(): + raise FileNotFoundError(f"Gene list file not found: {gene_list_file}") + if universe_file and not universe_file.is_file(): + raise FileNotFoundError(f"Universe file not found: {universe_file}") + if min_gssize < 0 or max_gssize < 0 or min_gssize > max_gssize: + raise ValueError("Invalid min_gssize or max_gssize.") + if not shutil.which("Rscript"): + raise RuntimeError("Rscript not found in PATH. Please ensure R is installed and accessible.") + + output_dir = Path(output_prefix).parent + output_dir.mkdir(parents=True, exist_ok=True) + + output_files = { + "results_table": Path(f"{output_prefix}_results.csv"), + "dotplot": Path(f"{output_prefix}_dotplot.png"), + "cnetplot": Path(f"{output_prefix}_cnetplot.png"), + } + + r_script_content = f""" + # Load required libraries + suppressPackageStartupMessages(library(DOSE)) + suppressPackageStartupMessages(library(clusterProfiler)) + suppressPackageStartupMessages(library(enrichplot)) + suppressPackageStartupMessages(library(ggplot2)) + + # Check if organism DB is installed, if not, stop with an error + if (!requireNamespace("{organism_db}", quietly = TRUE)) {{ + stop("Required organism database '{organism_db}' is not installed. Please install it from Bioconductor.", call. = FALSE) + }} + library({organism_db}, character.only = TRUE) + + # Read gene list + genes <- read.table("{gene_list_file.resolve()}", header = FALSE, stringsAsFactors = FALSE)$V1 + + # Read universe if provided + universe_genes <- NULL + if (!is.null("{universe_file}")) {{ + universe_genes <- read.table("{str(universe_file.resolve()) if universe_file else ''}", header = FALSE, stringsAsFactors = FALSE)$V1 + }} + + # Run enrichment analysis + edo <- enrichDO( + gene = genes, + OrgDb = {organism_db}, + keyType = "{key_type}", + ont = "DO", + pvalueCutoff = {pvalue_cutoff}, + pAdjustMethod = "{p_adjust_method}", + universe = universe_genes, + minGSSize = {min_gssize}, + maxGSSize = {max_gssize}, + qvalueCutoff = {qvalue_cutoff}, + readable = {"TRUE" if readable else "FALSE"} + ) + + # Save results if any were found + if (!is.null(edo) && nrow(as.data.frame(edo)) > 0) {{ + write.csv(as.data.frame(edo), file = "{output_files['results_table'].resolve()}", row.names = FALSE) + + # Generate and save plots + p1 <- dotplot(edo, showCategory=30) + ggsave(p1, filename="{output_files['dotplot'].resolve()}", width=10, height=8) + + # Cnetplot requires converting gene IDs if readable is TRUE + edo_plot <- if ("{readable}" == "TRUE") setReadable(edo, OrgDb = {organism_db}, keyType="{key_type}") else edo + p2 <- cnetplot(edo_plot, categorySize="pvalue") + ggsave(p2, filename="{output_files['cnetplot'].resolve()}", width=12, height=10) + + cat("Analysis complete. Results and plots saved.\\n") + }} else {{ + cat("No significant enrichment found.\\n") + # Create an empty results file to indicate completion + file.create("{output_files['results_table'].resolve()}") + }} + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_r_script: + tmp_r_script.write(r_script_content) + r_script_path = tmp_r_script.name + + command = ["Rscript", r_script_path] + command_executed = " ".join(command) + log.info(f"Executing command: {command_executed}") + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + # Clean up temporary file + Path(r_script_path).unlink() + + # Filter out non-existent files if no results were found + final_output_files = {k: str(v) for k, v in output_files.items() if v.exists()} + + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": final_output_files, + } + except subprocess.CalledProcessError as e: + # Clean up temporary file + Path(r_script_path).unlink() + log.error(f"R script execution failed:\nSTDOUT: {e.stdout}\nSTDERR: {e.stderr}") + raise RuntimeError(f"R script failed with exit code {e.returncode}:\n{e.stderr}") from e + + +@mcp.tool +def gse_do( + ranked_gene_list_file: Path, + organism_db: str, + output_prefix: str, + key_type: str = "ENTREZID", + n_permutations: int = 1000, + min_gssize: int = 10, + max_gssize: int = 500, + pvalue_cutoff: float = 0.05, + p_adjust_method: PAdjustMethod = "BH", + verbose: bool = True, + seed: bool = False, +) -> dict: + """ + Performs Gene Set Enrichment Analysis (GSEA) on Disease Ontology (DO). + + This tool requires an R environment with 'DOSE', 'clusterProfiler', 'enrichplot', + and the specified organism database (e.g., 'org.Hs.eg.db') installed. + + Args: + ranked_gene_list_file: Path to a two-column file (GeneID, Score/FoldChange) without a header. + organism_db: Name of the Bioconductor organism annotation package (e.g., "org.Hs.eg.db"). + output_prefix: Prefix for all output files. + key_type: The type of gene identifier in the input file. + n_permutations: Number of permutations for GSEA. + min_gssize: Minimum size of the gene sets to be considered. + max_gssize: Maximum size of the gene sets to be considered. + pvalue_cutoff: Cutoff for p-value significance. + p_adjust_method: Method for p-value adjustment. + verbose: If True, prints progress messages. + seed: If True, sets a random seed for reproducibility. + + Returns: + A dictionary containing the executed command, stdout, stderr, and paths to output files. + """ + # --- Input Validation --- + if not ranked_gene_list_file.is_file(): + raise FileNotFoundError(f"Ranked gene list file not found: {ranked_gene_list_file}") + if n_permutations <= 0: + raise ValueError("Number of permutations must be positive.") + if not shutil.which("Rscript"): + raise RuntimeError("Rscript not found in PATH. Please ensure R is installed and accessible.") + + output_dir = Path(output_prefix).parent + output_dir.mkdir(parents=True, exist_ok=True) + + output_files = { + "results_table": Path(f"{output_prefix}_results.csv"), + "gseaplot": Path(f"{output_prefix}_gseaplot.png"), + "ridgeplot": Path(f"{output_prefix}_ridgeplot.png"), + } + + r_script_content = f""" + suppressPackageStartupMessages(library(DOSE)) + suppressPackageStartupMessages(library(clusterProfiler)) + suppressPackageStartupMessages(library(enrichplot)) + suppressPackageStartupMessages(library(ggplot2)) + + if (!requireNamespace("{organism_db}", quietly = TRUE)) {{ + stop("Required organism database '{organism_db}' is not installed.", call. = FALSE) + }} + library({organism_db}, character.only = TRUE) + + # Read and prepare ranked gene list + df <- read.table("{ranked_gene_list_file.resolve()}", header = FALSE, col.names = c("ID", "Score")) + geneList <- df$Score + names(geneList) <- as.character(df$ID) + geneList <- sort(geneList, decreasing = TRUE) + + # Run GSEA + gse <- gseDO( + geneList = geneList, + OrgDb = {organism_db}, + keyType = "{key_type}", + nPerm = {n_permutations}, + minGSSize = {min_gssize}, + maxGSSize = {max_gssize}, + pvalueCutoff = {pvalue_cutoff}, + pAdjustMethod = "{p_adjust_method}", + verbose = {"TRUE" if verbose else "FALSE"}, + seed = {"TRUE" if seed else "FALSE"} + ) + + if (!is.null(gse) && nrow(as.data.frame(gse)) > 0) {{ + write.csv(as.data.frame(gse), file = "{output_files['results_table'].resolve()}", row.names = FALSE) + + # Generate and save plots + # Get the top term ID for the GSEA plot + top_term_id <- as.data.frame(gse)[1, "ID"] + p1 <- gseaplot(gse, geneSetID = top_term_id, title = gse[top_term_id, "Description"]) + ggsave(p1, filename="{output_files['gseaplot'].resolve()}", width=10, height=8) + + p2 <- ridgeplot(gse) + ggsave(p2, filename="{output_files['ridgeplot'].resolve()}", width=12, height=10) + + cat("GSEA complete. Results and plots saved.\\n") + }} else {{ + cat("No significant GSEA results found.\\n") + file.create("{output_files['results_table'].resolve()}") + }} + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_r_script: + tmp_r_script.write(r_script_content) + r_script_path = tmp_r_script.name + + command = ["Rscript", r_script_path] + command_executed = " ".join(command) + log.info(f"Executing command: {command_executed}") + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + Path(r_script_path).unlink() + final_output_files = {k: str(v) for k, v in output_files.items() if v.exists()} + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": final_output_files, + } + except subprocess.CalledProcessError as e: + Path(r_script_path).unlink() + log.error(f"R script execution failed:\nSTDOUT: {e.stdout}\nSTDERR: {e.stderr}") + raise RuntimeError(f"R script failed with exit code {e.returncode}:\n{e.stderr}") from e + + +@mcp.tool +def enrich_ncg( + gene_list_file: Path, + output_prefix: str, + pvalue_cutoff: float = 0.05, + qvalue_cutoff: float = 0.2, + p_adjust_method: PAdjustMethod = "BH", + universe_file: Optional[Path] = None, + min_gssize: int = 10, + max_gssize: int = 500, + readable: bool = False, +) -> dict: + """ + Performs Network of Cancer Genes (NCG) enrichment analysis. + + This tool requires an R environment with 'DOSE' and 'clusterProfiler' installed. + It uses built-in NCG data, so an organism DB is not required. Gene IDs must be Entrez IDs. + + Args: + gene_list_file: Path to a file containing a list of Entrez gene IDs, one per line. + output_prefix: Prefix for all output files. + pvalue_cutoff: Cutoff for p-value significance. + qvalue_cutoff: Cutoff for q-value (FDR) significance. + p_adjust_method: Method for p-value adjustment. + universe_file: Optional path to a file containing background gene IDs. + min_gssize: Minimum size of the gene sets to be considered. + max_gssize: Maximum size of the gene sets to be considered. + readable: If True, maps gene IDs to gene symbols. Requires 'org.Hs.eg.db'. + + Returns: + A dictionary containing the executed command, stdout, stderr, and paths to output files. + """ + # --- Input Validation --- + if not gene_list_file.is_file(): + raise FileNotFoundError(f"Gene list file not found: {gene_list_file}") + if universe_file and not universe_file.is_file(): + raise FileNotFoundError(f"Universe file not found: {universe_file}") + if not shutil.which("Rscript"): + raise RuntimeError("Rscript not found in PATH. Please ensure R is installed and accessible.") + + output_dir = Path(output_prefix).parent + output_dir.mkdir(parents=True, exist_ok=True) + + output_files = { + "results_table": Path(f"{output_prefix}_results.csv"), + "dotplot": Path(f"{output_prefix}_dotplot.png"), + } + + readable_setup = "" + if readable: + readable_setup = """ + if (!requireNamespace("org.Hs.eg.db", quietly = TRUE)) { + stop("The 'readable=TRUE' option requires 'org.Hs.eg.db'. Please install it from Bioconductor.", call. = FALSE) + } + library(org.Hs.eg.db) + """ + + r_script_content = f""" + suppressPackageStartupMessages(library(DOSE)) + suppressPackageStartupMessages(library(clusterProfiler)) + suppressPackageStartupMessages(library(enrichplot)) + suppressPackageStartupMessages(library(ggplot2)) + {readable_setup} + + genes <- read.table("{gene_list_file.resolve()}", header = FALSE, stringsAsFactors = FALSE)$V1 + + universe_genes <- NULL + if (!is.null("{universe_file}")) {{ + universe_genes <- read.table("{str(universe_file.resolve()) if universe_file else ''}", header = FALSE, stringsAsFactors = FALSE)$V1 + }} + + encg <- enrichNCG( + gene = genes, + pvalueCutoff = {pvalue_cutoff}, + pAdjustMethod = "{p_adjust_method}", + universe = universe_genes, + minGSSize = {min_gssize}, + maxGSSize = {max_gssize}, + qvalueCutoff = {qvalue_cutoff}, + readable = {"TRUE" if readable else "FALSE"} + ) + + if (!is.null(encg) && nrow(as.data.frame(encg)) > 0) {{ + write.csv(as.data.frame(encg), file = "{output_files['results_table'].resolve()}", row.names = FALSE) + p1 <- dotplot(encg, showCategory=30) + ggsave(p1, filename="{output_files['dotplot'].resolve()}", width=10, height=8) + cat("NCG enrichment complete.\\n") + }} else {{ + cat("No significant NCG enrichment found.\\n") + file.create("{output_files['results_table'].resolve()}") + }} + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_r_script: + tmp_r_script.write(r_script_content) + r_script_path = tmp_r_script.name + + command = ["Rscript", r_script_path] + command_executed = " ".join(command) + log.info(f"Executing command: {command_executed}") + + try: + process = subprocess.run(command, capture_output=True, text=True, check=True) + Path(r_script_path).unlink() + final_output_files = {k: str(v) for k, v in output_files.items() if v.exists()} + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": final_output_files, + } + except subprocess.CalledProcessError as e: + Path(r_script_path).unlink() + log.error(f"R script execution failed:\nSTDOUT: {e.stdout}\nSTDERR: {e.stderr}") + raise RuntimeError(f"R script failed with exit code {e.returncode}:\n{e.stderr}") from e + + +@mcp.tool +def gse_ncg( + ranked_gene_list_file: Path, + output_prefix: str, + n_permutations: int = 1000, + min_gssize: int = 10, + max_gssize: int = 500, + pvalue_cutoff: float = 0.05, + p_adjust_method: PAdjustMethod = "BH", + verbose: bool = True, + seed: bool = False, +) -> dict: + """ + Performs Gene Set Enrichment Analysis (GSEA) on Network of Cancer Genes (NCG). + + This tool requires an R environment with 'DOSE' and 'clusterProfiler' installed. + Gene IDs must be Entrez IDs. + + Args: + ranked_gene_list_file: Path to a two-column file (EntrezID, Score/FoldChange) without a header. + output_prefix: Prefix for all output files. + n_permutations: Number of permutations for GSEA. + min_gssize: Minimum size of the gene sets to be considered. + max_gssize: Maximum size of the gene sets to be considered. + pvalue_cutoff: Cutoff for p-value significance. + p_adjust_method: Method for p-value adjustment. + verbose: If True, prints progress messages. + seed: If True, sets a random seed for reproducibility. + + Returns: + A dictionary containing the executed command, stdout, stderr, and paths to output files. + """ + # --- Input Validation --- + if not ranked_gene_list_file.is_file(): + raise FileNotFoundError(f"Ranked gene list file not found: {ranked_gene_list_file}") + if not shutil.which("Rscript"): + raise RuntimeError("Rscript not found in PATH. Please ensure R is installed and accessible.") + + output_dir = Path(output_prefix).parent + output_dir.mkdir(parents=True, exist_ok=True) + + output_files = { + "results_table": Path(f"{output_prefix}_results.csv"), + "ridgeplot": Path(f"{output_prefix}_ridgeplot.png"), + } + + r_script_content = f""" + suppressPackageStartupMessages(library(DOSE)) + suppressPackageStartupMessages(library(clusterProfiler)) + suppressPackageStartupMessages(library(enrichplot)) + suppressPackageStartupMessages(library(ggplot2)) + + df <- read.table("{ranked_gene_list_file.resolve()}", header = FALSE, col.names = c("ID", "Score")) + geneList <- df$Score + names(geneList) <- as.character(df$ID) + geneList <- sort(geneList, decreasing = TRUE) + + gse <- gseNCG( + geneList = geneList, + nPerm = {n_permutations}, + minGSSize = {min_gssize}, + maxGSSize = {max_gssize}, + pvalueCutoff = {pvalue_cutoff}, + pAdjustMethod = "{p_adjust_method}", + verbose = {"TRUE" if verbose else "FALSE"}, + seed = {"TRUE" if seed else "FALSE"} + ) + + if (!is.null(gse) && nrow(as.data.frame(gse)) > 0) {{ + write.csv(as.data.frame(gse), file = "{output_files['results_table'].resolve()}", row.names = FALSE) + p1 <- ridgeplot(gse) + ggsave(p1, filename="{output_files['ridgeplot'].resolve()}", width=12, height=10) + cat("NCG GSEA complete.\\n") + }} else {{ + cat("No significant NCG GSEA results found.\\n") + file.create("{output_files['results_table'].resolve()}") + }} + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_r_script: + tmp_r_script.write(r_script_content) + r_script_path = tmp_r_script.name + + command = ["Rscript", r_script_path] + command_executed = " ".join(command) + log.info(f"Executing command: {command_executed}") + + try: + process = subprocess.run(command, capture_output=True, text=True, check=True) + Path(r_script_path).unlink() + final_output_files = {k: str(v) for k, v in output_files.items() if v.exists()} + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": final_output_files, + } + except subprocess.CalledProcessError as e: + Path(r_script_path).unlink() + log.error(f"R script execution failed:\nSTDOUT: {e.stdout}\nSTDERR: {e.stderr}") + raise RuntimeError(f"R script failed with exit code {e.returncode}:\n{e.stderr}") from e + + +@mcp.tool +def enrich_dgn( + gene_list_file: Path, + output_prefix: str, + pvalue_cutoff: float = 0.05, + qvalue_cutoff: float = 0.2, + p_adjust_method: PAdjustMethod = "BH", + universe_file: Optional[Path] = None, + min_gssize: int = 10, + max_gssize: int = 500, + readable: bool = False, +) -> dict: + """ + Performs DisGeNET enrichment analysis. + + This tool requires an R environment with 'DOSE' and 'clusterProfiler' installed. + Gene IDs must be Entrez IDs. + + Args: + gene_list_file: Path to a file containing a list of Entrez gene IDs, one per line. + output_prefix: Prefix for all output files. + pvalue_cutoff: Cutoff for p-value significance. + qvalue_cutoff: Cutoff for q-value (FDR) significance. + p_adjust_method: Method for p-value adjustment. + universe_file: Optional path to a file containing background gene IDs. + min_gssize: Minimum size of the gene sets to be considered. + max_gssize: Maximum size of the gene sets to be considered. + readable: If True, maps gene IDs to gene symbols. Requires 'org.Hs.eg.db'. + + Returns: + A dictionary containing the executed command, stdout, stderr, and paths to output files. + """ + # --- Input Validation --- + if not gene_list_file.is_file(): + raise FileNotFoundError(f"Gene list file not found: {gene_list_file}") + if universe_file and not universe_file.is_file(): + raise FileNotFoundError(f"Universe file not found: {universe_file}") + if not shutil.which("Rscript"): + raise RuntimeError("Rscript not found in PATH. Please ensure R is installed and accessible.") + + output_dir = Path(output_prefix).parent + output_dir.mkdir(parents=True, exist_ok=True) + + output_files = { + "results_table": Path(f"{output_prefix}_results.csv"), + "dotplot": Path(f"{output_prefix}_dotplot.png"), + } + + readable_setup = "" + if readable: + readable_setup = """ + if (!requireNamespace("org.Hs.eg.db", quietly = TRUE)) { + stop("The 'readable=TRUE' option requires 'org.Hs.eg.db'. Please install it from Bioconductor.", call. = FALSE) + } + library(org.Hs.eg.db) + """ + + r_script_content = f""" + suppressPackageStartupMessages(library(DOSE)) + suppressPackageStartupMessages(library(clusterProfiler)) + suppressPackageStartupMessages(library(enrichplot)) + suppressPackageStartupMessages(library(ggplot2)) + {readable_setup} + + genes <- read.table("{gene_list_file.resolve()}", header = FALSE, stringsAsFactors = FALSE)$V1 + + universe_genes <- NULL + if (!is.null("{universe_file}")) {{ + universe_genes <- read.table("{str(universe_file.resolve()) if universe_file else ''}", header = FALSE, stringsAsFactors = FALSE)$V1 + }} + + edgn <- enrichDGN( + gene = genes, + pvalueCutoff = {pvalue_cutoff}, + pAdjustMethod = "{p_adjust_method}", + universe = universe_genes, + minGSSize = {min_gssize}, + maxGSSize = {max_gssize}, + qvalueCutoff = {qvalue_cutoff}, + readable = {"TRUE" if readable else "FALSE"} + ) + + if (!is.null(edgn) && nrow(as.data.frame(edgn)) > 0) {{ + write.csv(as.data.frame(edgn), file = "{output_files['results_table'].resolve()}", row.names = FALSE) + p1 <- dotplot(edgn, showCategory=30) + ggsave(p1, filename="{output_files['dotplot'].resolve()}", width=10, height=8) + cat("DisGeNET enrichment complete.\\n") + }} else {{ + cat("No significant DisGeNET enrichment found.\\n") + file.create("{output_files['results_table'].resolve()}") + }} + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_r_script: + tmp_r_script.write(r_script_content) + r_script_path = tmp_r_script.name + + command = ["Rscript", r_script_path] + command_executed = " ".join(command) + log.info(f"Executing command: {command_executed}") + + try: + process = subprocess.run(command, capture_output=True, text=True, check=True) + Path(r_script_path).unlink() + final_output_files = {k: str(v) for k, v in output_files.items() if v.exists()} + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": final_output_files, + } + except subprocess.CalledProcessError as e: + Path(r_script_path).unlink() + log.error(f"R script execution failed:\nSTDOUT: {e.stdout}\nSTDERR: {e.stderr}") + raise RuntimeError(f"R script failed with exit code {e.returncode}:\n{e.stderr}") from e + + +@mcp.tool +def gse_dgn( + ranked_gene_list_file: Path, + output_prefix: str, + n_permutations: int = 1000, + min_gssize: int = 10, + max_gssize: int = 500, + pvalue_cutoff: float = 0.05, + p_adjust_method: PAdjustMethod = "BH", + verbose: bool = True, + seed: bool = False, +) -> dict: + """ + Performs Gene Set Enrichment Analysis (GSEA) on DisGeNET. + + This tool requires an R environment with 'DOSE' and 'clusterProfiler' installed. + Gene IDs must be Entrez IDs. + + Args: + ranked_gene_list_file: Path to a two-column file (EntrezID, Score/FoldChange) without a header. + output_prefix: Prefix for all output files. + n_permutations: Number of permutations for GSEA. + min_gssize: Minimum size of the gene sets to be considered. + max_gssize: Maximum size of the gene sets to be considered. + pvalue_cutoff: Cutoff for p-value significance. + p_adjust_method: Method for p-value adjustment. + verbose: If True, prints progress messages. + seed: If True, sets a random seed for reproducibility. + + Returns: + A dictionary containing the executed command, stdout, stderr, and paths to output files. + """ + # --- Input Validation --- + if not ranked_gene_list_file.is_file(): + raise FileNotFoundError(f"Ranked gene list file not found: {ranked_gene_list_file}") + if not shutil.which("Rscript"): + raise RuntimeError("Rscript not found in PATH. Please ensure R is installed and accessible.") + + output_dir = Path(output_prefix).parent + output_dir.mkdir(parents=True, exist_ok=True) + + output_files = { + "results_table": Path(f"{output_prefix}_results.csv"), + "ridgeplot": Path(f"{output_prefix}_ridgeplot.png"), + } + + r_script_content = f""" + suppressPackageStartupMessages(library(DOSE)) + suppressPackageStartupMessages(library(clusterProfiler)) + suppressPackageStartupMessages(library(enrichplot)) + suppressPackageStartupMessages(library(ggplot2)) + + df <- read.table("{ranked_gene_list_file.resolve()}", header = FALSE, col.names = c("ID", "Score")) + geneList <- df$Score + names(geneList) <- as.character(df$ID) + geneList <- sort(geneList, decreasing = TRUE) + + gse <- gseDGN( + geneList = geneList, + nPerm = {n_permutations}, + minGSSize = {min_gssize}, + maxGSSize = {max_gssize}, + pvalueCutoff = {pvalue_cutoff}, + pAdjustMethod = "{p_adjust_method}", + verbose = {"TRUE" if verbose else "FALSE"}, + seed = {"TRUE" if seed else "FALSE"} + ) + + if (!is.null(gse) && nrow(as.data.frame(gse)) > 0) {{ + write.csv(as.data.frame(gse), file = "{output_files['results_table'].resolve()}", row.names = FALSE) + p1 <- ridgeplot(gse) + ggsave(p1, filename="{output_files['ridgeplot'].resolve()}", width=12, height=10) + cat("DisGeNET GSEA complete.\\n") + }} else {{ + cat("No significant DisGeNET GSEA results found.\\n") + file.create("{output_files['results_table'].resolve()}") + }} + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_r_script: + tmp_r_script.write(r_script_content) + r_script_path = tmp_r_script.name + + command = ["Rscript", r_script_path] + command_executed = " ".join(command) + log.info(f"Executing command: {command_executed}") + + try: + process = subprocess.run(command, capture_output=True, text=True, check=True) + Path(r_script_path).unlink() + final_output_files = {k: str(v) for k, v in output_files.items() if v.exists()} + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": final_output_files, + } + except subprocess.CalledProcessError as e: + Path(r_script_path).unlink() + log.error(f"R script execution failed:\nSTDOUT: {e.stdout}\nSTDERR: {e.stderr}") + raise RuntimeError(f"R script failed with exit code {e.returncode}:\n{e.stderr}") from e \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/app/bioconductor-dose_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/app/bioconductor-dose_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5b38cb980a208fe3dd5347283fc0c0f704b85c72 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/app/bioconductor-dose_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_manual_txt/mcp_bioconductor-dose/app/bioconductor-dose_server.py') +SERVER_NAME = 'biosci_bioconductor_dose' + + +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_manual_txt/mcp_bioconductor-dose/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..376316817b1839f8e71282772f7841fad3c91011 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-dose: + build: . + image: mcp-bioconductor-dose:latest + container_name: mcp-bioconductor-dose + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-dose + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3c620138711796e54adfe97dd442b9b327e07163 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-dose + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ebseq/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ebseq/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ebseq/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..afa6508a4a79e041e41e6dba488188175d2bf18b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-edger via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-edger -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-edger_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-edger_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-edger_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/app/bioconductor-edger_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/app/bioconductor-edger_server.py new file mode 100644 index 0000000000000000000000000000000000000000..332f526b57fd69c80e8fa5ac66fe22bdca59ce45 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/app/bioconductor-edger_server.py @@ -0,0 +1,236 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional + +# Assume @mcp.tool() is defined in the execution environment. +# No import is needed as per the instructions. + + +@mcp.tool() +def run_edger_de( + counts_file: Path, + samples_file: Path, + output_file: Path, + contrast: str, + group_column: str, + gene_id_column: Optional[str] = None, + min_cpm: float = 1.0, + min_samples_fraction: float = 0.5, + normalization_method: str = "TMM", + test_method: str = "glmQLFTest", + fdr_cutoff: float = 0.05, + r_executable: str = "Rscript", +) -> dict: + """ + Performs differential expression analysis on RNA-seq count data using edgeR. + + This tool wraps a standard edgeR workflow, including data loading, filtering of + lowly-expressed genes, TMM normalization, dispersion estimation, model fitting, + and hypothesis testing using either the quasi-likelihood F-test (glmQLFTest), + the likelihood ratio test (glmLRT), or the exact test. + + Args: + counts_file: Path to the input count matrix file (tab-separated). + Rows should be genes and columns should be samples. + samples_file: Path to the sample metadata file (tab-separated). + Must contain a column mapping samples to experimental groups. + The first column should contain sample names matching the + count matrix headers. + output_file: Path for the output results table (tab-separated). + contrast: The contrast to be tested, in the format 'GroupA-GroupB'. + group_column: The name of the column in the samples_file that contains + the experimental group information. + gene_id_column: The name of the column in the counts_file that contains + gene identifiers. If not provided, the first column is used. + min_cpm: The minimum counts-per-million (CPM) a gene must have to be + considered expressed. Used for filtering. + min_samples_fraction: The minimum fraction of samples within the smallest + group where a gene must have a CPM > min_cpm to be kept. + normalization_method: Normalization method to be used. + Options: "TMM", "TMMwsp", "RLE", "upperquartile", "none". + test_method: The statistical test to use for differential expression. + Options: "glmQLFTest", "glmLRT", "exactTest". + fdr_cutoff: The false discovery rate (FDR) threshold for reporting results. + r_executable: The command to execute Rscript. Defaults to 'Rscript'. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list + of output file paths. + """ + # --- 1. Input Validation --- + if not counts_file.is_file(): + raise FileNotFoundError(f"Counts file not found: {counts_file}") + if not samples_file.is_file(): + raise FileNotFoundError(f"Samples metadata file not found: {samples_file}") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + allowed_norm = ["TMM", "TMMwsp", "RLE", "upperquartile", "none"] + if normalization_method not in allowed_norm: + raise ValueError( + f"Invalid normalization_method '{normalization_method}'. Must be one of {allowed_norm}" + ) + + allowed_tests = ["glmQLFTest", "glmLRT", "exactTest"] + if test_method not in allowed_tests: + raise ValueError( + f"Invalid test_method '{test_method}'. Must be one of {allowed_tests}" + ) + + if not (0 <= fdr_cutoff <= 1): + raise ValueError("fdr_cutoff must be between 0 and 1.") + if not (0 <= min_samples_fraction <= 1): + raise ValueError("min_samples_fraction must be between 0 and 1.") + if min_cpm < 0: + raise ValueError("min_cpm must be non-negative.") + + if "-" not in contrast or len(contrast.split("-")) != 2: + raise ValueError("Contrast must be in the format 'GroupA-GroupB'.") + + # --- 2. Generate R Script --- + r_script_content = f""" + # Load necessary library + if (!requireNamespace("edgeR", quietly = TRUE)) {{ + stop("The 'edgeR' package is not installed. Please install it from Bioconductor.") + }} + library(edgeR) + + # --- Arguments from Python --- + counts_file_path <- "{counts_file.resolve()}" + samples_file_path <- "{samples_file.resolve()}" + output_file_path <- "{output_file.resolve()}" + group_col <- "{group_column}" + contrast_str <- "{contrast}" + gene_id_col <- {f'"{gene_id_column}"' if gene_id_column else '1'} + min_cpm_val <- {min_cpm} + min_samples_frac <- {min_samples_fraction} + norm_method <- "{normalization_method}" + test_method <- "{test_method}" + fdr_val <- {fdr_cutoff} + + # --- Data Loading --- + cat("Reading counts data from:", counts_file_path, "\\n") + counts_data <- read.delim(counts_file_path, row.names = gene_id_col, check.names = FALSE, stringsAsFactors = FALSE) + + cat("Reading sample metadata from:", samples_file_path, "\\n") + sample_info <- read.delim(samples_file_path, row.names = 1, check.names = FALSE, stringsAsFactors = FALSE) + + # Ensure sample order matches between counts and metadata + if (!all(colnames(counts_data) %in% rownames(sample_info))) {{ + stop("Mismatch: Some column names in the counts file are not present as row names in the samples file.") + }} + sample_info <- sample_info[colnames(counts_data), , drop = FALSE] + + # --- DGEList Object Creation --- + cat("Creating DGEList object...\\n") + group <- factor(sample_info[[group_col]]) + dge <- DGEList(counts = counts_data, group = group) + + # --- Filtering --- + cat("Filtering low-expressed genes...\\n") + min_samples_in_smallest_group <- min(table(group)) + min_samples <- floor(min_samples_frac * min_samples_in_smallest_group) + if (min_samples < 1) {{ + min_samples <- 1 # At least one sample + }} + cat("Keeping genes with CPM >", min_cpm_val, "in at least", min_samples, "samples.\\n") + keep <- rowSums(cpm(dge) > min_cpm_val) >= min_samples + dge <- dge[keep, , keep.lib.sizes = FALSE] + + # --- Normalization --- + cat("Calculating normalization factors using method:", norm_method, "\\n") + dge <- calcNormFactors(dge, method = norm_method) + + # --- Model Fitting and Testing --- + if (test_method == "exactTest") {{ + if (nlevels(group) != 2) {{ + stop("exactTest can only be used for two-group comparisons.") + }} + cat("Estimating dispersion for exactTest...\\n") + dge <- estimateDisp(dge) + + cat("Performing exact test...\\n") + et <- exactTest(dge) + + cat("Extracting top tags...\\n") + results_table <- topTags(et, n = Inf, adjust.method = "BH", sort.by = "PValue")$table + + }} else {{ # GLM approach + cat("Setting up design matrix...\\n") + design <- model.matrix(~ 0 + group) + colnames(design) <- make.names(levels(group)) + + cat("Estimating GLM dispersions...\\n") + dge <- estimateDisp(dge, design, robust=TRUE) + + if (test_method == "glmLRT") {{ + cat("Fitting GLM model (glmLRT)...\\n") + fit <- glmFit(dge, design) + + cat("Performing Likelihood Ratio Test...\\n") + contr <- makeContrasts(contrasts = contrast_str, levels = design) + lrt <- glmLRT(fit, contrast = contr) + + cat("Extracting top tags...\\n") + results_table <- topTags(lrt, n = Inf, adjust.method = "BH", sort.by = "PValue")$table + + }} else {{ # glmQLFTest is the default + cat("Fitting GLM model (glmQLFTest)...\\n") + fit <- glmQLFit(dge, design, robust=TRUE) + + cat("Performing Quasi-Likelihood F-Test...\\n") + contr <- makeContrasts(contrasts = contrast_str, levels = design) + qlf <- glmQLFTest(fit, contrast = contr) + + cat("Extracting top tags...\\n") + results_table <- topTags(qlf, n = Inf, adjust.method = "BH", sort.by = "PValue")$table + }} + }} + + # Add gene IDs back as a column for clarity + results_table <- cbind(GeneID = rownames(results_table), results_table) + + # --- Writing Output --- + cat("Writing results with FDR <", fdr_val, "to:", output_file_path, "\\n") + final_results <- subset(results_table, FDR < fdr_val) + write.table(final_results, file = output_file_path, sep = "\\t", quote = FALSE, row.names = FALSE) + + cat("edgeR analysis complete.\\n") + """ + + # --- 3. Subprocess Execution --- + with tempfile.NamedTemporaryFile( + mode="w", delete=False, suffix=".R", encoding="utf-8" + ) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = r_script_file.name + + command = [r_executable, r_script_path] + command_str = " ".join(map(str, command)) + + try: + result = subprocess.run( + command, capture_output=True, text=True, check=True, encoding="utf-8" + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file.resolve())], + } + except FileNotFoundError: + raise RuntimeError( + f"Rscript executable not found at '{r_executable}'. Please ensure R is installed and in your system's PATH." + ) + except subprocess.CalledProcessError as e: + error_message = ( + f"edgeR R script failed with exit code {e.returncode}.\n" + f"COMMAND: {command_str}\n" + f"STDOUT:\n{e.stdout}\n" + f"STDERR:\n{e.stderr}\n" + ) + raise RuntimeError(error_message) + finally: + # Ensure temporary file is always cleaned up + Path(r_script_path).unlink() diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/app/bioconductor-edger_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/app/bioconductor-edger_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b111bfb8d23a113afbd33bd21f518bc0e6451079 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/app/bioconductor-edger_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_manual_txt/mcp_bioconductor-edger/app/bioconductor-edger_server.py') +SERVER_NAME = 'biosci_bioconductor_edger' + + +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_manual_txt/mcp_bioconductor-edger/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..3c2d48e4be4ae96adc8e3d2a236e22da2a3d7e41 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-edger: + build: . + image: mcp-bioconductor-edger:latest + container_name: mcp-bioconductor-edger + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-edger + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6dc7924789c820fb39041415eb915f5b2f3558e6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-edger + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9b0f11efd1181364a6ae2124d61ec7bc886f56fb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-ensembldb via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-ensembldb -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-ensembldb_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-ensembldb_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-ensembldb_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/app/bioconductor-ensembldb_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/app/bioconductor-ensembldb_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b16aa3887d89f6af557937f4480a2a8aa12f8734 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/app/bioconductor-ensembldb_server.py @@ -0,0 +1,433 @@ +import subprocess +import tempfile +import textwrap +from pathlib import Path +from typing import Optional, List, Dict, Any + +# Assume mcp.tool is imported from a framework library +class mcp: + def tool(func): + return func + +def _run_r_script(r_script_content: str, args: List[str]) -> Dict[str, Any]: + """ + A helper function to execute an R script using Rscript, handling errors. + + This function requires that R and the required Bioconductor packages + (e.g., ensembldb, AnnotationFilter) are installed in the execution environment. + + Args: + r_script_content: A string containing the R code to execute. + args: A list of command-line arguments for the R script. + + Returns: + A dictionary containing the executed command, stdout, and stderr. + + Raises: + RuntimeError: If Rscript is not found in the system's PATH. + subprocess.CalledProcessError: If the R script execution fails. + """ + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, encoding='utf-8') as tmp_script: + script_path = Path(tmp_script.name) + tmp_script.write(r_script_content) + + command = ["Rscript", str(script_path)] + args + + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + encoding='utf-8' + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + error_message = ( + f"R script execution failed with exit code {e.returncode}.\n" + f"Command: {' '.join(e.cmd)}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) + # Re-raise with a more informative stderr + raise subprocess.CalledProcessError(e.returncode, e.cmd, output=e.stdout, stderr=error_message) + finally: + if 'script_path' in locals() and script_path.exists(): + script_path.unlink() + +@mcp.tool +def create_ensdb_from_gtf( + gtf_file: Path, + output_db: Path, + organism: str, + genome_version: str, + ensembl_version: str, +) -> Dict[str, Any]: + """ + Creates an EnsemblDB SQLite database from a GTF file. + + This tool wraps the `ensDbFromGtf` function from the R/Bioconductor + package 'ensembldb'. It requires R and the 'ensembldb' package to be + installed in the environment. + + Args: + gtf_file: Path to the input GTF file. + output_db: Path for the output SQLite database file. + organism: Name of the organism (e.g., 'Homo_sapiens'). + genome_version: Genome build version (e.g., 'GRCh38'). + ensembl_version: Ensembl release version (e.g., '104'). + + Returns: + A dictionary containing the command executed, stdout, stderr, + and a list of output files. + """ + # Input validation + if not gtf_file.is_file(): + raise FileNotFoundError(f"Input GTF file not found: {gtf_file}") + if not output_db.parent.is_dir(): + raise NotADirectoryError(f"Output directory does not exist: {output_db.parent}") + if not all([organism, genome_version, ensembl_version]): + raise ValueError("organism, genome_version, and ensembl_version must be non-empty strings.") + + r_script = textwrap.dedent(""" + library("ensembldb") + args <- commandArgs(trailingOnly = TRUE) + ensDbFromGtf( + gtf = args[1], + outfile = args[2], + organism = args[3], + genomeVersion = args[4], + version = args[5] + ) + """) + + args = [ + str(gtf_file), + str(output_db), + organism, + genome_version, + ensembl_version + ] + + result = _run_r_script(r_script, args) + result["output_files"] = [str(output_db)] + return result + +@mcp.tool +def create_ensdb_from_gff( + gff_file: Path, + output_db: Path, + organism: str, + genome_version: str, + ensembl_version: str, +) -> Dict[str, Any]: + """ + Creates an EnsemblDB SQLite database from a GFF3 file. + + This tool wraps the `ensDbFromGff` function from the R/Bioconductor + package 'ensembldb'. It requires R and the 'ensembldb' package to be + installed in the environment. + + Args: + gff_file: Path to the input GFF3 file. + output_db: Path for the output SQLite database file. + organism: Name of the organism (e.g., 'Homo_sapiens'). + genome_version: Genome build version (e.g., 'GRCh38'). + ensembl_version: Ensembl release version (e.g., '104'). + + Returns: + A dictionary containing the command executed, stdout, stderr, + and a list of output files. + """ + # Input validation + if not gff_file.is_file(): + raise FileNotFoundError(f"Input GFF file not found: {gff_file}") + if not output_db.parent.is_dir(): + raise NotADirectoryError(f"Output directory does not exist: {output_db.parent}") + if not all([organism, genome_version, ensembl_version]): + raise ValueError("organism, genome_version, and ensembl_version must be non-empty strings.") + + r_script = textwrap.dedent(""" + library("ensembldb") + args <- commandArgs(trailingOnly = TRUE) + ensDbFromGff( + gff = args[1], + outfile = args[2], + organism = args[3], + genomeVersion = args[4], + version = args[5] + ) + """) + + args = [ + str(gff_file), + str(output_db), + organism, + genome_version, + ensembl_version + ] + + result = _run_r_script(r_script, args) + result["output_files"] = [str(output_db)] + return result + +def _build_query_script(query_function: str, extra_r_code: str = "") -> str: + """Helper to generate the R script for various query types.""" + return textwrap.dedent(f""" + library("ensembldb") + library("AnnotationFilter") + + args <- commandArgs(trailingOnly = TRUE) + + parse_args <- function(args) {{ + params <- list() + for (arg in args) {{ + if (startsWith(arg, "--")) {{ + parts <- strsplit(substring(arg, 3), "=", fixed = TRUE)[[1]] + key <- parts[1] + value <- if (length(parts) > 1) parts[2] else TRUE + params[[key]] <- value + }} + }} + return(params) + }} + + params <- parse_args(args) + + if (is.null(params$db) || is.null(params$outfile)) {{ + stop("Both --db and --outfile arguments are required.") + }} + + edb <- EnsDb(params$db) + + filter_list <- list() + if (!is.null(params$filter_gene_id)) {{ + filter_list <- c(filter_list, GeneIdFilter(params$filter_gene_id)) + }} + if (!is.null(params$filter_gene_biotype)) {{ + filter_list <- c(filter_list, GeneBiotypeFilter(params$filter_gene_biotype)) + }} + if (!is.null(params$filter_seq_name)) {{ + filter_list <- c(filter_list, SeqNameFilter(params$filter_seq_name)) + }} + if (!is.null(params$filter_tx_id)) {{ + filter_list <- c(filter_list, TxIdFilter(params$filter_tx_id)) + }} + if (!is.null(params$filter_tx_biotype)) {{ + filter_list <- c(filter_list, TxBiotypeFilter(params$filter_tx_biotype)) + }} + if (!is.null(params$filter_exon_id)) {{ + filter_list <- c(filter_list, ExonIdFilter(params$filter_exon_id)) + }} + + final_filter <- NULL + if (length(filter_list) > 0) {{ + final_filter <- AnnotationFilterList(filter_list, logicOp = "&") + }} + + {extra_r_code} + + results <- {query_function}(edb, filter = final_filter) + + write.table(as.data.frame(results), file = params$outfile, sep = "\t", row.names = FALSE, quote = FALSE) + + cat("Successfully wrote query results to:", params$outfile, "\n") + """) + +@mcp.tool +def query_genes( + db_file: Path, + output_tsv: Path, + filter_gene_id: Optional[str] = None, + filter_gene_biotype: Optional[str] = None, + filter_seq_name: Optional[str] = None, +) -> Dict[str, Any]: + """ + Queries gene information from an EnsemblDB SQLite database. + + This tool wraps the `genes` function from 'ensembldb'. It requires R, + 'ensembldb', and 'AnnotationFilter' packages. + + Args: + db_file: Path to the input EnsemblDB SQLite file. + output_tsv: Path for the output TSV file. + filter_gene_id: Optional filter by Ensembl gene ID. + filter_gene_biotype: Optional filter by gene biotype (e.g., 'protein_coding'). + filter_seq_name: Optional filter by sequence/chromosome name (e.g., 'X'). + + Returns: + A dictionary containing the command executed, stdout, stderr, + and a list of output files. + """ + if not db_file.is_file(): + raise FileNotFoundError(f"Input database file not found: {db_file}") + if not output_tsv.parent.is_dir(): + raise NotADirectoryError(f"Output directory does not exist: {output_tsv.parent}") + + r_script = _build_query_script("genes") + + args = [f"--db={db_file}", f"--outfile={output_tsv}"] + if filter_gene_id: + args.append(f"--filter_gene_id={filter_gene_id}") + if filter_gene_biotype: + args.append(f"--filter_gene_biotype={filter_gene_biotype}") + if filter_seq_name: + args.append(f"--filter_seq_name={filter_seq_name}") + + result = _run_r_script(r_script, args) + result["output_files"] = [str(output_tsv)] + return result + +@mcp.tool +def query_transcripts( + db_file: Path, + output_tsv: Path, + filter_gene_id: Optional[str] = None, + filter_tx_id: Optional[str] = None, + filter_tx_biotype: Optional[str] = None, +) -> Dict[str, Any]: + """ + Queries transcript information from an EnsemblDB SQLite database. + + This tool wraps the `transcripts` function from 'ensembldb'. It requires R, + 'ensembldb', and 'AnnotationFilter' packages. + + Args: + db_file: Path to the input EnsemblDB SQLite file. + output_tsv: Path for the output TSV file. + filter_gene_id: Optional filter by Ensembl gene ID. + filter_tx_id: Optional filter by Ensembl transcript ID. + filter_tx_biotype: Optional filter by transcript biotype (e.g., 'protein_coding'). + + Returns: + A dictionary containing the command executed, stdout, stderr, + and a list of output files. + """ + if not db_file.is_file(): + raise FileNotFoundError(f"Input database file not found: {db_file}") + if not output_tsv.parent.is_dir(): + raise NotADirectoryError(f"Output directory does not exist: {output_tsv.parent}") + + r_script = _build_query_script("transcripts") + + args = [f"--db={db_file}", f"--outfile={output_tsv}"] + if filter_gene_id: + args.append(f"--filter_gene_id={filter_gene_id}") + if filter_tx_id: + args.append(f"--filter_tx_id={filter_tx_id}") + if filter_tx_biotype: + args.append(f"--filter_tx_biotype={filter_tx_biotype}") + + result = _run_r_script(r_script, args) + result["output_files"] = [str(output_tsv)] + return result + +@mcp.tool +def query_exons( + db_file: Path, + output_tsv: Path, + filter_gene_id: Optional[str] = None, + filter_tx_id: Optional[str] = None, + filter_exon_id: Optional[str] = None, +) -> Dict[str, Any]: + """ + Queries exon information from an EnsemblDB SQLite database. + + This tool wraps the `exons` function from 'ensembldb'. It requires R, + 'ensembldb', and 'AnnotationFilter' packages. + + Args: + db_file: Path to the input EnsemblDB SQLite file. + output_tsv: Path for the output TSV file. + filter_gene_id: Optional filter by Ensembl gene ID. + filter_tx_id: Optional filter by Ensembl transcript ID. + filter_exon_id: Optional filter by Ensembl exon ID. + + Returns: + A dictionary containing the command executed, stdout, stderr, + and a list of output files. + """ + if not db_file.is_file(): + raise FileNotFoundError(f"Input database file not found: {db_file}") + if not output_tsv.parent.is_dir(): + raise NotADirectoryError(f"Output directory does not exist: {output_tsv.parent}") + + r_script = _build_query_script("exons") + + args = [f"--db={db_file}", f"--outfile={output_tsv}"] + if filter_gene_id: + args.append(f"--filter_gene_id={filter_gene_id}") + if filter_tx_id: + args.append(f"--filter_tx_id={filter_tx_id}") + if filter_exon_id: + args.append(f"--filter_exon_id={filter_exon_id}") + + result = _run_r_script(r_script, args) + result["output_files"] = [str(output_tsv)] + return result + +@mcp.tool +def query_promoters( + db_file: Path, + output_tsv: Path, + upstream: int = 2000, + downstream: int = 200, + filter_gene_id: Optional[str] = None, + filter_tx_id: Optional[str] = None, +) -> Dict[str, Any]: + """ + Extracts promoter regions for transcripts from an EnsemblDB. + + This tool wraps the `promoters` function from 'ensembldb'. It requires R, + 'ensembldb', and 'AnnotationFilter' packages. + + Args: + db_file: Path to the input EnsemblDB SQLite file. + output_tsv: Path for the output TSV file. + upstream: The number of bases upstream of the TSS to include. + downstream: The number of bases downstream of the TSS to include. + filter_gene_id: Optional filter by Ensembl gene ID. + filter_tx_id: Optional filter by Ensembl transcript ID. + + Returns: + A dictionary containing the command executed, stdout, stderr, + and a list of output files. + """ + if not db_file.is_file(): + raise FileNotFoundError(f"Input database file not found: {db_file}") + if not output_tsv.parent.is_dir(): + raise NotADirectoryError(f"Output directory does not exist: {output_tsv.parent}") + if upstream < 0 or downstream < 0: + raise ValueError("upstream and downstream values must be non-negative.") + + # The 'promoters' function takes upstream/downstream as direct arguments, + # so we modify the R script generation slightly. + extra_r_code = textwrap.dedent(f""" + up <- as.numeric(params$upstream) + down <- as.numeric(params$downstream) + results <- promoters(edb, upstream = up, downstream = down, filter = final_filter) + """) + + # We remove the final `results <- ...` line from the base template + base_script = _build_query_script("", extra_r_code) + + args = [ + f"--db={db_file}", + f"--outfile={output_tsv}", + f"--upstream={upstream}", + f"--downstream={downstream}" + ] + if filter_gene_id: + args.append(f"--filter_gene_id={filter_gene_id}") + if filter_tx_id: + args.append(f"--filter_tx_id={filter_tx_id}") + + result = _run_r_script(base_script, args) + result["output_files"] = [str(output_tsv)] + return result \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/app/bioconductor-ensembldb_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/app/bioconductor-ensembldb_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8313a2a3d9801b46701ee1832c7889bb14e241f8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/app/bioconductor-ensembldb_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_manual_txt/mcp_bioconductor-ensembldb/app/bioconductor-ensembldb_server.py') +SERVER_NAME = 'biosci_bioconductor_ensembldb' + + +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_manual_txt/mcp_bioconductor-ensembldb/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..fa827e40424fd2e2a65cbddc7f4cf3a3492f6067 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-ensembldb: + build: . + image: mcp-bioconductor-ensembldb:latest + container_name: mcp-bioconductor-ensembldb + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-ensembldb + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..62a1c11177e8cff952ab7e45ef6a86420acc5fff --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-ensembldb + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1f7b43050805f6bea8ccb79abf39b082b62f9ad5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-erma via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-erma -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-erma_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-erma_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-erma_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/app/bioconductor-erma_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/app/bioconductor-erma_server.py new file mode 100644 index 0000000000000000000000000000000000000000..427b357057822d1a7dc9899e89a14e53e36a25ad --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/app/bioconductor-erma_server.py @@ -0,0 +1,108 @@ +import subprocess +import logging +from pathlib import Path +from typing import List, Optional + +# Configure basic logging +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided by the MCP framework. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +@mcp.tool() +def run_erma_script( + script_path: Path, + output_dir: Path, + args: Optional[List[str]] = None, +): + """ + Executes a user-provided R script in an environment with bioconductor-erma. + + The 'bioconductor-erma' package is an R library for epigenomic data analysis + and does not provide a direct command-line interface. This tool serves as a + generic wrapper to execute R scripts that utilize the 'erma' library. The + user's script is responsible for implementing the analysis logic and writing + any output files to the specified directory. + + Args: + script_path: The path to the R script to be executed. + output_dir: The path to the directory where the R script is expected to + write its output files. This directory will be created if it + does not exist. + args: An optional list of command-line arguments to be passed to the + R script. + """ + # 1. Input Validation + if not script_path.is_file(): + raise FileNotFoundError(f"The specified R script does not exist: {script_path}") + + # 2. File Path Handling + try: + output_dir.mkdir(parents=True, exist_ok=True) + except OSError as e: + logging.error(f"Failed to create output directory {output_dir}: {e}") + raise + + # 3. Command Construction + command = ["Rscript", "--vanilla", str(script_path)] + if args: + command.extend([str(arg) for arg in args]) + + command_executed = " ".join(command) + logging.info(f"Executing command: {command_executed}") + + # 4. Subprocess Execution and Error Handling + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + cwd=output_dir, # Execute the script from the output directory + ) + stdout = result.stdout + stderr = result.stderr + logging.info("R script executed successfully.") + + except FileNotFoundError: + error_message = "Error: 'Rscript' command not found. Please ensure R is installed and accessible in the system's PATH." + logging.error(error_message) + return { + "command_executed": command_executed, + "stdout": "", + "stderr": error_message, + "output_files": [] + } + + except subprocess.CalledProcessError as e: + logging.error(f"R script failed with exit code {e.returncode}.") + logging.error(f"STDOUT: {e.stdout}") + logging.error(f"STDERR: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + # 5. Structured Result Return + try: + output_files = [str(f) for f in output_dir.iterdir() if f.is_file()] + except OSError as e: + logging.error(f"Error listing output files in {output_dir}: {e}") + # Append this error to stderr to inform the user about the issue + stderr += f"\n[MCP Wrapper Error] Could not list output files: {e}" + output_files = [] + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/app/bioconductor-erma_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/app/bioconductor-erma_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fe405693464562daf5e6d6fb4b03f084a232a896 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/app/bioconductor-erma_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_manual_txt/mcp_bioconductor-erma/app/bioconductor-erma_server.py') +SERVER_NAME = 'biosci_bioconductor_erma' + + +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_manual_txt/mcp_bioconductor-erma/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..782d3f8e2e0c9fa5dcda40aff6c86fe72ffa05ae --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-erma: + build: . + image: mcp-bioconductor-erma:latest + container_name: mcp-bioconductor-erma + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-erma + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e6edd0dc0eba1149262c0edeed5f97fce8950fde --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-erma + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..058e2e690efb46b0d54a80923d71a0f11fec4ddc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-escher via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-escher -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-escher_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-escher_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-escher_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/app/bioconductor-escher_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/app/bioconductor-escher_server.py new file mode 100644 index 0000000000000000000000000000000000000000..05b291bf2ca2d8d4cf530465194a10c4262ed641 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/app/bioconductor-escher_server.py @@ -0,0 +1,279 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# MCP-decorated functions for the 'escher' command-line tool. +# Note: This implementation is for the Python 'escher' package, which provides a +# command-line interface. The 'bioconductor-escher' package is an R wrapper +# and does not have a corresponding command-line tool. It is assumed the +# Python tool was the intended target. + + +@mcp.tool() +def escher_convert( + input_files: List[Path], + output: Optional[Path] = None, + format: Optional[str] = None, +): + """ + Converts Escher maps (JSON) to SVG or PNG formats. + + This tool wraps the 'escher convert' command. + + Args: + input_files: A list of one or more Escher map files (JSON) to convert. + output: The output file or directory. If not provided, output is saved + next to the input files. If multiple inputs are given, this must + be a directory. + format: The output format ('svg' or 'png'). Overrides the output file + extension. Defaults to 'svg' if not determinable from output path. + """ + # Input validation + if not input_files: + raise ValueError("At least one input file must be provided.") + for file_path in input_files: + if not file_path.is_file(): + raise FileNotFoundError(f"Input file not found: {file_path}") + + if format and format not in ["svg", "png"]: + raise ValueError("Invalid format. Must be 'svg' or 'png'.") + + if len(input_files) > 1 and output and output.is_file(): + raise ValueError( + "When multiple input files are provided, the output path must be a directory, not a file." + ) + + command = ["escher", "convert"] + command.extend(["--input", *[str(p) for p in input_files]]) + + output_format = "svg" + if format: + command.extend(["--format", format]) + output_format = format + elif output and output.suffix in [".svg", ".png"]: + output_format = output.suffix[1:] + + output_paths = [] + if output: + command.extend(["--output", str(output)]) + # Check if output is intended to be a directory + if output.is_dir() or (len(input_files) > 1) or (not output.suffix): + output.mkdir(parents=True, exist_ok=True) + for in_file in input_files: + output_paths.append(output / f"{in_file.stem}.{output_format}") + else: + # Output is a file + output.parent.mkdir(parents=True, exist_ok=True) + output_paths.append(output) + else: + # No output specified, save next to input + for in_file in input_files: + output_paths.append(in_file.with_suffix(f".{output_format}")) + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(p) for p in output_paths if p.exists()], + } + except FileNotFoundError: + raise RuntimeError( + "Error: 'escher' command not found. Please ensure the escher package is installed and in your PATH." + ) + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + + +@mcp.tool() +def escher_clear_cache(): + """ + Clears the Escher cache of downloaded maps and models. + + This tool wraps the 'escher clear-cache' command. + """ + command = ["escher", "clear-cache"] + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + } + except FileNotFoundError: + raise RuntimeError( + "Error: 'escher' command not found. Please ensure the escher package is installed and in your PATH." + ) + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + } + + +@mcp.tool() +def escher_run( + port: int = 7778, + host: str = "127.0.0.1", + no_cache: bool = False, + timeout: int = 30, +): + """ + Runs a new Escher server. + + Warning: This command starts a long-running server process. The 'timeout' + parameter is used to terminate the server after a specified duration. + This tool is primarily for interactive use and may have limited utility + in an automated MCP environment. The --no-browser flag is always used. + + Args: + port: The port to run the server on. + host: The host for the server. + no_cache: If True, do not cache Escher resources. + timeout: The maximum time in seconds to run the server before terminating. + """ + if timeout <= 0: + raise ValueError("Timeout must be a positive integer.") + + command = ["escher", "run", "--no-browser"] + command.extend(["--port", str(port)]) + command.extend(["--host", host]) + if no_cache: + command.append("--no-cache") + + try: + process = subprocess.run( + command, capture_output=True, text=True, timeout=timeout + ) + # This block is unlikely to be reached as the server runs indefinitely + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + } + except FileNotFoundError: + raise RuntimeError( + "Error: 'escher' command not found. Please ensure the escher package is installed and in your PATH." + ) + except subprocess.TimeoutExpired as e: + # This is the expected outcome for this tool in an MCP environment + return { + "command_executed": " ".join(command), + "stdout": e.stdout or "", + "stderr": e.stderr or f"Process terminated after {timeout}s timeout.", + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + } + + +@mcp.tool() +def escher_launch( + map_name: Optional[str] = None, + map_json: Optional[Path] = None, + model_name: Optional[str] = None, + model_json: Optional[Path] = None, + port: int = 7779, + host: str = "127.0.0.1", + no_cache: bool = False, + never_ask_before_quit: bool = False, + timeout: int = 30, +): + """ + Launches an Escher instance in a server, optionally loading a map/model. + + Warning: This command starts a long-running server process. The 'timeout' + parameter is used to terminate the server after a specified duration. + This tool is primarily for interactive use and may have limited utility + in an automated MCP environment. The --no-browser flag is always used. + + Args: + map_name: The name of the map to load from the Escher server. + map_json: A local JSON file for the map. + model_name: The name of the model to load from the Escher server. + model_json: A local JSON file for the model. + port: The port to run the server on. + host: The host for the server. + no_cache: If True, do not cache Escher resources. + never_ask_before_quit: If True, never ask "Are you sure you want to quit?". + timeout: The maximum time in seconds to run the server before terminating. + """ + # Input validation + if map_name and map_json: + raise ValueError("'map_name' and 'map_json' are mutually exclusive.") + if model_name and model_json: + raise ValueError("'model_name' and 'model_json' are mutually exclusive.") + if map_json and not map_json.is_file(): + raise FileNotFoundError(f"Map JSON file not found: {map_json}") + if model_json and not model_json.is_file(): + raise FileNotFoundError(f"Model JSON file not found: {model_json}") + if timeout <= 0: + raise ValueError("Timeout must be a positive integer.") + + command = ["escher", "launch", "--no-browser"] + + if map_name: + command.extend(["--map_name", map_name]) + if map_json: + command.extend(["--map_json", str(map_json)]) + if model_name: + command.extend(["--model_name", model_name]) + if model_json: + command.extend(["--model_json", str(model_json)]) + + command.extend(["--port", str(port)]) + command.extend(["--host", host]) + + if no_cache: + command.append("--no-cache") + if never_ask_before_quit: + command.append("--never_ask_before_quit") + + try: + process = subprocess.run( + command, capture_output=True, text=True, timeout=timeout + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + } + except FileNotFoundError: + raise RuntimeError( + "Error: 'escher' command not found. Please ensure the escher package is installed and in your PATH." + ) + except subprocess.TimeoutExpired as e: + # This is the expected outcome for this tool in an MCP environment + return { + "command_executed": " ".join(command), + "stdout": e.stdout or "", + "stderr": e.stderr or f"Process terminated after {timeout}s timeout.", + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/app/bioconductor-escher_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/app/bioconductor-escher_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7ee7b113e8e9d722dc366b15ac8abde8e3ae256c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/app/bioconductor-escher_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_manual_txt/mcp_bioconductor-escher/app/bioconductor-escher_server.py') +SERVER_NAME = 'biosci_bioconductor_escher' + + +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_manual_txt/mcp_bioconductor-escher/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..de7a0181d2217e0800a6feab0783313d926346ec --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-escher: + build: . + image: mcp-bioconductor-escher:latest + container_name: mcp-bioconductor-escher + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-escher + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..33e3ee7e3a9ca4625e9cc78d2ba5d7a00c40015d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-escher + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8efe558b37798abdb85fea94e1317a5793f49e90 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-experimentsubset via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-experimentsubset -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-experimentsubset_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-experimentsubset_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-experimentsubset_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/app/bioconductor-experimentsubset_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/app/bioconductor-experimentsubset_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0145224014ed8533a40c338feb2dfcc0046d6065 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/app/bioconductor-experimentsubset_server.py @@ -0,0 +1,178 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, Dict, List + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided by the MCP framework. +def mcp_tool_placeholder(*args, **kwargs): + def decorator(func): + return func + return decorator + +mcp = type('mcp', (), {'tool': mcp_tool_placeholder}) + + +@mcp.tool() +def manage_experiment_subset( + input_rds: Path, + output_rds: Path, + subset_name: str = "mcp_subset", + row_subset: Optional[str] = None, + col_subset: Optional[str] = None, + row_subset_file: Optional[Path] = None, + col_subset_file: Optional[Path] = None, +) -> Dict[str, any]: + """ + Provides a command-line interface to the R/Bioconductor 'ExperimentSubset' package. + + This tool subsets a Bioconductor experiment object (e.g., SummarizedExperiment, + SingleCellExperiment) stored in an RDS file based on provided row (e.g., genes) + or column (e.g., cells) identifiers. + + Args: + input_rds: Path to the input RDS file containing a Bioconductor experiment object. + output_rds: Path to save the output subsetted RDS file. + subset_name: A name to assign to the created subset. + row_subset: A comma-separated string of row names to include in the subset. + col_subset: A comma-separated string of column names to include in the subset. + row_subset_file: Path to a file containing row names to include (one per line). + col_subset_file: Path to a file containing column names to include (one per line). + + Returns: + A dictionary containing the execution command, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not input_rds.exists(): + raise FileNotFoundError(f"Input file not found: {input_rds}") + + if row_subset and row_subset_file: + raise ValueError("Cannot specify both 'row_subset' and 'row_subset_file'.") + + if col_subset and col_subset_file: + raise ValueError("Cannot specify both 'col_subset' and 'col_subset_file'.") + + if not any([row_subset, col_subset, row_subset_file, col_subset_file]): + raise ValueError("At least one subsetting criterion must be provided " + "('row_subset', 'col_subset', 'row_subset_file', or 'col_subset_file').") + + if not output_rds.parent.exists(): + output_rds.parent.mkdir(parents=True, exist_ok=True) + + # --- R Script Generation --- + r_script_content = f""" + # Load required libraries + if (!require("optparse", quietly = TRUE)) install.packages("optparse", repos = "http://cran.us.r-project.org") + if (!require("ExperimentSubset", quietly = TRUE)) {{ + if (!require("BiocManager", quietly = TRUE)) install.packages("BiocManager", repos = "http://cran.us.r-project.org") + BiocManager::install("ExperimentSubset", update=FALSE) + }} + library(optparse) + library(ExperimentSubset) + + # Define and parse command-line options + option_list <- list( + make_option(c("-i", "--input"), type="character", help="Input RDS file path"), + make_option(c("-o", "--output"), type="character", help="Output RDS file path"), + make_option(c("-n", "--name"), type="character", default="mcp_subset", help="Name for the subset"), + make_option(c("-r", "--rows"), type="character", default=NULL, help="Comma-separated row names"), + make_option(c("-c", "--cols"), type="character", default=NULL, help="Comma-separated column names"), + make_option(c("--row_file"), type="character", default=NULL, help="File with row names"), + make_option(c("--col_file"), type="character", default=NULL, help="File with column names") + ) + + opt_parser <- OptionParser(option_list=option_list) + opt <- parse_args(opt_parser) + + if (is.null(opt$input) || is.null(opt$output)) {{ + print_help(opt_parser) + stop("Input and output files must be supplied.", call.=FALSE) + }} + + # Load the experiment object + cat("Loading input RDS file:", opt$input, "\\n") + exp_obj <- readRDS(opt$input) + + # Create ExperimentSubset object + es <- ExperimentSubset(exp_obj) + + # Determine row and column subsets + row_indices <- NULL + if (!is.null(opt$rows)) {{ + row_indices <- trimws(strsplit(opt$rows, ",")[[1]]) + }} else if (!is.null(opt$row_file)) {{ + row_indices <- readLines(opt$row_file) + }} + + col_indices <- NULL + if (!is.null(opt$cols)) {{ + col_indices <- trimws(strsplit(opt$cols, ",")[[1]]) + }} else if (!is.null(opt$col_file)) {{ + col_indices <- readLines(opt$col_file) + }} + + # Create the subset using the subsetData function + cat("Creating subset '", opt$name, "'...\\n", sep="") + es <- subsetData(es, subsetName = opt$name, rows = row_indices, cols = col_indices) + + # Retrieve the actual subsetted object from the container + subset_obj <- getSubset(es, subsetName = opt$name) + + # Save the subsetted object + cat("Saving subsetted object to:", opt$output, "\\n") + saveRDS(subset_obj, file = opt$output) + + cat("Successfully created subset.\\n") + """ + + # --- Subprocess Execution --- + cmd: List[str] = [] + try: + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R") as r_script_file: + r_script_file.write(r_script_content) + r_script_path = r_script_file.name + + cmd = [ + "Rscript", r_script_path, + "--input", str(input_rds), + "--output", str(output_rds), + "--name", subset_name + ] + + if row_subset: + cmd.extend(["--rows", row_subset]) + if col_subset: + cmd.extend(["--cols", col_subset]) + if row_subset_file: + cmd.extend(["--row_file", str(row_subset_file)]) + if col_subset_file: + cmd.extend(["--col_file", str(col_subset_file)]) + + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_rds)] + } + + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } + finally: + # Clean up the temporary R script + if 'r_script_path' in locals() and Path(r_script_path).exists(): + Path(r_script_path).unlink() diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/app/bioconductor-experimentsubset_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/app/bioconductor-experimentsubset_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..987e1e52691de75b7adc44897e785a14133cefb9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/app/bioconductor-experimentsubset_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_manual_txt/mcp_bioconductor-experimentsubset/app/bioconductor-experimentsubset_server.py') +SERVER_NAME = 'biosci_bioconductor_experimentsubset' + + +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_manual_txt/mcp_bioconductor-experimentsubset/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..14db9f06094e56cfbc89047242ced0ca6d097862 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-experimentsubset: + build: . + image: mcp-bioconductor-experimentsubset:latest + container_name: mcp-bioconductor-experimentsubset + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-experimentsubset + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0522c599fba65423c66bcf93f421921e6df214cf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-experimentsubset + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3f58f161cd9693a95e4de36814275152fecf9f5d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-fgsea via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-fgsea -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-fgsea_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-fgsea_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-fgsea_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/app/bioconductor-fgsea_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/app/bioconductor-fgsea_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8f1562a3805d916d0b5e1bdb2ebde0d140ebc8d4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/app/bioconductor-fgsea_server.py @@ -0,0 +1,421 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional + +# This is a dummy decorator for development. +# In a real MCP environment, 'mcp' would be an imported module. +class MCP: + def tool(self): + def decorator(f): + return f + return decorator +mcp = MCP() + +R_DEPENDENCIES_NOTE = """ +NOTE: This tool requires R to be installed and in the system's PATH. +It also requires the following R packages to be installed: +- BiocManager +- fgsea (from Bioconductor) +- data.table +- argparse +- ggplot2 +- grid +You can install them in R with: +install.packages(c("data.table", "argparse", "ggplot2")) +if (!require("BiocManager", quietly = TRUE)) + install.packages("BiocManager") +BiocManager::install("fgsea") +""" + +@mcp.tool() +def fgsea_run( + pathways_file: Path, + stats_file: Path, + min_size: int = 1, + max_size: Optional[int] = None, + eps: float = 1e-10, + score_type: str = "std", + n_proc: int = 0, + gsea_param: float = 1.0, + n_perm_simple: int = 1000, + abs_eps: Optional[float] = None, + seed: int = 42, +) -> dict: + """ + Runs Fast Gene Set Enrichment Analysis (fgsea). + + This tool performs GSEA using the fgsea R package. It requires a pathways file + in GMT format and a file with pre-ranked gene-level statistics. The stats + file must be a two-column TSV/CSV with no header, containing gene IDs in the + first column and numeric stats in the second. + + Args: + pathways_file: Path to the pathways file in GMT format. + stats_file: Path to the gene-level stats file (2-column, no header). + min_size: Minimal size of a pathway to be considered. + max_size: Maximal size of a pathway to be considered. + eps: Boundary for calculating p-values. + score_type: Type of score for multilevel GSEA ('std', 'pos', 'neg'). + n_proc: Number of processors to use. 0 means automatic detection. + gsea_param: GSEA parameter (enrichment score weight). + n_perm_simple: Number of permutations for fgseaSimple. + abs_eps: Absolute epsilon for p-value calculation. + seed: Random seed for reproducibility. + + Returns: + A dictionary containing the execution command, stdout, stderr, and + a path to the resulting TSV file. + """ + # --- Input Validation --- + if not pathways_file.is_file(): + raise FileNotFoundError(f"Pathways file not found: {pathways_file}") + if not stats_file.is_file(): + raise FileNotFoundError(f"Stats file not found: {stats_file}") + + if min_size < 0: + raise ValueError("min_size must be a non-negative integer.") + if max_size is not None and max_size < min_size: + raise ValueError("max_size must be greater than or equal to min_size.") + if eps <= 0: + raise ValueError("eps must be a positive float.") + if score_type not in ["std", "pos", "neg"]: + raise ValueError("score_type must be one of 'std', 'pos', or 'neg'.") + if n_proc < 0: + raise ValueError("n_proc must be a non-negative integer.") + if n_perm_simple <= 0: + raise ValueError("n_perm_simple must be a positive integer.") + if abs_eps is not None and abs_eps <= 0: + raise ValueError("abs_eps must be a positive float if provided.") + + # --- R Script Definition --- + r_script_content = """ +#!/usr/bin/env Rscript +library(argparse) +library(fgsea) +library(data.table) + +parser <- ArgumentParser(description="Run fgsea analysis") +parser$add_argument("--pathways", type="character", required=TRUE) +parser$add_argument("--stats", type="character", required=TRUE) +parser$add_argument("--output", type="character", required=TRUE) +parser$add_argument("--minSize", type="integer", default=1) +parser$add_argument("--maxSize", type="integer", default=NULL) +parser$add_argument("--eps", type="double", default=1e-10) +parser$add_argument("--scoreType", type="character", default="std", choices=c("std", "pos", "neg")) +parser$add_argument("--nproc", type="integer", default=0) +parser$add_argument("--gseaParam", type="double", default=1.0) +parser$add_argument("--nPermSimple", type="integer", default=1000) +parser$add_argument("--absEps", type="double", default=NULL) +parser$add_argument("--seed", type="integer", default=42) +args <- parser$parse_args() + +set.seed(args$seed) + +pathways <- gmtPathways(args$pathways) + +stats_df <- fread(args$stats, header=FALSE) +if (ncol(stats_df) != 2) { + stop("Stats file must have exactly two columns (gene, stat) with no header.") +} +stats <- setNames(stats_df[[2]], stats_df[[1]]) +stats <- stats[!is.na(stats)] +stats <- sort(stats, decreasing=TRUE) + +maxSize <- if (is.null(args$maxSize)) Inf else args$maxSize + +fgseaRes <- fgsea( + pathways = pathways, + stats = stats, + minSize = args$minSize, + maxSize = maxSize, + eps = args$eps, + scoreType = args$scoreType, + nproc = args$nproc, + gseaParam = args$gseaParam, + nPermSimple = args$nPermSimple, + absEps = args$absEps +) + +fwrite(fgseaRes, file=args$output, sep="\\t", quote=FALSE, row.names=FALSE) +cat("fgsea analysis completed successfully.\\n") + """ + + with tempfile.TemporaryDirectory() as temp_dir: + temp_path = Path(temp_dir) + r_script_path = temp_path / "run_fgsea.R" + r_script_path.write_text(r_script_content) + + output_file = temp_path / "fgsea_results.tsv" + + cmd = [ + "Rscript", str(r_script_path), + "--pathways", str(pathways_file.resolve()), + "--stats", str(stats_file.resolve()), + "--output", str(output_file.resolve()), + "--minSize", str(min_size), + "--eps", str(eps), + "--scoreType", score_type, + "--nproc", str(n_proc), + "--gseaParam", str(gsea_param), + "--nPermSimple", str(n_perm_simple), + "--seed", str(seed), + ] + + if max_size is not None: + cmd.extend(["--maxSize", str(max_size)]) + if abs_eps is not None: + cmd.extend(["--absEps", str(abs_eps)]) + + # --- Subprocess Execution --- + try: + process = subprocess.run( + cmd, check=True, capture_output=True, text=True + ) + except FileNotFoundError: + raise RuntimeError(f"Rscript not found. Please ensure R is installed and in your PATH. {R_DEPENDENCIES_NOTE}") + except subprocess.CalledProcessError as e: + error_message = ( + f"fgsea execution failed with return code {e.returncode}.\n" + f"Command: {' '.join(cmd)}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}\n" + f"{R_DEPENDENCIES_NOTE}" + ) + raise RuntimeError(error_message) from e + + # --- Structured Result Return --- + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {"results_table": str(output_file)} + } + +@mcp.tool() +def fgsea_plot_enrichment( + pathways_file: Path, + stats_file: Path, + pathway_name: str, + gsea_param: float = 1.0, +) -> dict: + """ + Plots the GSEA enrichment score profile for a specific pathway. + + Args: + pathways_file: Path to the pathways file in GMT format. + stats_file: Path to the gene-level stats file (2-column, no header). + pathway_name: Name of the specific pathway to plot. + gsea_param: GSEA parameter (enrichment score weight). + + Returns: + A dictionary containing the execution command, stdout, stderr, and + a path to the resulting PDF plot. + """ + # --- Input Validation --- + if not pathways_file.is_file(): + raise FileNotFoundError(f"Pathways file not found: {pathways_file}") + if not stats_file.is_file(): + raise FileNotFoundError(f"Stats file not found: {stats_file}") + if not pathway_name: + raise ValueError("pathway_name cannot be empty.") + + # --- R Script Definition --- + r_script_content = """ +#!/usr/bin/env Rscript +library(argparse) +library(fgsea) +library(data.table) +library(ggplot2) + +parser <- ArgumentParser(description="Plot fgsea enrichment score") +parser$add_argument("--pathways", type="character", required=TRUE) +parser$add_argument("--stats", type="character", required=TRUE) +parser$add_argument("--pathway_name", type="character", required=TRUE) +parser$add_argument("--output", type="character", required=TRUE) +parser$add_argument("--gseaParam", type="double", default=1.0) +args <- parser$parse_args() + +pathways <- gmtPathways(args$pathways) +stats_df <- fread(args$stats, header=FALSE) +if (ncol(stats_df) != 2) { + stop("Stats file must have exactly two columns (gene, stat) with no header.") +} +stats <- setNames(stats_df[[2]], stats_df[[1]]) +stats <- stats[!is.na(stats)] + +if (!args$pathway_name %in% names(pathways)) { + stop(paste("Pathway '", args$pathway_name, "' not found in the pathways file.", sep="")) +} +selected_pathway <- pathways[[args$pathway_name]] + +p <- plotEnrichment(pathway=selected_pathway, stats=stats, gseaParam=args$gseaParam) + + labs(title=args$pathway_name) + +ggsave(args$output, plot=p, device="pdf") +cat("Enrichment plot saved to", args$output, "\\n") + """ + + with tempfile.TemporaryDirectory() as temp_dir: + temp_path = Path(temp_dir) + r_script_path = temp_path / "plot_enrichment.R" + r_script_path.write_text(r_script_content) + + safe_pathway_name = "".join(c for c in pathway_name if c.isalnum() or c in ('_', '-')).rstrip() + output_plot_file = temp_path / f"enrichment_plot_{safe_pathway_name}.pdf" + + cmd = [ + "Rscript", str(r_script_path), + "--pathways", str(pathways_file.resolve()), + "--stats", str(stats_file.resolve()), + "--pathway_name", pathway_name, + "--output", str(output_plot_file.resolve()), + "--gseaParam", str(gsea_param), + ] + + # --- Subprocess Execution --- + try: + process = subprocess.run( + cmd, check=True, capture_output=True, text=True + ) + except FileNotFoundError: + raise RuntimeError(f"Rscript not found. Please ensure R is installed and in your PATH. {R_DEPENDENCIES_NOTE}") + except subprocess.CalledProcessError as e: + error_message = ( + f"fgsea plot enrichment failed with return code {e.returncode}.\n" + f"Command: {' '.join(cmd)}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}\n" + f"{R_DEPENDENCIES_NOTE}" + ) + raise RuntimeError(error_message) from e + + # --- Structured Result Return --- + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {"enrichment_plot": str(output_plot_file)} + } + +@mcp.tool() +def fgsea_plot_gsea_table( + pathways_file: Path, + stats_file: Path, + fgsea_results_file: Path, + top_n: int = 10, + gsea_param: float = 1.0, +) -> dict: + """ + Plots a table of top GSEA results. + + Args: + pathways_file: Path to the pathways file in GMT format. + stats_file: Path to the gene-level stats file (2-column, no header). + fgsea_results_file: Path to the results TSV from a previous fgsea_run. + top_n: Number of top pathways (both up- and down-regulated) to plot. + gsea_param: GSEA parameter (enrichment score weight). + + Returns: + A dictionary containing the execution command, stdout, stderr, and + a path to the resulting PDF plot. + """ + # --- Input Validation --- + if not pathways_file.is_file(): + raise FileNotFoundError(f"Pathways file not found: {pathways_file}") + if not stats_file.is_file(): + raise FileNotFoundError(f"Stats file not found: {stats_file}") + if not fgsea_results_file.is_file(): + raise FileNotFoundError(f"fgsea results file not found: {fgsea_results_file}") + if top_n <= 0: + raise ValueError("top_n must be a positive integer.") + + # --- R Script Definition --- + r_script_content = """ +#!/usr/bin/env Rscript +library(argparse) +library(fgsea) +library(data.table) +library(grid) + +parser <- ArgumentParser(description="Plot fgsea results table") +parser$add_argument("--pathways", type="character", required=TRUE) +parser$add_argument("--stats", type="character", required=TRUE) +parser$add_argument("--results", type="character", required=TRUE) +parser$add_argument("--output", type="character", required=TRUE) +parser$add_argument("--top_n", type="integer", default=10) +parser$add_argument("--gseaParam", type="double", default=1.0) +args <- parser$parse_args() + +pathways <- gmtPathways(args$pathways) +stats_df <- fread(args$stats, header=FALSE) +if (ncol(stats_df) != 2) { + stop("Stats file must have exactly two columns (gene, stat) with no header.") +} +stats <- setNames(stats_df[[2]], stats_df[[1]]) +stats <- stats[!is.na(stats)] +fgseaRes <- fread(args$results) + +topPathwaysUp <- fgseaRes[ES > 0][head(order(pval), n=args$top_n), pathway] +topPathwaysDown <- fgseaRes[ES < 0][head(order(pval), n=args$top_n), pathway] +topPathways <- c(topPathwaysUp, rev(topPathwaysDown)) + +if (length(topPathways) == 0) { + stop("No significant pathways found to plot.") +} + +p <- plotGseaTable( + pathways = pathways[topPathways], + stats = stats, + fgseaRes = fgseaRes, + gseaParam = args$gseaParam +) + +pdf(args$output, width=10, height=max(2, 0.5 * length(topPathways))) +grid::grid.draw(p) +dev.off() + +cat("GSEA table plot saved to", args$output, "\\n") + """ + + with tempfile.TemporaryDirectory() as temp_dir: + temp_path = Path(temp_dir) + r_script_path = temp_path / "plot_gsea_table.R" + r_script_path.write_text(r_script_content) + + output_plot_file = temp_path / "gsea_table_plot.pdf" + + cmd = [ + "Rscript", str(r_script_path), + "--pathways", str(pathways_file.resolve()), + "--stats", str(stats_file.resolve()), + "--results", str(fgsea_results_file.resolve()), + "--output", str(output_plot_file.resolve()), + "--top_n", str(top_n), + "--gseaParam", str(gsea_param), + ] + + # --- Subprocess Execution --- + try: + process = subprocess.run( + cmd, check=True, capture_output=True, text=True + ) + except FileNotFoundError: + raise RuntimeError(f"Rscript not found. Please ensure R is installed and in your PATH. {R_DEPENDENCIES_NOTE}") + except subprocess.CalledProcessError as e: + error_message = ( + f"fgsea plot table failed with return code {e.returncode}.\n" + f"Command: {' '.join(cmd)}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}\n" + f"{R_DEPENDENCIES_NOTE}" + ) + raise RuntimeError(error_message) from e + + # --- Structured Result Return --- + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {"gsea_table_plot": str(output_plot_file)} + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/app/bioconductor-fgsea_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/app/bioconductor-fgsea_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..69a14a330957f7c35ff03bf137bea9d358a88177 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/app/bioconductor-fgsea_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_manual_txt/mcp_bioconductor-fgsea/app/bioconductor-fgsea_server.py') +SERVER_NAME = 'biosci_bioconductor_fgsea' + + +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_manual_txt/mcp_bioconductor-fgsea/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d9e0484b15b6a435468866e3995fb77b3dacdd6b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-fgsea: + build: . + image: mcp-bioconductor-fgsea:latest + container_name: mcp-bioconductor-fgsea + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-fgsea + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..110d3aced27b25d56e28db04a1eba7d50ffa67ba --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-fgsea + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genefilter/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genefilter/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..dc85663f20f55f0012a7e7ede03831c347bd098c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genefilter/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-genefilter via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-genefilter -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-genefilter_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-genefilter_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-genefilter_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genefilter/app/bioconductor-genefilter_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genefilter/app/bioconductor-genefilter_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7447bf40784a329babfc22f835ff0f6c97e2af86 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genefilter/app/bioconductor-genefilter_server.py @@ -0,0 +1,405 @@ +import subprocess +import os +import tempfile +from pathlib import Path +from typing import Optional, List, Union + +def run_r_script(script_content: str): + """Helper function to execute R code via Rscript.""" + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(script_content) + tmp_path = tmp.name + + try: + result = subprocess.run( + ["Rscript", tmp_path], + capture_output=True, + text=True, + check=True + ) + return result.stdout, result.stderr + except subprocess.CalledProcessError as e: + raise RuntimeError(f"R script failed with error:\n{e.stderr}\nStdout:\n{e.stdout}") + finally: + if os.path.exists(tmp_path): + os.remove(tmp_path) + +@mcp.tool() +def genefilter_k_over_a( + input_file: str, + output_file: str, + k: int = 1, + a: float = 10.0, + sep: str = ",", + has_header: bool = True +): + """ + Filter genes that have at least k samples with expression values greater than A. + + Args: + input_file: Path to the input expression matrix (CSV/TSV). First column should be Gene IDs. + output_file: Path to save the filtered matrix. + k: Minimum number of samples that must exceed the threshold. + a: The expression threshold value. + sep: Separator used in the input file (e.g., ',' for CSV, '\\t' for TSV). + has_header: Whether the input file has a header row. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file {input_file} not found."} + + if k < 1: + return {"error": "Parameter k must be at least 1."} + + r_script = f""" + library(genefilter) + data <- read.table("{input_file}", sep="{sep}", header={str(has_header).upper()}, row.names=1, check.names=FALSE) + f1 <- kOverA({k}, {a}) + ff <- filterfun(f1) + logical_vector <- genefilter(data, ff) + filtered_data <- data[logical_vector, ] + write.table(filtered_data, "{output_file}", sep="{sep}", col.names=NA, quote=FALSE) + cat(paste("Rows before:", nrow(data), "\\n")) + cat(paste("Rows after:", nrow(filtered_data), "\\n")) + """ + + try: + stdout, stderr = run_r_script(r_script) + return { + "command_executed": f"genefilter::kOverA(k={k}, A={a})", + "stdout": stdout, + "stderr": stderr, + "output_files": [output_file] + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def genefilter_p_over_a( + input_file: str, + output_file: str, + p: float = 0.1, + a: float = 10.0, + sep: str = ",", + has_header: bool = True +): + """ + Filter genes that have at least a proportion P of samples with expression values greater than A. + + Args: + input_file: Path to the input expression matrix. + output_file: Path to save the filtered matrix. + p: Minimum proportion of samples (0.0 to 1.0). + a: The expression threshold value. + sep: Separator used in the input file. + has_header: Whether the input file has a header row. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file {input_file} not found."} + + if not (0.0 <= p <= 1.0): + return {"error": "Parameter p must be between 0.0 and 1.0."} + + r_script = f""" + library(genefilter) + data <- read.table("{input_file}", sep="{sep}", header={str(has_header).upper()}, row.names=1, check.names=FALSE) + f1 <- pOverA({p}, {a}) + ff <- filterfun(f1) + logical_vector <- genefilter(data, ff) + filtered_data <- data[logical_vector, ] + write.table(filtered_data, "{output_file}", sep="{sep}", col.names=NA, quote=FALSE) + cat(paste("Rows before:", nrow(data), "\\n")) + cat(paste("Rows after:", nrow(filtered_data), "\\n")) + """ + + try: + stdout, stderr = run_r_script(r_script) + return { + "command_executed": f"genefilter::pOverA(p={p}, A={a})", + "stdout": stdout, + "stderr": stderr, + "output_files": [output_file] + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def genefilter_cv( + input_file: str, + output_file: str, + min_cv: float = 0.1, + max_cv: float = 10.0, + sep: str = ",", + has_header: bool = True +): + """ + Filter genes based on the Coefficient of Variation (CV = sd/mean). + + Args: + input_file: Path to the input expression matrix. + output_file: Path to save the filtered matrix. + min_cv: Minimum CV threshold. + max_cv: Maximum CV threshold. + sep: Separator used in the input file. + has_header: Whether the input file has a header row. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file {input_file} not found."} + + r_script = f""" + library(genefilter) + data <- read.table("{input_file}", sep="{sep}", header={str(has_header).upper()}, row.names=1, check.names=FALSE) + f1 <- cv({min_cv}, {max_cv}) + ff <- filterfun(f1) + logical_vector <- genefilter(as.matrix(data), ff) + filtered_data <- data[logical_vector, ] + write.table(filtered_data, "{output_file}", sep="{sep}", col.names=NA, quote=FALSE) + cat(paste("Rows before:", nrow(data), "\\n")) + cat(paste("Rows after:", nrow(filtered_data), "\\n")) + """ + + try: + stdout, stderr = run_r_script(r_script) + return { + "command_executed": f"genefilter::cv(a={min_cv}, b={max_cv})", + "stdout": stdout, + "stderr": stderr, + "output_files": [output_file] + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def genefilter_row_ttests( + input_file: str, + output_file: str, + groups: str, + sep: str = ",", + has_header: bool = True +): + """ + Perform fast row-wise t-tests for two groups. + + Args: + input_file: Path to the input expression matrix. + output_file: Path to save the t-test results (p-values, statistics). + groups: A comma-separated string of group labels (e.g., "A,A,A,B,B,B") matching the columns. + sep: Separator used in the input file. + has_header: Whether the input file has a header row. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file {input_file} not found."} + + r_script = f""" + library(genefilter) + data <- read.table("{input_file}", sep="{sep}", header={str(has_header).upper()}, row.names=1, check.names=FALSE) + fac <- factor(c(unlist(strsplit("{groups}", ",")))) + if(length(fac) != ncol(data)) stop("Length of groups must match number of columns in data") + res <- rowttests(as.matrix(data), fac) + write.table(res, "{output_file}", sep="{sep}", col.names=NA, quote=FALSE) + """ + + try: + stdout, stderr = run_r_script(r_script) + return { + "command_executed": "genefilter::rowttests()", + "stdout": stdout, + "stderr": stderr, + "output_files": [output_file] + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def genefilter_row_ftests( + input_file: str, + output_file: str, + groups: str, + sep: str = ",", + has_header: bool = True +): + """ + Perform fast row-wise F-tests for multiple groups. + + Args: + input_file: Path to the input expression matrix. + output_file: Path to save the F-test results. + groups: A comma-separated string of group labels matching the columns. + sep: Separator used in the input file. + has_header: Whether the input file has a header row. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file {input_file} not found."} + + r_script = f""" + library(genefilter) + data <- read.table("{input_file}", sep="{sep}", header={str(has_header).upper()}, row.names=1, check.names=FALSE) + fac <- factor(c(unlist(strsplit("{groups}", ",")))) + if(length(fac) != ncol(data)) stop("Length of groups must match number of columns in data") + res <- rowFtests(as.matrix(data), fac) + write.table(res, "{output_file}", sep="{sep}", col.names=NA, quote=FALSE) + """ + + try: + stdout, stderr = run_r_script(r_script) + return { + "command_executed": "genefilter::rowFtests()", + "stdout": stdout, + "stderr": stderr, + "output_files": [output_file] + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def genefilter_ns_filter( + input_file: str, + output_file: str, + var_filter: bool = True, + var_cutoff: float = 0.5, + filter_by_quantile: bool = True, + require_entrez: bool = False, + sep: str = ",", + has_header: bool = True +): + """ + Non-specific filtering of genes (removes low variance genes, etc.). + + Args: + input_file: Path to the input expression matrix. + output_file: Path to save the filtered matrix. + var_filter: Whether to filter by variance. + var_cutoff: The cutoff value for variance filtering. + filter_by_quantile: If True, var_cutoff is a quantile. If False, it's an absolute value. + require_entrez: If True, filters out genes without Entrez IDs (requires ExpressionSet logic). + sep: Separator used in the input file. + has_header: Whether the input file has a header row. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file {input_file} not found."} + + r_script = f""" + library(genefilter) + library(Biobase) + data_mat <- as.matrix(read.table("{input_file}", sep="{sep}", header={str(has_header).upper()}, row.names=1, check.names=FALSE)) + eset <- ExpressionSet(assayData=data_mat) + + # nsFilter returns a list with 'eset' and 'filter.log' + result <- nsFilter(eset, + var.filter={str(var_filter).upper()}, + var.cutoff={var_cutoff}, + filterByQuantile={str(filter_by_quantile).upper()}, + require.entrez={str(require_entrez).upper()}) + + filtered_data <- exprs(result$eset) + write.table(filtered_data, "{output_file}", sep="{sep}", col.names=NA, quote=FALSE) + cat(paste("Rows before:", nrow(data_mat), "\\n")) + cat(paste("Rows after:", nrow(filtered_data), "\\n")) + """ + + try: + stdout, stderr = run_r_script(r_script) + return { + "command_executed": "genefilter::nsFilter()", + "stdout": stdout, + "stderr": stderr, + "output_files": [output_file] + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def genefilter_row_stats( + input_file: str, + output_file: str, + stat_type: str = "vars", + sep: str = ",", + has_header: bool = True +): + """ + Calculate fast row-wise statistics (vars, sds, maxs, mins). + + Args: + input_file: Path to the input expression matrix. + output_file: Path to save the statistics. + stat_type: Type of statistic: 'vars', 'sds', 'maxs', or 'mins'. + sep: Separator used in the input file. + has_header: Whether the input file has a header row. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file {input_file} not found."} + + valid_stats = ["vars", "sds", "maxs", "mins"] + if stat_type not in valid_stats: + return {"error": f"stat_type must be one of {valid_stats}"} + + r_func = { + "vars": "rowVars", + "sds": "rowSds", + "maxs": "rowMaxs", + "mins": "rowMins" + }[stat_type] + + r_script = f""" + library(genefilter) + data <- as.matrix(read.table("{input_file}", sep="{sep}", header={str(has_header).upper()}, row.names=1, check.names=FALSE)) + res <- {r_func}(data) + names(res) <- rownames(data) + write.table(res, "{output_file}", sep="{sep}", col.names=FALSE, quote=FALSE) + """ + + try: + stdout, stderr = run_r_script(r_script) + return { + "command_executed": f"genefilter::{r_func}()", + "stdout": stdout, + "stderr": stderr, + "output_files": [output_file] + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def genefilter_shorth( + input_file: str, + output_file: str, + sep: str = ",", + has_header: bool = True +): + """ + Calculate the 'shorth' for each row (the shortest interval containing half the data). + Often used as a robust estimator of location. + + Args: + input_file: Path to the input expression matrix. + output_file: Path to save the results. + sep: Separator used in the input file. + has_header: Whether the input file has a header row. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file {input_file} not found."} + + r_script = f""" + library(genefilter) + data <- read.table("{input_file}", sep="{sep}", header={str(has_header).upper()}, row.names=1, check.names=FALSE) + res <- apply(as.matrix(data), 1, shorth) + write.table(res, "{output_file}", sep="{sep}", col.names=FALSE, quote=FALSE) + """ + + try: + stdout, stderr = run_r_script(r_script) + return { + "command_executed": "apply(data, 1, genefilter::shorth)", + "stdout": stdout, + "stderr": stderr, + "output_files": [output_file] + } + except Exception as e: + return {"error": str(e)} \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genefilter/app/bioconductor-genefilter_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genefilter/app/bioconductor-genefilter_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..17658b415004bf8afdd05a807608349c8162e105 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genefilter/app/bioconductor-genefilter_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_manual_txt/mcp_bioconductor-genefilter/app/bioconductor-genefilter_server.py') +SERVER_NAME = 'biosci_bioconductor_genefilter' + + +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_manual_txt/mcp_bioconductor-genefilter/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genefilter/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genefilter/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genefilter/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genefilter/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b8e8117174138cbb23e50012e6aebca949f11ffa --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genefilter/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-genefilter: + build: . + image: mcp-bioconductor-genefilter:latest + container_name: mcp-bioconductor-genefilter + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-genefilter + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genefilter/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genefilter/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..312740a65e928231eccc1ea6ad5aa3f5d906f6ab --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genefilter/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-genefilter + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genefilter/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genefilter/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genefilter/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geneplotter/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geneplotter/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9d0c94a2a986994b11bf5544d2ed47deb4078e57 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geneplotter/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-geneplotter via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-geneplotter -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-geneplotter_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-geneplotter_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-geneplotter_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geneplotter/app/bioconductor-geneplotter_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geneplotter/app/bioconductor-geneplotter_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6e20958751c8f717b0b32135e1eae309d16a354b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geneplotter/app/bioconductor-geneplotter_server.py @@ -0,0 +1,342 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Dict +import logging + +# Configure logging +logging.basicConfig(level=logging.INFO) + +def _run_r_script(script_content: str, output_files: List[Path]) -> Dict: + """ + A helper function to run an R script using a temporary file. + + Args: + script_content: A string containing the R code to execute. + output_files: A list of expected output file paths for validation. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of generated output files. + """ + command_executed = "" + stdout_str = "" + stderr_str = "" + + try: + with tempfile.NamedTemporaryFile( + mode='w', suffix=".R", delete=False, encoding='utf-8' + ) as r_script_file: + r_script_file.write(script_content) + script_path = r_script_file.name + + cmd = ["Rscript", script_path] + command_executed = " ".join(cmd) + + logging.info(f"Executing command: {command_executed}") + logging.info(f"R script content:\n---\n{script_content}\n---") + + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + stdout_str = process.stdout + stderr_str = process.stderr + + # Verify that output files were created + validated_output_files = [] + for f in output_files: + if f.exists() and f.stat().st_size > 0: + validated_output_files.append(str(f)) + else: + logging.warning(f"Expected output file not found or is empty: {f}") + # Add to stderr to notify user + stderr_str += f"\n[MCP WARNING] Expected output file not found or is empty: {f}" + + + return { + "command_executed": command_executed, + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": validated_output_files + } + + except subprocess.CalledProcessError as e: + logging.error(f"Error executing R script: {e}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + except Exception as e: + logging.error(f"An unexpected error occurred: {e}") + return { + "command_executed": command_executed, + "stdout": stdout_str, + "stderr": f"An unexpected Python error occurred: {str(e)}", + "output_files": [] + } + finally: + if 'script_path' in locals() and Path(script_path).exists(): + Path(script_path).unlink() + + +@mcp.tool() +def plot_ma( + expression_data: Path, + output_file: Path, + a_col: str, + m_col: str, + plot_format: str = "pdf", + title: Optional[str] = "MA Plot", + xlab: Optional[str] = "A (Average log-intensity)", + ylab: Optional[str] = "M (log-ratio)", + col: Optional[str] = "blue", + cex: float = 0.5 +): + """ + Generates an M-A plot from expression data using geneplotter's plotMA function. + + An M-A plot is a common visualization for microarray data, plotting the log-fold-change (M) + against the average intensity (A). + + Args: + expression_data: Path to a tab-separated (TSV) or comma-separated (CSV) file + containing expression data. Must have a header. + output_file: Path to save the output plot. The extension is ignored; use plot_format. + a_col: The name of the column representing 'A' (average log-intensity). + m_col: The name of the column representing 'M' (log-ratio). + plot_format: The format of the output plot. One of 'pdf', 'png', 'svg'. + title: The main title for the plot. + xlab: The label for the x-axis. + ylab: The label for the y-axis. + col: The color of the points. + cex: The expansion factor for the points. + """ + # Input validation + if not expression_data.exists(): + raise FileNotFoundError(f"Input file not found: {expression_data}") + if plot_format not in ["pdf", "png", "svg"]: + raise ValueError("plot_format must be one of 'pdf', 'png', or 'svg'") + if cex <= 0: + raise ValueError("cex must be a positive number.") + + output_path = output_file.with_suffix(f".{plot_format}") + + # Determine separator for read.csv + separator = "," if str(expression_data).endswith(".csv") else "\\t" + + # Build R function call with optional parameters + r_params = [] + if title: + r_params.append(f'main="{title}"') + if xlab: + r_params.append(f'xlab="{xlab}"') + if ylab: + r_params.append(f'ylab="{ylab}"') + if col: + r_params.append(f'col="{col}"') + if cex: + r_params.append(f'cex={cex}') + + r_params_str = ", ".join(r_params) + + r_script = f""" + library(geneplotter) + + # Load data + data <- read.csv("{expression_data}", sep="{separator}", header=TRUE, stringsAsFactors=FALSE) + + # Check if columns exist + if (!("{a_col}" %in% colnames(data)) || !("{m_col}" %in% colnames(data))) {{ + stop("Specified columns for A and M not found in the data file.") + }} + + # Open graphics device + {plot_format}("{output_path}") + + # Create plot + plotMA(data, array=1, x.abscissa="{a_col}", y.ordinate="{m_col}", {r_params_str}) + + # Close device + dev.off() + """ + + return _run_r_script(r_script, [output_path]) + + +@mcp.tool() +def plot_pca( + data_matrix: Path, + output_file: Path, + plot_format: str = "pdf", + groups_file: Optional[Path] = None, + title: Optional[str] = "PCA Plot", + pc_x: int = 1, + pc_y: int = 2 +): + """ + Generates a PCA plot from a data matrix using geneplotter's plotPCA function. + + This function performs Principal Component Analysis on the provided data and plots + the samples based on the specified principal components. + + Args: + data_matrix: Path to a TSV or CSV file where rows are features (e.g., genes) + and columns are samples. The first column should be feature names. + output_file: Path to save the output plot. The extension is ignored; use plot_format. + plot_format: The format of the output plot. One of 'pdf', 'png', 'svg'. + groups_file: Optional path to a two-column TSV/CSV file mapping sample names + (from data_matrix header) to groups for coloring. Header: Sample,Group. + title: The main title for the plot. + pc_x: The principal component to plot on the x-axis. + pc_y: The principal component to plot on the y-axis. + """ + # Input validation + if not data_matrix.exists(): + raise FileNotFoundError(f"Input data matrix not found: {data_matrix}") + if groups_file and not groups_file.exists(): + raise FileNotFoundError(f"Groups file not found: {groups_file}") + if plot_format not in ["pdf", "png", "svg"]: + raise ValueError("plot_format must be one of 'pdf', 'png', or 'svg'") + if pc_x <= 0 or pc_y <= 0 or pc_x == pc_y: + raise ValueError("Principal components must be positive and distinct integers.") + + output_path = output_file.with_suffix(f".{plot_format}") + + # Determine separator for read.csv + data_sep = "," if str(data_matrix).endswith(".csv") else "\\t" + + # Build R script + r_script = f""" + library(geneplotter) + library(Biobase) + + # Load data matrix + data <- read.csv("{data_matrix}", sep="{data_sep}", header=TRUE, row.names=1, stringsAsFactors=FALSE) + + # Ensure data is numeric + data <- as.matrix(data) + if(!is.numeric(data)){{ + stop("Data matrix contains non-numeric values.") + }} + + # Create a minimal ExpressionSet object + eset <- ExpressionSet(assayData=data) + + # Prepare groups for coloring if provided + plot_args <- list(x=eset, groups=NULL, pcs=c({pc_x}, {pc_y})) + """ + + if groups_file: + group_sep = "," if str(groups_file).endswith(".csv") else "\\t" + r_script += f""" + groups_df <- read.csv("{groups_file}", sep="{group_sep}", header=TRUE, stringsAsFactors=TRUE) + # Match order of groups to sample names in eset + sample_names_eset <- sampleNames(eset) + matched_indices <- match(sample_names_eset, groups_df$Sample) + if(any(is.na(matched_indices))) {{ + warning("Some samples in the data matrix are not found in the groups file.") + }} + ordered_groups <- groups_df$Group[matched_indices] + pData(eset) <- data.frame(group=ordered_groups) + plot_args$groups <- pData(eset)$group + """ + + if title: + r_script += f'plot_args$main <- "{title}"\n' + + r_script += f""" + # Open graphics device + {plot_format}("{output_path}") + + # Create plot + do.call(plotPCA, plot_args) + + # Close device + dev.off() + """ + + return _run_r_script(r_script, [output_path]) + + +@mcp.tool() +def cplot( + location_data: Path, + output_file: Path, + chrom_col: str, + pos_col: str, + plot_format: str = "pdf", + plot_type: str = "hist", + title: Optional[str] = "Genomic Location Plot", + xlab: Optional[str] = "Chromosome", + ylab: Optional[str] = "Count" +): + """ + Plots the distribution of genomic locations across chromosomes using geneplotter's cPlot. + + Args: + location_data: Path to a TSV or CSV file with genomic locations. Must have a header. + output_file: Path to save the output plot. The extension is ignored; use plot_format. + chrom_col: The name of the column containing chromosome identifiers. + pos_col: The name of the column containing the chromosomal position. + plot_format: The format of the output plot. One of 'pdf', 'png', 'svg'. + plot_type: The type of plot to generate. One of 'hist' (histogram) or 'scatter'. + title: The main title for the plot. + xlab: The label for the x-axis. + ylab: The label for the y-axis. + """ + # Input validation + if not location_data.exists(): + raise FileNotFoundError(f"Input file not found: {location_data}") + if plot_format not in ["pdf", "png", "svg"]: + raise ValueError("plot_format must be one of 'pdf', 'png', or 'svg'") + if plot_type not in ["hist", "scatter"]: + raise ValueError("plot_type must be one of 'hist' or 'scatter'") + + output_path = output_file.with_suffix(f".{plot_format}") + + # Determine separator for read.csv + separator = "," if str(location_data).endswith(".csv") else "\\t" + + # Build R function call with optional parameters + r_params = [] + if title: + r_params.append(f'main="{title}"') + if xlab: + r_params.append(f'xlab="{xlab}"') + if ylab: + r_params.append(f'ylab="{ylab}"') + + r_params_str = ", ".join(r_params) + + r_script = f""" + library(geneplotter) + library(annotate) + + # Load data + loc_data <- read.csv("{location_data}", sep="{separator}", header=TRUE, stringsAsFactors=FALSE) + + # Check if columns exist + if (!("{chrom_col}" %in% colnames(loc_data)) || !("{pos_col}" %in% colnames(loc_data))) {{ + stop("Specified columns for chromosome and position not found in the data file.") + }} + + # Create a chromLocation object + chrom_loc <- new("chromLocation", + chromosome=as.character(loc_data[['{chrom_col}']]), + position=as.numeric(loc_data[['{pos_col}']])) + + # Open graphics device + {plot_format}("{output_path}") + + # Create plot + cPlot(chrom_loc, type="{plot_type}", {r_params_str}) + + # Close device + dev.off() + """ + + return _run_r_script(r_script, [output_path]) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geneplotter/app/bioconductor-geneplotter_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geneplotter/app/bioconductor-geneplotter_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f9a656e9aedeb9a50993ed017f055f0a3415b479 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geneplotter/app/bioconductor-geneplotter_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_manual_txt/mcp_bioconductor-geneplotter/app/bioconductor-geneplotter_server.py') +SERVER_NAME = 'biosci_bioconductor_geneplotter' + + +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_manual_txt/mcp_bioconductor-geneplotter/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geneplotter/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geneplotter/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geneplotter/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geneplotter/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..026bcda856f99b635b1b6d84ba99f4b936d948d7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geneplotter/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-geneplotter: + build: . + image: mcp-bioconductor-geneplotter:latest + container_name: mcp-bioconductor-geneplotter + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-geneplotter + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geneplotter/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geneplotter/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..140b2e80539603f5b9039b3b6fdfde9efa0c3d43 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geneplotter/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-geneplotter + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geneplotter/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geneplotter/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geneplotter/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodb/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodb/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..da1928863b64adf79436afc2d7c96a25511e3b41 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodb/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-genomeinfodb via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-genomeinfodb -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-genomeinfodb_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-genomeinfodb_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-genomeinfodb_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodb/app/bioconductor-genomeinfodb_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodb/app/bioconductor-genomeinfodb_server.py new file mode 100644 index 0000000000000000000000000000000000000000..247ad74c244354ac05b0ea362a4966374284ace9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodb/app/bioconductor-genomeinfodb_server.py @@ -0,0 +1,325 @@ +import subprocess +import tempfile +import shutil +from pathlib import Path +from typing import Optional, List, Dict +import sys +import logging + +# Configure logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# Mock the mcp.tool decorator for standalone execution +class mcp: + def tool(func): + return func + +def _check_rscript(): + """Checks if Rscript is available in the system PATH.""" + if not shutil.which("Rscript"): + raise EnvironmentError( + "Rscript not found in PATH. R and the GenomeInfoDb Bioconductor " + "package are required to run these tools." + ) + +@mcp.tool +def genomeinfodb_list_styles(species: str) -> Dict: + """ + Lists the available chromosome naming styles (e.g., UCSC, NCBI) for a given species. + + This tool wraps the `genomeStyles()` function from the R/Bioconductor GenomeInfoDb package. + + Args: + species: The scientific name of the species (e.g., "Homo sapiens", "Mus musculus"). + + Returns: + A dictionary containing the command executed, stdout (with the list of styles), + stderr, and a list of available styles. + """ + _check_rscript() + if not species: + raise ValueError("The 'species' argument cannot be empty.") + + r_script_content = f""" + suppressPackageStartupMessages(library(GenomeInfoDb)) + tryCatch({{ + styles <- genomeStyles('{species}') + if (length(styles) == 0) {{ + cat("No styles found for species: {species}\\n", file=stderr()) + }} else {{ + cat(paste(names(styles), collapse='\\n')) + }} + }}, error = function(e) {{ + cat(paste("Error:", e$message, "\\n"), file=stderr()) + quit(status = 1) + }}) + """ + + command = ["Rscript", "-e", r_script_content] + command_executed = " ".join(command) + logger.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + styles_list = result.stdout.strip().split('\n') if result.stdout.strip() else [] + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "styles": styles_list, + } + except subprocess.CalledProcessError as e: + logger.error(f"Error executing GenomeInfoDb R script: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to list genome styles. Check if the species name is correct and GenomeInfoDb is installed.", + } + +@mcp.tool +def genomeinfodb_map_seqlevels( + target_style: str, + species: str, + input_file: Path, + output_file: Path, +) -> Dict: + """ + Maps chromosome names from an input file to a specified naming convention (style). + + This tool wraps the `mapSeqlevels()` function from the R/Bioconductor GenomeInfoDb package. + It produces a two-column TSV file: 'original' and 'mapped'. + + Args: + target_style: The target naming style (e.g., "UCSC", "NCBI", "Ensembl"). + species: The scientific name of the species (e.g., "Homo sapiens"). + input_file: Path to a file containing one chromosome name per line. + output_file: Path to write the output TSV file with original and mapped names. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output file. + """ + _check_rscript() + if not target_style: + raise ValueError("The 'target_style' argument cannot be empty.") + if not species: + raise ValueError("The 'species' argument cannot be empty.") + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + r_script_content = f""" + suppressPackageStartupMessages(library(GenomeInfoDb)) + args <- commandArgs(trailingOnly=TRUE) + inputFile <- args[1] + targetStyle <- args[2] + species <- args[3] + outputFile <- args[4] + + tryCatch({{ + seqs <- readLines(inputFile) + if (length(seqs) == 0) {{ + stop("Input file is empty.") + }} + mapped_seqs <- mapSeqlevels(seqs, style=targetStyle, species=species) + output_df <- data.frame(original=seqs, mapped=mapped_seqs) + write.table(output_df, file=outputFile, sep='\\t', row.names=FALSE, col.names=TRUE, quote=FALSE) + }}, error = function(e) {{ + cat(paste("Error:", e$message, "\\n"), file=stderr()) + quit(status = 1) + }}) + """ + + command = [ + "Rscript", + "-e", + r_script_content, + str(input_file), + target_style, + species, + str(output_file), + ] + command_executed = " ".join(command) + logger.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"mapped_seqlevels": str(output_file)}, + } + except subprocess.CalledProcessError as e: + logger.error(f"Error executing GenomeInfoDb R script: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to map seqlevels. Check parameters and ensure input file is correctly formatted.", + } + +@mcp.tool +def genomeinfodb_get_seqinfo( + genome: str, + output_file: Path, +) -> Dict: + """ + Fetches sequence information (lengths, circularity) for a given genome assembly. + + This tool wraps the `Seqinfo()` constructor from the R/Bioconductor GenomeInfoDb package. + It produces a TSV file containing seqnames, seqlengths, isCircular, and genome. + + Args: + genome: The genome assembly identifier (e.g., "hg19", "hg38", "mm10"). + output_file: Path to write the output TSV file with sequence information. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output file. + """ + _check_rscript() + if not genome: + raise ValueError("The 'genome' argument cannot be empty.") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + r_script_content = f""" + suppressPackageStartupMessages(library(GenomeInfoDb)) + args <- commandArgs(trailingOnly=TRUE) + genome_id <- args[1] + outputFile <- args[2] + + tryCatch({{ + si <- Seqinfo(genome=genome_id) + si_df <- as.data.frame(si) + write.table(si_df, file=outputFile, sep='\\t', row.names=TRUE, col.names=NA, quote=FALSE) + }}, error = function(e) {{ + cat(paste("Error:", e$message, "\\n"), file=stderr()) + quit(status = 1) + }}) + """ + + command = ["Rscript", "-e", r_script_content, genome, str(output_file)] + command_executed = " ".join(command) + logger.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"seqinfo": str(output_file)}, + } + except subprocess.CalledProcessError as e: + logger.error(f"Error executing GenomeInfoDb R script: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to get seqinfo. Check if the genome identifier is correct.", + } + +@mcp.tool +def genomeinfodb_rename_seqlevels( + input_file: Path, + mapping_file: Path, + output_file: Path, +) -> Dict: + """ + Renames chromosome names from an input file based on a provided mapping file. + + This tool wraps the `renameSeqlevels()` function from the R/Bioconductor GenomeInfoDb package. + It produces a two-column TSV file: 'original' and 'renamed'. + + Args: + input_file: Path to a file containing one chromosome name per line. + mapping_file: Path to a two-column TSV file (old_namenew_name) without a header. + output_file: Path to write the output TSV file with original and renamed names. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output file. + """ + _check_rscript() + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if not mapping_file.is_file(): + raise FileNotFoundError(f"Mapping file not found: {mapping_file}") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + r_script_content = f""" + suppressPackageStartupMessages(library(GenomeInfoDb)) + args <- commandArgs(trailingOnly=TRUE) + inputFile <- args[1] + mappingFile <- args[2] + outputFile <- args[3] + + tryCatch({{ + seqs <- readLines(inputFile) + if (length(seqs) == 0) {{ + stop("Input file is empty.") + }} + mapping_df <- read.table(mappingFile, sep='\\t', header=FALSE, stringsAsFactors=FALSE, col.names=c("old", "new")) + if (nrow(mapping_df) == 0) {{ + stop("Mapping file is empty.") + }} + value <- setNames(mapping_df$new, mapping_df$old) + renamed_seqs <- renameSeqlevels(seqs, value) + output_df <- data.frame(original=seqs, renamed=renamed_seqs) + write.table(output_df, file=outputFile, sep='\\t', row.names=FALSE, col.names=TRUE, quote=FALSE) + }}, error = function(e) {{ + cat(paste("Error:", e$message, "\\n"), file=stderr()) + quit(status = 1) + }}) + """ + + command = [ + "Rscript", + "-e", + r_script_content, + str(input_file), + str(mapping_file), + str(output_file), + ] + command_executed = " ".join(command) + logger.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"renamed_seqlevels": str(output_file)}, + } + except subprocess.CalledProcessError as e: + logger.error(f"Error executing GenomeInfoDb R script: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to rename seqlevels. Check file formats and content.", + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodb/app/bioconductor-genomeinfodb_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodb/app/bioconductor-genomeinfodb_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2534a7528d190408439f3c6107dda8b95f1d6e4e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodb/app/bioconductor-genomeinfodb_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_manual_txt/mcp_bioconductor-genomeinfodb/app/bioconductor-genomeinfodb_server.py') +SERVER_NAME = 'biosci_bioconductor_genomeinfodb' + + +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_manual_txt/mcp_bioconductor-genomeinfodb/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodb/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodb/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodb/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodb/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f45008fc4f9db6ed1b6aafd4d5c65aa0c5ac8c66 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodb/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-genomeinfodb: + build: . + image: mcp-bioconductor-genomeinfodb:latest + container_name: mcp-bioconductor-genomeinfodb + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-genomeinfodb + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodb/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodb/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9340ec8e0823c9ed7de8c928916c2c625108234e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodb/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-genomeinfodb + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodb/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodb/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodb/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodbdata/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodbdata/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..dc26f6e5aed612e1d00f134418a4dfb7f9cfe0cb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodbdata/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-genomeinfodbdata via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-genomeinfodbdata -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-genomeinfodbdata_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-genomeinfodbdata_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-genomeinfodbdata_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodbdata/app/bioconductor-genomeinfodbdata_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodbdata/app/bioconductor-genomeinfodbdata_server.py new file mode 100644 index 0000000000000000000000000000000000000000..673b3e6005e9431d22f349cbed330bb9973aa3ee --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodbdata/app/bioconductor-genomeinfodbdata_server.py @@ -0,0 +1,130 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict, Any + +# MCP decorator placeholder +def tool(*args, **kwargs): + def decorator(f): + return f + return decorator + +# In a real MCP environment, the 'mcp' object would be imported. +# For this standalone script, we define a placeholder. +class mcp: + tool = tool + +@mcp.tool() +def run_rscript( + script_file: Optional[Path] = None, + expressions: Optional[List[str]] = None, + args: Optional[List[str]] = None, + verbose: bool = False, + default_packages: Optional[str] = None, + save: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: bool = False, + restore: bool = False, + vanilla: bool = False, +) -> Dict[str, Any]: + """ + Executes an R script using the Rscript interpreter. + + This tool is a general-purpose wrapper for the Rscript command-line utility. + The 'bioconductor-genomeinfodbdata' package is a data-only package and does not + have its own executable. It is intended to be used within R scripts, which can + be run with this tool. + + Args: + script_file: Path to the R script file to be executed. + expressions: A list of R expressions to be executed. Use this or script_file, not both. + args: A list of arguments to be passed to the R script. + verbose: Print information on progress (--verbose). + default_packages: A comma-separated list of package names to be loaded by default (--default-packages). + save: Save the workspace at the end of the session (--save). + no_environ: Don't read the site and user environment files (--no-environ). + no_site_file: Don't read the site-wide Rprofile (--no-site-file). + no_init_file: Don't read the user R profile (--no-init-file). + restore: Restore previously saved objects at startup (--restore). + vanilla: Combine --no-save, --no-restore, --no-site-file, --no-init-file, and --no-environ (--vanilla). + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # Input validation + if script_file and expressions: + raise ValueError("Provide either 'script_file' or 'expressions', not both.") + 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 script file does not exist: {script_file}") + + cmd = ["Rscript"] + + # Add R-specific 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") + + if verbose: + cmd.append("--verbose") + if default_packages: + cmd.extend(["--default-packages", default_packages]) + + # Add script file or expressions + if script_file: + cmd.append(str(script_file)) + elif expressions: + for expr in expressions: + cmd.extend(["-e", expr]) + + # Add script arguments + if args: + cmd.extend(args) + + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + stdout = result.stdout + stderr = result.stderr + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: Rscript not found. Is R installed and in your PATH?", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + # Since the script's output files are unknown, we return an empty list. + # The user's R script is responsible for managing its own outputs. + 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_manual_txt/mcp_bioconductor-genomeinfodbdata/app/bioconductor-genomeinfodbdata_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodbdata/app/bioconductor-genomeinfodbdata_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..50c7513e3e083a896da9551cc0ea1380659fdd47 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodbdata/app/bioconductor-genomeinfodbdata_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_manual_txt/mcp_bioconductor-genomeinfodbdata/app/bioconductor-genomeinfodbdata_server.py') +SERVER_NAME = 'biosci_bioconductor_genomeinfodbdata' + + +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_manual_txt/mcp_bioconductor-genomeinfodbdata/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodbdata/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodbdata/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodbdata/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodbdata/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..417a651e07b0490b797620fdf758562f52d5a1cb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodbdata/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-genomeinfodbdata: + build: . + image: mcp-bioconductor-genomeinfodbdata:latest + container_name: mcp-bioconductor-genomeinfodbdata + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-genomeinfodbdata + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodbdata/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodbdata/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e178851c0df5db898851d3336adcacfea12f5cad --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodbdata/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-genomeinfodbdata + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodbdata/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodbdata/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomeinfodbdata/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicalignments/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicalignments/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1df8854d574f92a14aab64756ce0ad45c64c831b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicalignments/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-genomicalignments via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-genomicalignments -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-genomicalignments_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-genomicalignments_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-genomicalignments_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicalignments/app/bioconductor-genomicalignments_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicalignments/app/bioconductor-genomicalignments_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5888853d01184363b7a02d2df8c879e0970783c2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicalignments/app/bioconductor-genomicalignments_server.py @@ -0,0 +1,142 @@ +import subprocess +import tempfile +import os +from pathlib import Path +from typing import List, Optional, Dict, Any + +@mcp.tool() +def run_genomicalignments_r_script( + r_script_content: str, + input_files: Optional[List[Path]] = None, + expected_output_filenames: Optional[List[str]] = None, + r_base_path: str = "Rscript", +) -> Dict[str, Any]: + """ + Executes a user-provided R script that utilizes the Bioconductor GenomicAlignments package. + + The GenomicAlignments package is an R library and does not expose a direct + command-line interface with subcommands in the traditional sense. Its + functionalities (e.g., read counting, coverage calculation, junction detection, + working with nucleotide content) are accessed by calling R functions within an + R environment. + + This MCP tool provides a wrapper to execute arbitrary R code that leverages + the GenomicAlignments package. Users are expected to provide the full R script + content, including `library(GenomicAlignments)` and calls to the specific + functions they wish to use. + + Args: + r_script_content: A string containing the R code to execute. This script + should include `library(GenomicAlignments)` and any + necessary calls to its functions. + input_files: An optional list of `Path` objects for input files (e.g., BAM files, + GTF files) that the R script might need. These files will be + symlinked into the temporary execution directory, making them + accessible to the R script by their base filenames. + expected_output_filenames: An optional list of strings, where each string is + the base filename of an output file that the R script + is expected to create in its working directory. The tool + will verify the existence of these files and include + them in the `output_files` result. + r_base_path: The path to the Rscript executable. Defaults to "Rscript", + assuming it's available in the system's PATH. + + Returns: + A dictionary containing: + - "command_executed": The Rscript command used. + - "stdout": Standard output from the R script execution. + - "stderr": Standard error from the R script execution. + - "output_files": A list of `Path` objects to any successfully created + output files. These paths will be absolute paths within + the temporary execution environment, which the MCP + framework will handle for persistence. + - "error": An error message if the command failed. + """ + if not r_script_content: + raise ValueError("R script content cannot be empty.") + + # Create a temporary directory for execution to isolate files and manage outputs + with tempfile.TemporaryDirectory() as tmpdir: + tmpdir_path = Path(tmpdir) + + # Write the R script content to a temporary file + r_script_path = tmpdir_path / "genomicalignments_script.R" + r_script_path.write_text(r_script_content) + + # Prepare input files by symlinking them into the temporary directory + # This makes them accessible to the R script by their base names + if input_files: + for input_file in input_files: + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + # Create a symlink to the input file in the temporary directory + # This avoids copying large files and makes them accessible by name + os.symlink(input_file.resolve(), tmpdir_path / input_file.name) + + command = [r_base_path, str(r_script_path)] + + stdout = "" + stderr = "" + output_files_created: List[Path] = [] + + try: + process = subprocess.run( + command, + cwd=tmpdir_path, # Execute in the temporary directory + capture_output=True, + text=True, + check=True, + ) + stdout = process.stdout + stderr = process.stderr + + # Check for expected output files + if expected_output_filenames: + for filename in expected_output_filenames: + if not isinstance(filename, str) or not filename: + raise ValueError( + f"Invalid expected_output_filenames entry: '{filename}'. " + "Must be a non-empty string." + ) + actual_output_path = tmpdir_path / filename + if actual_output_path.is_file(): + output_files_created.append(actual_output_path) + else: + stderr += ( + f"\nWarning: Expected output file '{filename}' not found " + "in the temporary execution directory." + ) + + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": f"Error: Rscript executable not found at '{r_base_path}'. " + "Please ensure R is installed and Rscript is in your PATH " + "or provide the full path.", + "output_files": [], + "error": f"Rscript executable not found: {r_base_path}", + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": f"R script execution failed with exit code {e.returncode}", + } + except Exception as e: + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": [], + "error": f"An unexpected error occurred: {str(e)}", + } + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files_created, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicalignments/app/bioconductor-genomicalignments_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicalignments/app/bioconductor-genomicalignments_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..23f79193154821320b08919a52ce5d6b54c51881 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicalignments/app/bioconductor-genomicalignments_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_manual_txt/mcp_bioconductor-genomicalignments/app/bioconductor-genomicalignments_server.py') +SERVER_NAME = 'biosci_bioconductor_genomicalignments' + + +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_manual_txt/mcp_bioconductor-genomicalignments/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicalignments/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicalignments/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicalignments/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicalignments/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..abb740c24ddfef04f23dc41a049518a7b7c7e21f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicalignments/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-genomicalignments: + build: . + image: mcp-bioconductor-genomicalignments:latest + container_name: mcp-bioconductor-genomicalignments + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-genomicalignments + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicalignments/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicalignments/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0d43bf092a97ea39850977042b15a1c8a2d642c7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicalignments/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-genomicalignments + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicalignments/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicalignments/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicalignments/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicfeatures/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicfeatures/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9ce330750f20d1fec8196e0bc3c8a1de5fbd3e99 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicfeatures/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-genomicfeatures via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-genomicfeatures -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-genomicfeatures_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-genomicfeatures_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-genomicfeatures_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicfeatures/app/bioconductor-genomicfeatures_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicfeatures/app/bioconductor-genomicfeatures_server.py new file mode 100644 index 0000000000000000000000000000000000000000..148f17a16e5580810a889e3dacb04112358ad16a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicfeatures/app/bioconductor-genomicfeatures_server.py @@ -0,0 +1,184 @@ +import subprocess +import tempfile +import logging +from pathlib import Path +from typing import Optional, Literal + +# Configure logging +logging.basicConfig(level=logging.INFO) + +# @mcp.tool() decorator would be here in a real MCP environment +def extract_genomic_features( + source_type: Literal["gff", "ucsc", "biomart"], + feature_type: Literal["genes", "transcripts", "exons", "cds", "introns", "promoters"], + output_file: Path, + gff_file: Optional[Path] = None, + ucsc_genome: Optional[str] = None, + ucsc_tablename: Optional[str] = None, + biomart_dataset: Optional[str] = None, + biomart_host: str = "https://www.ensembl.org", + output_format: Literal["bed", "gff3", "gtf"] = "gff3", + organism: Optional[str] = None, + chrominfo_file: Optional[Path] = None, + data_source: Optional[str] = None, + species: Optional[str] = None, + transcript_name_column: Optional[str] = None, + geneid_name_column: Optional[str] = None, + promoter_upstream: int = 2000, + promoter_downstream: int = 200, + single_strand_genes_only: bool = True, +) -> dict: + """ + Extracts genomic features from a gene model source using Bioconductor's GenomicFeatures package. + + This tool creates a transcript database (TxDb) from a GFF/GTF file, UCSC Genome Browser, + or a BioMart database, and then extracts specified features like genes, exons, or promoters, + saving them to a file. + + Args: + source_type: The source of the gene models ('gff', 'ucsc', or 'biomart'). + feature_type: The type of genomic feature to extract. + output_file: Path to the output file where features will be saved. + gff_file: Path to the input GFF or GTF file (required if source_type is 'gff'). + ucsc_genome: UCSC genome assembly name, e.g., 'hg19' (required if source_type is 'ucsc'). + ucsc_tablename: UCSC table name, e.g., 'knownGene' (required if source_type is 'ucsc'). + biomart_dataset: BioMart dataset name, e.g., 'hsapiens_gene_ensembl' (required if source_type is 'biomart'). + biomart_host: The base URL of the BioMart host. + output_format: The format for the output file ('bed', 'gff3', or 'gtf'). + organism: The scientific name of the organism, e.g., 'Homo sapiens'. + chrominfo_file: A tab-separated file with chromosome names and lengths. + data_source: A string describing the source of the data. + species: The species name, e.g., 'Human'. + transcript_name_column: For GFF files, the attribute column containing the transcript name. + geneid_name_column: For GFF files, the attribute column containing the gene ID. + promoter_upstream: For 'promoters' feature_type, the number of bases upstream of the TSS. + promoter_downstream: For 'promoters' feature_type, the number of bases downstream of the TSS. + single_strand_genes_only: For 'genes' feature_type, whether to ignore genes on both strands. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if source_type == "gff": + if not gff_file: + raise ValueError("`gff_file` is required when `source_type` is 'gff'.") + if not gff_file.is_file(): + raise FileNotFoundError(f"GFF file not found: {gff_file}") + elif source_type == "ucsc": + if not ucsc_genome or not ucsc_tablename: + raise ValueError("`ucsc_genome` and `ucsc_tablename` are required when `source_type` is 'ucsc'.") + elif source_type == "biomart": + if not biomart_dataset: + raise ValueError("`biomart_dataset` is required when `source_type` is 'biomart'.") + else: + # This case should be caught by Literal, but included for robustness + raise ValueError(f"Invalid `source_type`: {source_type}") + + if chrominfo_file and not chrominfo_file.is_file(): + raise FileNotFoundError(f"Chromosome info file not found: {chrominfo_file}") + + if promoter_upstream < 0 or promoter_downstream < 0: + raise ValueError("`promoter_upstream` and `promoter_downstream` must be non-negative.") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + # --- R Script Generation --- + r_script_lines = [ + "library(GenomicFeatures)", + "library(rtracklayer)", + "", + "# Wrap in tryCatch for robust error handling", + "tryCatch({", + ] + + # Part 1: Create TxDb object + txdb_creation_lines = [] + if source_type == "gff": + args = [f'file = "{gff_file}"'] + if data_source: args.append(f'dataSource = "{data_source}"') + if organism: args.append(f'organism = "{organism}"') + if species: args.append(f'species = "{species}"') + if chrominfo_file: + txdb_creation_lines.append(f'chrominfo_df <- read.table("{chrominfo_file}", sep="\\t", col.names=c("chrom", "length"))') + args.append('chrominfo = chrominfo_df') + if transcript_name_column: args.append(f'transcript_name.column = "{transcript_name_column}"') + if geneid_name_column: args.append(f'geneid.column = "{geneid_name_column}"') + txdb_creation_lines.append(f" txdb <- makeTxDbFromGFF({', '.join(args)})") + elif source_type == "ucsc": + args = [f'genome = "{ucsc_genome}"', f'tablename = "{ucsc_tablename}"'] + if organism: args.append(f'organism = "{organism}"') + txdb_creation_lines.append(f" txdb <- makeTxDbFromUCSC({', '.join(args)})") + elif source_type == "biomart": + args = [f'biomart = "ensembl"', f'dataset = "{biomart_dataset}"', f'host = "{biomart_host}"'] + if organism: args.append(f'organism = "{organism}"') + txdb_creation_lines.append(f" txdb <- makeTxDbFromBiomart({', '.join(args)})") + + r_script_lines.extend(txdb_creation_lines) + + # Part 2: Extract Features + r_bool = "TRUE" if single_strand_genes_only else "FALSE" + feature_map = { + "genes": f"genes(txdb, single.strand.genes.only = {r_bool})", + "transcripts": "transcripts(txdb)", + "exons": "exons(txdb)", + "cds": "cds(txdb)", + "introns": "unlist(intronsByTranscript(txdb))", + "promoters": f"promoters(txdb, upstream = {promoter_upstream}, downstream = {promoter_downstream})" + } + r_script_lines.append(f" features <- {feature_map[feature_type]}") + + # Part 3: Export Results + r_script_lines.append(f' rtracklayer::export(features, "{output_file}", format = "{output_format}")') + + # Finalize R script with error handling + r_script_lines.extend([ + " cat('Feature extraction completed successfully.\\n')", + "}, error = function(e) {", + " cat(paste('Error in R script:', e$message, '\\n'), file = stderr())", + " quit(status = 1, save = 'no')", + "})" + ]) + + r_script = "\n".join(r_script_lines) + + # --- Subprocess Execution --- + command_executed = "" + stdout_str = "" + stderr_str = "" + + try: + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R") as tmp_script: + tmp_script.write(r_script) + script_path = tmp_script.name + + command = ["Rscript", script_path] + command_executed = " ".join(command) + logging.info(f"Executing command: {command_executed}") + + process = subprocess.run( + command, + 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: + logging.error(f"R script execution failed with exit code {e.returncode}") + logging.error(f"STDOUT: {e.stdout}") + logging.error(f"STDERR: {e.stderr}") + raise + finally: + # Clean up the temporary R script file + if 'script_path' in locals() and Path(script_path).exists(): + Path(script_path).unlink() + + return { + "command_executed": command_executed, + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": [str(output_file)] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicfeatures/app/bioconductor-genomicfeatures_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicfeatures/app/bioconductor-genomicfeatures_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..88f2161dda065e59e7b8fda74c50304cb47f27b9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicfeatures/app/bioconductor-genomicfeatures_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_manual_txt/mcp_bioconductor-genomicfeatures/app/bioconductor-genomicfeatures_server.py') +SERVER_NAME = 'biosci_bioconductor_genomicfeatures' + + +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_manual_txt/mcp_bioconductor-genomicfeatures/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicfeatures/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicfeatures/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicfeatures/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicfeatures/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..0ed64c15246a6e42f3ed448bcf13f62762db3b12 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicfeatures/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-genomicfeatures: + build: . + image: mcp-bioconductor-genomicfeatures:latest + container_name: mcp-bioconductor-genomicfeatures + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-genomicfeatures + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicfeatures/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicfeatures/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..077be5894b7e52c31a6f405538213f1090d401b7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicfeatures/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-genomicfeatures + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicfeatures/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicfeatures/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicfeatures/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicranges/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicranges/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a783e9fd7d22fd481ab343307f3a69bcaebf197c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicranges/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-genomicranges via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-genomicranges -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-genomicranges_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-genomicranges_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-genomicranges_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicranges/app/bioconductor-genomicranges_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicranges/app/bioconductor-genomicranges_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1e1d3a27c9f81ce92926563424c7bcbe5c95bb3a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicranges/app/bioconductor-genomicranges_server.py @@ -0,0 +1,344 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Dict, Any, Union + +def _run_r_command(r_code: str) -> Dict[str, Any]: + """ + Helper function to execute R code via Rscript. + """ + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + # Ensure GenomicRanges and rtracklayer are loaded + full_code = f"library(GenomicRanges); library(rtracklayer); {r_code}" + tmp.write(full_code) + tmp_path = tmp.name + + try: + result = subprocess.run( + ["Rscript", tmp_path], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript {tmp_path}", + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript {tmp_path}", + "stdout": e.stdout, + "stderr": e.stderr, + "status": "error", + "error_msg": str(e) + } + finally: + if Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def granges_reduce( + input_file: str, + output_file: str, + min_gapwidth: int = 1, + ignore_strand: bool = False, + with_revmap: bool = False +): + """ + Merge overlapping and adjacent genomic ranges into a single range. + Equivalent to GenomicRanges::reduce(). + """ + input_path = Path(input_file) + if not input_path.exists(): + raise FileNotFoundError(f"Input file {input_file} not found.") + + r_code = f""" + gr <- import("{input_file}") + reduced <- reduce(gr, min.gapwidth={min_gapwidth}, ignore.strand={str(ignore_strand).upper()}, with.revmap={str(with_revmap).upper()}) + export(reduced, "{output_file}") + """ + + res = _run_r_command(r_code) + res["output_files"] = [output_file] + return res + +@mcp.tool() +def granges_intersect( + query_file: str, + subject_file: str, + output_file: str, + ignore_strand: bool = False +): + """ + Find the intersection of two sets of genomic ranges. + Equivalent to GenomicRanges::intersect(). + """ + for f in [query_file, subject_file]: + if not Path(f).exists(): + raise FileNotFoundError(f"File {f} not found.") + + r_code = f""" + q <- import("{query_file}") + s <- import("{subject_file}") + res <- intersect(q, s, ignore.strand={str(ignore_strand).upper()}) + export(res, "{output_file}") + """ + + res = _run_r_command(r_code) + res["output_files"] = [output_file] + return res + +@mcp.tool() +def granges_union( + query_file: str, + subject_file: str, + output_file: str, + ignore_strand: bool = False +): + """ + Find the union of two sets of genomic ranges. + Equivalent to GenomicRanges::union(). + """ + for f in [query_file, subject_file]: + if not Path(f).exists(): + raise FileNotFoundError(f"File {f} not found.") + + r_code = f""" + q <- import("{query_file}") + s <- import("{subject_file}") + res <- union(q, s, ignore.strand={str(ignore_strand).upper()}) + export(res, "{output_file}") + """ + + res = _run_r_command(r_code) + res["output_files"] = [output_file] + return res + +@mcp.tool() +def granges_setdiff( + query_file: str, + subject_file: str, + output_file: str, + ignore_strand: bool = False +): + """ + Find the set difference between two sets of genomic ranges (query - subject). + Equivalent to GenomicRanges::setdiff(). + """ + for f in [query_file, subject_file]: + if not Path(f).exists(): + raise FileNotFoundError(f"File {f} not found.") + + r_code = f""" + q <- import("{query_file}") + s <- import("{subject_file}") + res <- setdiff(q, s, ignore.strand={str(ignore_strand).upper()}) + export(res, "{output_file}") + """ + + res = _run_r_command(r_code) + res["output_files"] = [output_file] + return res + +@mcp.tool() +def granges_find_overlaps( + query_file: str, + subject_file: str, + output_csv: str, + min_overlap: int = 1, + type: str = "any", + select: str = "all", + ignore_strand: bool = False +): + """ + Find overlaps between query and subject ranges. Returns a CSV of hit indices. + type: 'any', 'start', 'end', 'within', 'equal' + select: 'all', 'first', 'last', 'arbitrary' + """ + if type not in ["any", "start", "end", "within", "equal"]: + raise ValueError("Invalid type. Must be 'any', 'start', 'end', 'within', or 'equal'.") + if select not in ["all", "first", "last", "arbitrary"]: + raise ValueError("Invalid select. Must be 'all', 'first', 'last', or 'arbitrary'.") + + for f in [query_file, subject_file]: + if not Path(f).exists(): + raise FileNotFoundError(f"File {f} not found.") + + r_code = f""" + q <- import("{query_file}") + s <- import("{subject_file}") + hits <- findOverlaps(q, s, minoverlap={min_overlap}, type="{type}", select="{select}", ignore.strand={str(ignore_strand).upper()}) + if ("{select}" == "all") {{ + write.csv(as.data.frame(hits), "{output_csv}", row.names=FALSE) + }} else {{ + write.csv(data.frame(queryHits=seq_along(hits), subjectHits=hits), "{output_csv}", row.names=FALSE) + }} + """ + + res = _run_r_command(r_code) + res["output_files"] = [output_csv] + return res + +@mcp.tool() +def granges_flank( + input_file: str, + output_file: str, + width: int, + start: bool = True, + both: bool = False, + ignore_strand: bool = False +): + """ + Generate flanking regions for each range. + width: width of the flank. + start: if True, flank the start; if False, flank the end. + both: if True, flank both sides. + """ + if width < 0: + raise ValueError("Width must be a non-negative integer.") + + if not Path(input_file).exists(): + raise FileNotFoundError(f"Input file {input_file} not found.") + + r_code = f""" + gr <- import("{input_file}") + flanked <- flank(gr, width={width}, start={str(start).upper()}, both={str(both).upper()}, ignore.strand={str(ignore_strand).upper()}) + export(flanked, "{output_file}") + """ + + res = _run_r_command(r_code) + res["output_files"] = [output_file] + return res + +@mcp.tool() +def granges_resize( + input_file: str, + output_file: str, + width: int, + fix: str = "start", + ignore_strand: bool = False +): + """ + Resize genomic ranges to a specified width. + fix: 'start', 'end', or 'center' + """ + if fix not in ["start", "end", "center"]: + raise ValueError("fix must be 'start', 'end', or 'center'.") + if width < 0: + raise ValueError("Width must be a non-negative integer.") + + if not Path(input_file).exists(): + raise FileNotFoundError(f"Input file {input_file} not found.") + + r_code = f""" + gr <- import("{input_file}") + resized <- resize(gr, width={width}, fix="{fix}", ignore.strand={str(ignore_strand).upper()}) + export(resized, "{output_file}") + """ + + res = _run_r_command(r_code) + res["output_files"] = [output_file] + return res + +@mcp.tool() +def granges_shift( + input_file: str, + output_file: str, + shift: int = 0 +): + """ + Shift genomic ranges by a specified number of nucleotides. + """ + if not Path(input_file).exists(): + raise FileNotFoundError(f"Input file {input_file} not found.") + + r_code = f""" + gr <- import("{input_file}") + shifted <- shift(gr, shift={shift}) + export(shifted, "{output_file}") + """ + + res = _run_r_command(r_code) + res["output_files"] = [output_file] + return res + +@mcp.tool() +def granges_coverage( + input_file: str, + output_bw: str +): + """ + Calculate coverage across the genome and export as BigWig. + Note: Requires chromosome lengths to be present in the input or inferred. + """ + if not Path(input_file).exists(): + raise FileNotFoundError(f"Input file {input_file} not found.") + + r_code = f""" + gr <- import("{input_file}") + cov <- coverage(gr) + export(cov, "{output_bw}", format="bigWig") + """ + + res = _run_r_command(r_code) + res["output_files"] = [output_bw] + return res + +@mcp.tool() +def granges_gaps( + input_file: str, + output_file: str, + start: int = 1, + end: Optional[int] = None +): + """ + Find the gaps (uncovered regions) between ranges. + """ + if not Path(input_file).exists(): + raise FileNotFoundError(f"Input file {input_file} not found.") + + end_val = f", end={end}" if end is not None else "" + + r_code = f""" + gr <- import("{input_file}") + gp <- gaps(gr, start={start}{end_val}) + export(gp, "{output_file}") + """ + + res = _run_r_command(r_code) + res["output_files"] = [output_file] + return res + +@mcp.tool() +def granges_narrow( + input_file: str, + output_file: str, + start: int = 1, + end: Optional[int] = None, + width: Optional[int] = None +): + """ + Narrow genomic ranges by providing relative start/end/width. + """ + if not Path(input_file).exists(): + raise FileNotFoundError(f"Input file {input_file} not found.") + + params = [f"start={start}"] + if end is not None: + params.append(f"end={end}") + if width is not None: + params.append(f"width={width}") + + param_str = ", ".join(params) + + r_code = f""" + gr <- import("{input_file}") + narrowed <- narrow(gr, {param_str}) + export(narrowed, "{output_file}") + """ + + res = _run_r_command(r_code) + res["output_files"] = [output_file] + return res \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicranges/app/bioconductor-genomicranges_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicranges/app/bioconductor-genomicranges_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..396db8452c5bc29a0afa7cd27b03b6260776a3ee --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicranges/app/bioconductor-genomicranges_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_manual_txt/mcp_bioconductor-genomicranges/app/bioconductor-genomicranges_server.py') +SERVER_NAME = 'biosci_bioconductor_genomicranges' + + +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_manual_txt/mcp_bioconductor-genomicranges/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicranges/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicranges/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicranges/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicranges/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e81d4f5f098f9b6f1bc4fc6a0ce0235bf53b0514 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicranges/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-genomicranges: + build: . + image: mcp-bioconductor-genomicranges:latest + container_name: mcp-bioconductor-genomicranges + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-genomicranges + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicranges/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicranges/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6ffc91febb91701103946099d3bc44d0d4de7675 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicranges/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-genomicranges + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicranges/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicranges/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-genomicranges/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geomxtools/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geomxtools/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e7d23553fd16ce1626a84fcd3ab533e663d65307 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geomxtools/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-geomxtools via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-geomxtools -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-geomxtools_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-geomxtools_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-geomxtools_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geomxtools/app/bioconductor-geomxtools_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geomxtools/app/bioconductor-geomxtools_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7938087765354a4f310559016a2809375e7f9960 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geomxtools/app/bioconductor-geomxtools_server.py @@ -0,0 +1,680 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# In a real MCP environment, this would be imported. +# from mcp import tool as mcp_tool +# For this exercise, we assume the decorator @mcp.tool() is available. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +@mcp.tool() +def read_nanostring_geomx_set( + dcc_files_dir: Path, + pkc_files: List[Path], + pheno_data_file: Path, + output_rds_path: Path, + pheno_data_sheet: Optional[str] = None, + pheno_data_dcc_col_name: str = "Sample_ID", + protocol_data_col_names: Optional[List[str]] = None, + experiment_data_col_names: Optional[List[str]] = None, +) -> dict: + """ + Reads NanoString GeoMx files (DCC, PKC, annotation) and creates a NanoStringGeomxSet object. + + This tool is a wrapper around the `readNanoStringGeoMxSet` function from the + R/Bioconductor package `GeomxTools`. It processes raw data into a structured + R object for downstream analysis. + + Args: + dcc_files_dir: Path to the directory containing DCC files. + pkc_files: A list of paths to PKC files. + pheno_data_file: Path to the sample annotation file (e.g., an Excel file). + output_rds_path: Path for the output RDS file which will contain the NanoStringGeomxSet object. + pheno_data_sheet: Optional name of the worksheet in the Excel annotation file. + pheno_data_dcc_col_name: Column name in the annotation file that matches DCC file names. + protocol_data_col_names: Optional list of column names in annotation to be added to protocolData. + experiment_data_col_names: Optional list of column names in annotation to be added to experimentData. + + Returns: + A dictionary containing the execution command, stdout, stderr, and the path to the output RDS file. + """ + # --- Input Validation --- + if not dcc_files_dir.is_dir(): + raise ValueError(f"DCC files directory not found: {dcc_files_dir}") + if not pkc_files: + raise ValueError("At least one PKC file must be provided.") + for pkc_file in pkc_files: + if not pkc_file.is_file(): + raise ValueError(f"PKC file not found: {pkc_file}") + if not pheno_data_file.is_file(): + raise ValueError(f"Phenotype data file not found: {pheno_data_file}") + + output_rds_path.parent.mkdir(parents=True, exist_ok=True) + + # --- R Script Generation --- + # Safely create R vectors from Python lists + r_protocol_cols = f'c({", ".join(f"{col}" for col in protocol_data_col_names)})' if protocol_data_col_names else "NULL" + r_experiment_cols = f'c({", ".join(f"{col}" for col in experiment_data_col_names)})' if experiment_data_col_names else "NULL" + r_pheno_sheet = f'"{pheno_data_sheet}"' if pheno_data_sheet else "NULL" + pkc_files_r_vector = f'c({", ".join(f"{str(p)}" for p in pkc_files)})' + + r_script_content = f""" + library(GeomxTools) + + tryCatch({{ + dcc_dir <- "{dcc_files_dir}" + pkc_files_vec <- {pkc_files_r_vector} + pheno_file <- "{pheno_data_file}" + output_path <- "{output_rds_path}" + pheno_dcc_col <- "{pheno_data_dcc_col_name}" + + dcc_files <- list.files(dcc_dir, pattern = "\\\\.dcc$", full.names = TRUE, recursive = TRUE) + if (length(dcc_files) == 0) {{ + stop("No .dcc files found in the specified directory.") + }} + + geomx_data <- readNanoStringGeoMxSet( + dccFiles = dcc_files, + pkcFiles = pkc_files_vec, + phenoDataFile = pheno_file, + phenoDataSheet = {r_pheno_sheet}, + phenoDataDccColName = pheno_dcc_col, + protocolDataColNames = {r_protocol_cols}, + experimentDataColNames = {r_experiment_cols} + ) + + saveRDS(geomx_data, file = output_path) + cat("Successfully created NanoStringGeomxSet object and saved to", output_path, "\\n") + }}, error = function(e) {{ + message("R script failed with error: ", e$message) + quit(status = 1) + }}) + """ + + # --- Subprocess Execution --- + command_executed = "" + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, encoding='utf-8') as r_script_file: + r_script_file.write(r_script_content) + r_script_path = r_script_file.name + + cmd = ["Rscript", r_script_path] + command_executed = " ".join(cmd) + + process = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_rds_path)] + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode, + "output_files": [] + } + finally: + if 'r_script_path' in locals() and Path(r_script_path).exists(): + Path(r_script_path).unlink() + +@mcp.tool() +def set_segment_qc_flags( + input_rds_path: Path, + output_rds_path: Path, + min_segment_reads: Optional[int] = 1000, + percent_aligned: Optional[float] = 80, + percent_saturation: Optional[float] = 50, + min_negative_count: Optional[int] = 10, + max_ntc_count: Optional[int] = 1000, + min_nuclei: Optional[int] = 200, + min_area: Optional[int] = 16000, +) -> dict: + """ + Sets segment QC flags in a NanoStringGeomxSet object based on specified cutoffs. + + Args: + input_rds_path: Path to the input RDS file containing a NanoStringGeomxSet object. + output_rds_path: Path for the output RDS file with QC flags applied. + min_segment_reads: Minimum number of reads in a segment. + percent_aligned: Minimum percentage of reads aligned. + percent_saturation: Minimum percentage of reads saturated. + min_negative_count: Minimum negative probe counts. + max_ntc_count: Maximum counts observed in NTC wells. + min_nuclei: Minimum number of nuclei in a segment. + min_area: Minimum area of a segment. + + Returns: + A dictionary containing the execution command, stdout, stderr, and the path to the output RDS file. + """ + # --- Input Validation --- + if not input_rds_path.is_file(): + raise ValueError(f"Input RDS file not found: {input_rds_path}") + output_rds_path.parent.mkdir(parents=True, exist_ok=True) + + # --- R Script Generation --- + r_script_content = f""" + library(GeomxTools) + + tryCatch({{ + input_rds <- "{input_rds_path}" + output_rds <- "{output_rds_path}" + + geomx_data <- readRDS(input_rds) + + qc_cutoffs <- list() + if (!is.null({min_segment_reads or 'NULL'})) {{ qc_cutoffs$minSegmentReads <- {min_segment_reads} }} + if (!is.null({percent_aligned or 'NULL'})) {{ qc_cutoffs$percentAligned <- {percent_aligned} }} + if (!is.null({percent_saturation or 'NULL'})) {{ qc_cutoffs$percentSaturation <- {percent_saturation} }} + if (!is.null({min_negative_count or 'NULL'})) {{ qc_cutoffs$minNegativeCount <- {min_negative_count} }} + if (!is.null({max_ntc_count or 'NULL'})) {{ qc_cutoffs$maxNTCCount <- {max_ntc_count} }} + if (!is.null({min_nuclei or 'NULL'})) {{ qc_cutoffs$minNuclei <- {min_nuclei} }} + if (!is.null({min_area or 'NULL'})) {{ qc_cutoffs$minArea <- {min_area} }} + + geomx_data_qc <- setSegmentQCFlags(geomx_data, qcCutoffs = qc_cutoffs) + + saveRDS(geomx_data_qc, file = output_rds) + cat("Successfully applied segment QC flags and saved to", output_rds, "\\n") + }}, error = function(e) {{ + message("R script failed with error: ", e$message) + quit(status = 1) + }}) + """ + + # --- Subprocess Execution --- + command_executed = "" + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, encoding='utf-8') as r_script_file: + r_script_file.write(r_script_content) + r_script_path = r_script_file.name + + cmd = ["Rscript", r_script_path] + command_executed = " ".join(cmd) + + process = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_rds_path)] + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode, + "output_files": [] + } + finally: + if 'r_script_path' in locals() and Path(r_script_path).exists(): + Path(r_script_path).unlink() + +@mcp.tool() +def set_bioprobe_qc_flags( + input_rds_path: Path, + output_rds_path: Path, + min_probe_ratio: float = 0.1, + percent_fail_grubbs: float = 20, + remove_local_outliers: bool = True, +) -> dict: + """ + Sets probe QC flags in a NanoStringGeomxSet object. + + Args: + input_rds_path: Path to the input RDS file containing a NanoStringGeomxSet object. + output_rds_path: Path for the output RDS file with QC flags applied. + min_probe_ratio: Minimum ratio of probes to the geometric mean of all probes. + percent_fail_grubbs: Percentage of segments that must fail Grubbs test for a probe to be flagged. + remove_local_outliers: If TRUE, local outliers will be removed. + + Returns: + A dictionary containing the execution command, stdout, stderr, and the path to the output RDS file. + """ + # --- Input Validation --- + if not input_rds_path.is_file(): + raise ValueError(f"Input RDS file not found: {input_rds_path}") + output_rds_path.parent.mkdir(parents=True, exist_ok=True) + + # --- R Script Generation --- + r_script_content = f""" + library(GeomxTools) + + tryCatch({{ + input_rds <- "{input_rds_path}" + output_rds <- "{output_rds_path}" + + geomx_data <- readRDS(input_rds) + + qc_cutoffs <- list( + minProbeRatio = {min_probe_ratio}, + percentFailGrubbs = {percent_fail_grubbs} + ) + + geomx_data_qc <- setBioProbeQCFlags( + geomx_data, + qcCutoffs = qc_cutoffs, + removeLocalOutliers = {str(remove_local_outliers).upper()} + ) + + saveRDS(geomx_data_qc, file = output_rds) + cat("Successfully applied bioprobe QC flags and saved to", output_rds, "\\n") + }}, error = function(e) {{ + message("R script failed with error: ", e$message) + quit(status = 1) + }}) + """ + + # --- Subprocess Execution --- + command_executed = "" + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, encoding='utf-8') as r_script_file: + r_script_file.write(r_script_content) + r_script_path = r_script_file.name + + cmd = ["Rscript", r_script_path] + command_executed = " ".join(cmd) + + process = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_rds_path)] + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode, + "output_files": [] + } + finally: + if 'r_script_path' in locals() and Path(r_script_path).exists(): + Path(r_script_path).unlink() + +@mcp.tool() +def subset_geomx_set( + input_rds_path: Path, + output_rds_path: Path, + subset_by_pdata: bool = True, + subset_column: Optional[str] = None, + subset_values: Optional[List[str]] = None, +) -> dict: + """ + Subsets a NanoStringGeomxSet object based on phenotype (pData) or feature (fData) annotations. + + Args: + input_rds_path: Path to the input RDS file containing a NanoStringGeomxSet object. + output_rds_path: Path for the output subsetted RDS file. + subset_by_pdata: If True, subset by sample annotations (pData). If False, subset by feature annotations (fData). + subset_column: The column name in pData or fData to use for subsetting. + subset_values: A list of values to keep from the subset_column. + + Returns: + A dictionary containing the execution command, stdout, stderr, and the path to the output RDS file. + """ + # --- Input Validation --- + if not input_rds_path.is_file(): + raise ValueError(f"Input RDS file not found: {input_rds_path}") + if not subset_column or not subset_values: + raise ValueError("subset_column and subset_values must be provided for subsetting.") + output_rds_path.parent.mkdir(parents=True, exist_ok=True) + + # --- R Script Generation --- + subset_values_r = f'c({", ".join(f"{v}" for v in subset_values)})' + + r_script_content = f""" + library(GeomxTools) + library(Biobase) + + tryCatch({{ + object <- readRDS("{input_rds_path}") + subset_col <- "{subset_column}" + subset_vals <- {subset_values_r} + + if ({str(subset_by_pdata).upper()}) {{ + logic <- pData(object)[[subset_col]] %in% subset_vals + logic[is.na(logic)] <- FALSE + subset_object <- object[, logic] + }} else {{ + logic <- fData(object)[[subset_col]] %in% subset_vals + logic[is.na(logic)] <- FALSE + subset_object <- object[logic, ] + }} + + saveRDS(subset_object, file = "{output_rds_path}") + cat("Successfully subset object and saved to", "{output_rds_path}", "\\n") + }}, error = function(e) {{ + message("R script failed with error: ", e$message) + quit(status = 1) + }}) + """ + + # --- Subprocess Execution --- + command_executed = "" + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, encoding='utf-8') as r_script_file: + r_script_file.write(r_script_content) + r_script_path = r_script_file.name + + cmd = ["Rscript", r_script_path] + command_executed = " ".join(cmd) + + process = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_rds_path)] + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode, + "output_files": [] + } + finally: + if 'r_script_path' in locals() and Path(r_script_path).exists(): + Path(r_script_path).unlink() + +@mcp.tool() +def aggregate_counts( + input_rds_path: Path, + output_rds_path: Path, + elt: str = "exprs", +) -> dict: + """ + Aggregates probe-level counts to the target level in a NanoStringGeomxSet object. + + Args: + input_rds_path: Path to the input RDS file containing a NanoStringGeomxSet object. + output_rds_path: Path for the output RDS file with aggregated counts. + elt: The name of the assay data element to aggregate. + + Returns: + A dictionary containing the execution command, stdout, stderr, and the path to the output RDS file. + """ + # --- Input Validation --- + if not input_rds_path.is_file(): + raise ValueError(f"Input RDS file not found: {input_rds_path}") + output_rds_path.parent.mkdir(parents=True, exist_ok=True) + + # --- R Script Generation --- + r_script_content = f""" + library(GeomxTools) + + tryCatch({{ + geomx_data <- readRDS("{input_rds_path}") + aggregated_data <- aggregateCounts(geomx_data, elt = "{elt}") + + saveRDS(aggregated_data, file = "{output_rds_path}") + cat("Successfully aggregated counts and saved to", "{output_rds_path}", "\\n") + }}, error = function(e) {{ + message("R script failed with error: ", e$message) + quit(status = 1) + }}) + """ + + # --- Subprocess Execution --- + command_executed = "" + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, encoding='utf-8') as r_script_file: + r_script_file.write(r_script_content) + r_script_path = r_script_file.name + + cmd = ["Rscript", r_script_path] + command_executed = " ".join(cmd) + + process = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_rds_path)] + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode, + "output_files": [] + } + finally: + if 'r_script_path' in locals() and Path(r_script_path).exists(): + Path(r_script_path).unlink() + +@mcp.tool() +def normalize_geomx( + input_rds_path: Path, + output_rds_path: Path, + norm_method: str, + from_elt: str = "exprs", + to_elt: str = "exprs_norm", + housekeepers: Optional[List[str]] = None, +) -> dict: + """ + Normalizes the count data in a NanoStringGeomxSet object. + + Args: + input_rds_path: Path to the input RDS file containing a NanoStringGeomxSet object. + output_rds_path: Path for the output RDS file with normalized data. + norm_method: Normalization method. Must be one of 'quant', 'neg', 'hk'. + from_elt: The assay data element to use for normalization. + to_elt: The name of the new assay data element to store normalized values. + housekeepers: A list of housekeeper gene names, required if norm_method is 'hk'. + + Returns: + A dictionary containing the execution command, stdout, stderr, and the path to the output RDS file. + """ + # --- Input Validation --- + if not input_rds_path.is_file(): + raise ValueError(f"Input RDS file not found: {input_rds_path}") + + valid_methods = ["quant", "neg", "hk"] + if norm_method not in valid_methods: + raise ValueError(f"Invalid norm_method '{norm_method}'. Must be one of {valid_methods}.") + + if norm_method == "hk" and not housekeepers: + raise ValueError("Housekeeper genes must be provided for 'hk' normalization.") + + output_rds_path.parent.mkdir(parents=True, exist_ok=True) + + housekeepers_r = f'c({", ".join(f"{hk}" for hk in housekeepers)})' if housekeepers else "NULL" + + # --- R Script Generation --- + r_script_content = f""" + library(GeomxTools) + + tryCatch({{ + geomx_data <- readRDS("{input_rds_path}") + + normalized_data <- normalize( + geomx_data, + norm.method = "{norm_method}", + fromElt = "{from_elt}", + toElt = "{to_elt}", + housekeepers = {housekeepers_r} + ) + + saveRDS(normalized_data, file = "{output_rds_path}") + cat("Successfully normalized data and saved to", "{output_rds_path}", "\\n") + }}, error = function(e) {{ + message("R script failed with error: ", e$message) + quit(status = 1) + }}) + """ + + # --- Subprocess Execution --- + command_executed = "" + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, encoding='utf-8') as r_script_file: + r_script_file.write(r_script_content) + r_script_path = r_script_file.name + + cmd = ["Rscript", r_script_path] + command_executed = " ".join(cmd) + + process = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_rds_path)] + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode, + "output_files": [] + } + finally: + if 'r_script_path' in locals() and Path(r_script_path).exists(): + Path(r_script_path).unlink() + +@mcp.tool() +def mixed_model_de( + input_rds_path: Path, + output_csv_path: Path, + elt: str, + model_formula_fixed: str, + group_var: str, + model_formula_random: Optional[str] = None, + contrasts: Optional[List[str]] = None, + n_cores: int = 1, +) -> dict: + """ + Performs differential expression analysis using a linear mixed model. + + Args: + input_rds_path: Path to the input RDS file containing a NanoStringGeomxSet object. + output_csv_path: Path for the output CSV file with DE results. + elt: The assay data element to use for the analysis (e.g., 'exprs_norm'). + model_formula_fixed: The fixed effects part of the model formula (e.g., 'region + diseaseStatus'). + group_var: The main variable of interest for testing (e.g., 'diseaseStatus'). + model_formula_random: The random effects part of the model formula (e.g., '(1|slideName)'). + contrasts: A list of contrasts to test (e.g., ['diseaseA - diseaseB', 'diseaseC - diseaseB']). + n_cores: Number of cores to use for parallel processing. + + Returns: + A dictionary containing the execution command, stdout, stderr, and the path to the output CSV file. + """ + # --- Input Validation --- + if not input_rds_path.is_file(): + raise ValueError(f"Input RDS file not found: {input_rds_path}") + if n_cores < 1: + raise ValueError("n_cores must be at least 1.") + output_csv_path.parent.mkdir(parents=True, exist_ok=True) + + # --- R Script Generation --- + formula_str = f"~ {model_formula_fixed}" + if model_formula_random: + formula_str += f" + {model_formula_random}" + + contrasts_r = "NULL" + if contrasts: + contrasts_r = f'c({", ".join(f"{c}" for c in contrasts)})' + + r_script_content = f""" + library(GeomxTools) + library(limma) + library(Biobase) + + tryCatch({{ + object <- readRDS("{input_rds_path}") + + model_formula <- as.formula("{formula_str}") + + contrast_matrix <- NULL + if (!is.null({contrasts_r})) {{ + contrast_matrix <- makeContrasts(contrasts = {contrasts_r}, levels = unique(pData(object)[["{group_var}"]])) + }} + + results <- mixedModelDE( + object, + elt = "{elt}", + modelFormula = model_formula, + groupVar = "{group_var}", + nCores = {n_cores}, + multiCore = {str(n_cores > 1).upper()}, + contrasts = contrast_matrix + ) + + write.csv(results, file = "{output_csv_path}", row.names = FALSE) + cat("Successfully performed DE analysis and saved results to", "{output_csv_path}", "\\n") + }}, error = function(e) {{ + message("R script failed with error: ", e$message) + quit(status = 1) + }}) + """ + + # --- Subprocess Execution --- + command_executed = "" + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, encoding='utf-8') as r_script_file: + r_script_file.write(r_script_content) + r_script_path = r_script_file.name + + cmd = ["Rscript", r_script_path] + command_executed = " ".join(cmd) + + process = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_csv_path)] + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode, + "output_files": [] + } + finally: + if 'r_script_path' in locals() and Path(r_script_path).exists(): + Path(r_script_path).unlink() \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geomxtools/app/bioconductor-geomxtools_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geomxtools/app/bioconductor-geomxtools_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..be40c6c3438cfec57312ff321d8f50319cb06bd8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geomxtools/app/bioconductor-geomxtools_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_manual_txt/mcp_bioconductor-geomxtools/app/bioconductor-geomxtools_server.py') +SERVER_NAME = 'biosci_bioconductor_geomxtools' + + +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_manual_txt/mcp_bioconductor-geomxtools/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geomxtools/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..ddcec77dc3ef15c0699109b8924d12c4ccb1737e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geomxtools/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-geomxtools: + build: . + image: mcp-bioconductor-geomxtools:latest + container_name: mcp-bioconductor-geomxtools + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-geomxtools + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geomxtools/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geomxtools/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b21e8a4370c5f03f287e02d6c98afab673d9cd6b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geomxtools/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-geomxtools + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geomxtools/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geomxtools/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-geomxtools/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggsc/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggsc/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8e4385ba0e7fd397a459e7260eff11f045abdb1a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggsc/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-ggsc via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-ggsc -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-ggsc_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-ggsc_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-ggsc_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggsc/app/bioconductor-ggsc_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggsc/app/bioconductor-ggsc_server.py new file mode 100644 index 0000000000000000000000000000000000000000..cbffb0b68329713b1e53f28844ac45be84bfec1a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggsc/app/bioconductor-ggsc_server.py @@ -0,0 +1,360 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, List + +# This script assumes the presence of a companion R script (e.g., 'run_ggsc.R') +# that acts as a command-line interface for the 'ggsc' R package. +# The R environment must have 'ggsc', 'SingleCellExperiment', 'ggplot2', +# and an argument parser like 'optparse' installed. +R_SCRIPT_EXECUTABLE = "run_ggsc.R" + +# Per instructions, the @mcp.tool decorator is used. +# A dummy decorator is defined here for syntax validity in a standalone context. +# In a true MCP environment, this would be provided by the MCP framework. +def tool(func): + """Dummy decorator to match the required syntax.""" + return func + +class MCP: + """Dummy class to hold the tool decorator.""" + tool = staticmethod(tool) + +mcp = MCP() + + +@mcp.tool() +def plot_reduced_dim( + input_rds: Path, + output_plot: Path, + dim_red: str, + color_by: str, + facet_by: Optional[str] = None, + plot_title: Optional[str] = None, + img_width: int = 7, + img_height: int = 7 +) -> dict: + """ + Generates a reduced dimension plot (e.g., UMAP, t-SNE) from a SingleCellExperiment object. + + This tool wraps the `plot_reduced_dim_sce` function from the R/Bioconductor package `ggsc`. + The input must be a .rds file containing a SingleCellExperiment object. + + Args: + input_rds: Path to the input RDS file containing a SingleCellExperiment object. + output_plot: Path to save the output plot image (e.g., plot.png). + dim_red: Name of the dimension reduction to use (e.g., "UMAP", "TSNE"). + color_by: Variable in colData to color the points by (e.g., "label", "cluster"). + facet_by: Optional variable in colData to facet the plot by. + plot_title: Optional title for the plot. + img_width: Width of the output image in inches. + img_height: Height of the output image in inches. + + Returns: + A dictionary containing the execution details and output file path. + """ + # --- Input Validation --- + if not input_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {input_rds}") + if img_width <= 0 or img_height <= 0: + raise ValueError("Image width and height must be positive integers.") + + # Ensure output directory exists + output_plot.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd = [ + "Rscript", + R_SCRIPT_EXECUTABLE, + "reduced_dim", + "--input_rds", str(input_rds), + "--output_plot", str(output_plot), + "--dim_red", dim_red, + "--color_by", color_by, + "--img_width", str(img_width), + "--img_height", str(img_height) + ] + + if facet_by: + cmd.extend(["--facet_by", facet_by]) + if plot_title: + cmd.extend(["--plot_title", plot_title]) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + except FileNotFoundError: + raise RuntimeError("Rscript or the wrapper script not found. Please ensure R and the tool's R script are in the system's PATH.") + except subprocess.CalledProcessError as e: + error_message = f"ggsc R script failed for reduced_dim plot.\nSTDOUT: {e.stdout}\nSTDERR: {e.stderr}" + logging.error(error_message) + raise RuntimeError(error_message) from e + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_plot)] + } + + +@mcp.tool() +def plot_gene_expression( + input_rds: Path, + output_plot: Path, + gene: str, + dim_red: str, + assay: str = "logcounts", + plot_title: Optional[str] = None, + img_width: int = 7, + img_height: int = 7 +) -> dict: + """ + Plots the expression of a single gene on a reduced dimension plot. + + This tool wraps the `plot_gene_sce` function from the R/Bioconductor package `ggsc`. + The input must be a .rds file containing a SingleCellExperiment object. + + Args: + input_rds: Path to the input RDS file containing a SingleCellExperiment object. + output_plot: Path to save the output plot image. + gene: The name of the gene to plot. + dim_red: Name of the dimension reduction to use (e.g., "UMAP"). + assay: The assay to use for expression values (default: "logcounts"). + plot_title: Optional title for the plot. + img_width: Width of the output image in inches. + img_height: Height of the output image in inches. + + Returns: + A dictionary containing the execution details and output file path. + """ + # --- Input Validation --- + if not input_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {input_rds}") + if not gene: + raise ValueError("A gene name must be provided.") + if img_width <= 0 or img_height <= 0: + raise ValueError("Image width and height must be positive integers.") + + output_plot.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd = [ + "Rscript", + R_SCRIPT_EXECUTABLE, + "gene_plot", + "--input_rds", str(input_rds), + "--output_plot", str(output_plot), + "--gene", gene, + "--dim_red", dim_red, + "--assay", assay, + "--img_width", str(img_width), + "--img_height", str(img_height) + ] + + if plot_title: + cmd.extend(["--plot_title", plot_title]) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + except FileNotFoundError: + raise RuntimeError("Rscript or the wrapper script not found. Please ensure R and the tool's R script are in the system's PATH.") + except subprocess.CalledProcessError as e: + error_message = f"ggsc R script failed for gene expression plot.\nSTDOUT: {e.stdout}\nSTDERR: {e.stderr}" + logging.error(error_message) + raise RuntimeError(error_message) from e + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_plot)] + } + + +@mcp.tool() +def plot_expression_heatmap( + input_rds: Path, + output_plot: Path, + genes: List[str], + annotation_col: str, + assay: str = "logcounts", + plot_title: Optional[str] = None, + img_width: int = 7, + img_height: int = 10 +) -> dict: + """ + Generates a heatmap of gene expression for a set of genes. + + This tool wraps the `plot_heatmap_sce` function from the R/Bioconductor package `ggsc`. + The input must be a .rds file containing a SingleCellExperiment object. + + Args: + input_rds: Path to the input RDS file containing a SingleCellExperiment object. + output_plot: Path to save the output plot image. + genes: A list of gene names to include in the heatmap. + annotation_col: Column in colData to use for cell annotation. + assay: The assay to use for expression values (default: "logcounts"). + plot_title: Optional title for the plot. + img_width: Width of the output image in inches. + img_height: Height of the output image in inches. + + Returns: + A dictionary containing the execution details and output file path. + """ + # --- Input Validation --- + if not input_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {input_rds}") + if not genes: + raise ValueError("At least one gene must be provided in the list.") + if img_width <= 0 or img_height <= 0: + raise ValueError("Image width and height must be positive integers.") + + output_plot.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + genes_str = ",".join(genes) + cmd = [ + "Rscript", + R_SCRIPT_EXECUTABLE, + "heatmap", + "--input_rds", str(input_rds), + "--output_plot", str(output_plot), + "--genes", genes_str, + "--annotation_col", annotation_col, + "--assay", assay, + "--img_width", str(img_width), + "--img_height", str(img_height) + ] + + if plot_title: + cmd.extend(["--plot_title", plot_title]) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + except FileNotFoundError: + raise RuntimeError("Rscript or the wrapper script not found. Please ensure R and the tool's R script are in the system's PATH.") + except subprocess.CalledProcessError as e: + error_message = f"ggsc R script failed for expression heatmap.\nSTDOUT: {e.stdout}\nSTDERR: {e.stderr}" + logging.error(error_message) + raise RuntimeError(error_message) from e + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_plot)] + } + + +@mcp.tool() +def plot_expression_violin( + input_rds: Path, + output_plot: Path, + gene: str, + group_by: str, + assay: str = "logcounts", + plot_title: Optional[str] = None, + img_width: int = 7, + img_height: int = 5 +) -> dict: + """ + Generates a violin plot of gene expression across different groups. + + This tool wraps the `plot_violin_sce` function from the R/Bioconductor package `ggsc`. + The input must be a .rds file containing a SingleCellExperiment object. + + Args: + input_rds: Path to the input RDS file containing a SingleCellExperiment object. + output_plot: Path to save the output plot image. + gene: The name of the gene to plot. + group_by: Variable in colData to group the violins by (e.g., "cluster"). + assay: The assay to use for expression values (default: "logcounts"). + plot_title: Optional title for the plot. + img_width: Width of the output image in inches. + img_height: Height of the output image in inches. + + Returns: + A dictionary containing the execution details and output file path. + """ + # --- Input Validation --- + if not input_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {input_rds}") + if not gene: + raise ValueError("A gene name must be provided.") + if img_width <= 0 or img_height <= 0: + raise ValueError("Image width and height must be positive integers.") + + output_plot.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd = [ + "Rscript", + R_SCRIPT_EXECUTABLE, + "violin", + "--input_rds", str(input_rds), + "--output_plot", str(output_plot), + "--gene", gene, + "--group_by", group_by, + "--assay", assay, + "--img_width", str(img_width), + "--img_height", str(img_height) + ] + + if plot_title: + cmd.extend(["--plot_title", plot_title]) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + except FileNotFoundError: + raise RuntimeError("Rscript or the wrapper script not found. Please ensure R and the tool's R script are in the system's PATH.") + except subprocess.CalledProcessError as e: + error_message = f"ggsc R script failed for expression violin plot.\nSTDOUT: {e.stdout}\nSTDERR: {e.stderr}" + logging.error(error_message) + raise RuntimeError(error_message) from e + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_plot)] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggsc/app/bioconductor-ggsc_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggsc/app/bioconductor-ggsc_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..cdf9661d130ac447c96d1ccd3f01c7698a2d7bae --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggsc/app/bioconductor-ggsc_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_manual_txt/mcp_bioconductor-ggsc/app/bioconductor-ggsc_server.py') +SERVER_NAME = 'biosci_bioconductor_ggsc' + + +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_manual_txt/mcp_bioconductor-ggsc/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggsc/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..66d94a739f2052f5fb7c429bf4b4e1aec1181186 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggsc/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-ggsc: + build: . + image: mcp-bioconductor-ggsc:latest + container_name: mcp-bioconductor-ggsc + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-ggsc + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggsc/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggsc/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..179d5ec77128b05773abab6ecc408a5b49d85d51 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggsc/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-ggsc + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggsc/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggsc/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggsc/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggspavis/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggspavis/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cce68a8789108203349e557d81008954a56da088 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggspavis/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-ggspavis via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-ggspavis -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-ggspavis_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-ggspavis_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-ggspavis_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggspavis/app/bioconductor-ggspavis_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggspavis/app/bioconductor-ggspavis_server.py new file mode 100644 index 0000000000000000000000000000000000000000..33a6edfd4003ce2829eaf59e57d87b850ddc9f2d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggspavis/app/bioconductor-ggspavis_server.py @@ -0,0 +1,395 @@ +import subprocess +import tempfile +import json +import shlex +from pathlib import Path +from typing import Optional, List, Literal + +# This R script acts as a generic command-line wrapper for ggspavis functions. +# It is written to a temporary file and executed by the Python functions below. +# It dynamically installs required R packages, making the tool self-contained. +R_SCRIPT = """ +# ggspavis_runner.R +# A generic runner for ggspavis functions + +# Suppress startup messages for cleaner output +suppressPackageStartupMessages({ + # Check if packages are installed, install if not + if (!requireNamespace("argparse", quietly = TRUE)) install.packages("argparse", repos = "http://cran.us.r-project.org") + if (!requireNamespace("jsonlite", quietly = TRUE)) install.packages("jsonlite", repos = "http://cran.us.r-project.org") + if (!requireNamespace("ggplot2", quietly = TRUE)) install.packages("ggplot2", repos = "http://cran.us.r-project.org") + if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager", repos = "http://cran.us.r-project.org") + + # Use BiocManager to install Bioconductor packages + if (!requireNamespace("SpatialExperiment", quietly = TRUE)) BiocManager::install("SpatialExperiment", update = FALSE, ask = FALSE) + if (!requireNamespace("ggspavis", quietly = TRUE)) BiocManager::install("ggspavis", update = FALSE, ask = FALSE) +}) + +library(argparse) +library(jsonlite) +library(ggplot2) +library(SpatialExperiment) +library(ggspavis) + +# Main function to parse arguments and call the appropriate ggspavis function +main <- function() { + parser <- ArgumentParser(description = "A command-line wrapper for ggspavis functions.") + + parser$add_argument("func", help = "The ggspavis function to call (e.g., plotSpots, plotFeature).") + parser$add_argument("--spe_path", required = TRUE, help = "Path to the SpatialExperiment object (.rds file).") + parser$add_argument("--output_path", required = TRUE, help = "Path to save the output plot.") + parser$add_argument("--width", type = "double", default = 7, help = "Width of the output plot in inches.") + parser$add_argument("--height", type = "double", default = 7, help = "Height of the output plot in inches.") + parser$add_argument("--json_args", type = "character", default = "{}", help = "A JSON string of arguments for the ggspavis function.") + + args <- parser$parse_args() + + # Load SpatialExperiment object + if (!file.exists(args$spe_path)) { + stop("Input SPE file not found: ", args$spe_path) + } + spe <- readRDS(args$spe_path) + + # Parse JSON arguments for the target function + func_args <- fromJSON(args$json_args) + + # Add the main 'spe' object to the arguments list + func_args <- c(list(spe = spe), func_args) + + # Check if the requested function exists in the ggspavis package + if (!exists(args$func, where = "package:ggspavis", mode = "function")) { + stop("Function '", args$func, "' not found in ggspavis package.") + } + + # Dynamically call the ggspavis function with the parsed arguments + plot_obj <- do.call(args$func, func_args) + + # Save the generated plot to the specified output file + ggsave( + filename = args$output_path, + plot = plot_obj, + width = args$width, + height = args$height, + dpi = 300 + ) + + cat("Plot successfully saved to", args$output_path, "\\n") +} + +# Execute the main function and handle potential errors +tryCatch({ + main() +}, error = function(e) { + message("Error: ", e$message) + quit(status = 1) +}) +""" + +def _run_ggspavis( + function_name: str, + spe_path: Path, + output_path: Path, + plot_width: float, + plot_height: float, + json_args: dict, +) -> dict: + """ + Helper function to execute the ggspavis R script wrapper. + + Args: + function_name: The ggspavis function to execute (e.g., 'plotSpots'). + spe_path: Path to the input SpatialExperiment RDS file. + output_path: Path to save the output plot image. + plot_width: Width of the output plot in inches. + plot_height: Height of the output plot in inches. + json_args: A dictionary of arguments for the ggspavis function. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output file path. + """ + # Ensure output directory exists + output_path.parent.mkdir(parents=True, exist_ok=True) + + # Use a temporary file to store and execute the R script + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_path = Path(r_script_file.name) + r_script_file.write(R_SCRIPT) + + command = [ + "Rscript", + str(r_script_path), + function_name, + "--spe_path", str(spe_path), + "--output_path", str(output_path), + "--width", str(plot_width), + "--height", str(plot_height), + "--json_args", json.dumps(json_args), + ] + + command_executed = " ".join(shlex.quote(c) for c in command) + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + stdout = process.stdout + stderr = process.stderr + output_files = {"plot": str(output_path)} if output_path.exists() else {} + + except FileNotFoundError: + # This error occurs if 'Rscript' is not in the system's PATH + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'Rscript' command not found. Please ensure R is installed and in your system's PATH.", + "output_files": {}, + } + except subprocess.CalledProcessError as e: + # This error occurs if the R script returns a non-zero exit code + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": {}, + } + finally: + # Clean up the temporary R script file + r_script_path.unlink() + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + + +@mcp.tool() +def ggspavis_plot_spots( + spe_path: Path, + output_filename: str, + fill: Optional[str] = None, + highlight: Optional[str] = None, + facet_by: Optional[str] = None, + assay: str = "logcounts", + palette: str = "viridis", + point_size: float = 1.5, + point_alpha: float = 1.0, + plot_width: float = 7.0, + plot_height: float = 7.0, +): + """ + Generates a spatial plot of spots/capture locations using ggspavis::plotSpots. + + Args: + spe_path: Path to the input SpatialExperiment object (.rds file). + output_filename: Name of the output plot file (e.g., 'plot.png'). + fill: Column name in colData or a feature name to use for spot fill color. + highlight: Column name in colData to use for highlighting spots. + facet_by: Column name in colData to use for faceting the plot. + assay: Name of the assay to use if 'fill' is a feature name. + palette: Color palette for continuous values (e.g., 'viridis', 'magma'). + point_size: Size of the points representing spots. + point_alpha: Alpha transparency of the points. + plot_width: Width of the output plot in inches. + plot_height: Height of the output plot in inches. + """ + # Input validation + if not spe_path.is_file(): + raise FileNotFoundError(f"Input file not found: {spe_path}") + if point_size <= 0: + raise ValueError("point_size must be positive.") + if not (0.0 <= point_alpha <= 1.0): + raise ValueError("point_alpha must be between 0.0 and 1.0.") + + # Prepare arguments for the R function + json_args = { + "fill": fill, + "highlight": highlight, + "facet_by": facet_by, + "assay": assay, + "palette": palette, + "point_size": point_size, + "point_alpha": point_alpha, + } + # Filter out None values so they are not passed in the JSON + json_args = {k: v for k, v in json_args.items() if v is not None} + + output_path = Path(output_filename) + + return _run_ggspavis( + function_name="plotSpots", + spe_path=spe_path, + output_path=output_path, + plot_width=plot_width, + plot_height=plot_height, + json_args=json_args, + ) + + +@mcp.tool() +def ggspavis_plot_feature( + spe_path: Path, + output_filename: str, + feature: str, + assay: str = "logcounts", + platform: Literal["Visium", "ST", "VisiumHD", "mIF", "seqFISH", "MERFISH", "Xenium"] = "Visium", + palette: str = "viridis", + point_size: float = 1.5, + plot_width: float = 7.0, + plot_height: float = 7.0, +): + """ + Visualizes the expression of a single feature (e.g., gene) in spatial context using ggspavis::plotFeature. + + Args: + spe_path: Path to the input SpatialExperiment object (.rds file). + output_filename: Name of the output plot file (e.g., 'feature_plot.png'). + feature: Name of the feature (gene) to plot from the specified assay. + assay: Name of the assay containing the feature. + platform: The spatial transcriptomics platform. + palette: Color palette for continuous expression values. + point_size: Size of the points. + plot_width: Width of the output plot in inches. + plot_height: Height of the output plot in inches. + """ + # Input validation + if not spe_path.is_file(): + raise FileNotFoundError(f"Input file not found: {spe_path}") + if not feature: + raise ValueError("A feature name must be provided.") + + # Prepare arguments for the R function + json_args = { + "feature": feature, + "assay": assay, + "platform": platform, + "palette": palette, + "point_size": point_size, + } + json_args = {k: v for k, v in json_args.items() if v is not None} + + output_path = Path(output_filename) + + return _run_ggspavis( + function_name="plotFeature", + spe_path=spe_path, + output_path=output_path, + plot_width=plot_width, + plot_height=plot_height, + json_args=json_args, + ) + + +@mcp.tool() +def ggspavis_plot_dim_red( + spe_path: Path, + output_filename: str, + reduction_type: str, + x_axis: Optional[str] = None, + y_axis: Optional[str] = None, + color_by: Optional[str] = None, + shape_by: Optional[str] = None, + assay: str = "logcounts", + point_size: float = 1.5, + plot_width: float = 7.0, + plot_height: float = 7.0, +): + """ + Plots dimensionality reduction results (e.g., UMAP, PCA) using ggspavis::plotDimRed. + + Args: + spe_path: Path to the input SpatialExperiment object (.rds file). + output_filename: Name of the output plot file (e.g., 'umap.png'). + reduction_type: Name of the dimensionality reduction result in reducedDims(spe). + x_axis: Column name for the x-axis (e.g., 'UMAP_1'). Defaults to type_1. + y_axis: Column name for the y-axis (e.g., 'UMAP_2'). Defaults to type_2. + color_by: Column name in colData or feature name to use for point color. + shape_by: Column name in colData to use for point shape. + assay: Name of assay to use if 'color_by' is a feature name. + point_size: Size of the points. + plot_width: Width of the output plot in inches. + plot_height: Height of the output plot in inches. + """ + # Input validation + if not spe_path.is_file(): + raise FileNotFoundError(f"Input file not found: {spe_path}") + if not reduction_type: + raise ValueError("A reduction_type must be provided.") + + # Prepare arguments for the R function + json_args = { + "type": reduction_type, + "x_axis": x_axis, + "y_axis": y_axis, + "color_by": color_by, + "shape_by": shape_by, + "assay": assay, + "point_size": point_size, + } + json_args = {k: v for k, v in json_args.items() if v is not None} + + output_path = Path(output_filename) + + return _run_ggspavis( + function_name="plotDimRed", + spe_path=spe_path, + output_path=output_path, + plot_width=plot_width, + plot_height=plot_height, + json_args=json_args, + ) + + +@mcp.tool() +def ggspavis_plot_label( + spe_path: Path, + output_filename: str, + label: str, + platform: Literal["Visium", "ST", "VisiumHD", "mIF", "seqFISH", "MERFISH", "Xenium"] = "Visium", + palette: Optional[str] = None, + point_size: float = 1.5, + plot_width: float = 7.0, + plot_height: float = 7.0, +): + """ + Visualizes spatial clusters or other categorical labels using ggspavis::plotLabel. + + Args: + spe_path: Path to the input SpatialExperiment object (.rds file). + output_filename: Name of the output plot file (e.g., 'clusters.png'). + label: Column name in colData containing the labels to plot. + platform: The spatial transcriptomics platform. + palette: Optional color palette for labels. If None, ggplot2 default is used. + point_size: Size of the points. + plot_width: Width of the output plot in inches. + plot_height: Height of the output plot in inches. + """ + # Input validation + if not spe_path.is_file(): + raise FileNotFoundError(f"Input file not found: {spe_path}") + if not label: + raise ValueError("A label column name must be provided.") + + # Prepare arguments for the R function + json_args = { + "label": label, + "platform": platform, + "palette": palette, + "point_size": point_size, + } + json_args = {k: v for k, v in json_args.items() if v is not None} + + output_path = Path(output_filename) + + return _run_ggspavis( + function_name="plotLabel", + spe_path=spe_path, + output_path=output_path, + plot_width=plot_width, + plot_height=plot_height, + json_args=json_args, + ) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggspavis/app/bioconductor-ggspavis_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggspavis/app/bioconductor-ggspavis_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a55e4ae47a938e459767fc9d013c33d84e0bb875 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggspavis/app/bioconductor-ggspavis_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_manual_txt/mcp_bioconductor-ggspavis/app/bioconductor-ggspavis_server.py') +SERVER_NAME = 'biosci_bioconductor_ggspavis' + + +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_manual_txt/mcp_bioconductor-ggspavis/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggspavis/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggspavis/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggspavis/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggspavis/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..941920ed4e6d089e1a71dab40598b95cf6239402 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggspavis/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-ggspavis: + build: . + image: mcp-bioconductor-ggspavis:latest + container_name: mcp-bioconductor-ggspavis + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-ggspavis + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggspavis/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggspavis/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..282746043f724ae679e2f7e8ad158a7cb4b97be5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggspavis/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-ggspavis + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggspavis/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggspavis/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggspavis/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggtree/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggtree/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0399891b152181e15ed14a44c4e515af571b78aa --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggtree/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-ggtree via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-ggtree -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-ggtree_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-ggtree_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-ggtree_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggtree/app/bioconductor-ggtree_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggtree/app/bioconductor-ggtree_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e496dd1f781f97a218e20bb61d0efba774330741 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggtree/app/bioconductor-ggtree_server.py @@ -0,0 +1,208 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Dict, Any +import os + +@mcp.tool() +def run_ggtree_script( + r_script_content: str, + input_tree_file: Optional[Path] = None, + input_annotation_file: Optional[Path] = None, + output_image_format: str = "png", + image_width: int = 800, + image_height: int = 600, + output_filename_prefix: str = "ggtree_plot", +) -> Dict[str, Any]: + """ + Executes a custom R script using the bioconductor-ggtree package for phylogenetic tree visualization. + + This tool provides a flexible way to leverage ggtree's capabilities by allowing + users to provide arbitrary R code. It also facilitates common tasks like + loading tree and annotation files and saving plots. + + Note: The 'bioconductor-ggtree' package is an R library and does not expose + direct command-line functions or subcommands. This MCP tool provides a + generic R script execution environment where 'ggtree' and its dependencies + are available. Users are expected to provide R code that utilizes 'ggtree' + functions. + + Args: + r_script_content: A string containing the R code to execute. This script + should assume 'ggtree', 'treeio', 'ggplot2', and 'dplyr' + are loaded. It can access input files via variables + `input_tree_file` and `input_annotation_file` (which + will contain the POSIX paths as strings). The script + should write any desired output files to the current + working directory. + input_tree_file: Optional path to a phylogenetic tree file (e.g., Newick, Nexus). + If provided, its POSIX path will be available as the + `input_tree_file` variable in the R script. + input_annotation_file: Optional path to an annotation data file (e.g., CSV, TSV). + If provided, its POSIX path will be available as the + `input_annotation_file` variable in the R script. + output_image_format: The desired format for the output image. Supported: "png", "pdf", "svg", "jpeg", "tiff", "bmp". + This format will be used for the default `ggsave` call + if a ggplot object `p` is found and not explicitly saved + by `r_script_content`. + image_width: Width of the output image. For raster formats (png, jpeg, etc.), + this is in pixels. For vector formats (pdf, svg), this is + converted to inches (assuming 96 DPI for conversion from pixels). + image_height: Height of the output image. Similar to `image_width`. + output_filename_prefix: A prefix for the output image file. The full filename + will be '{prefix}.{format}'. This is used for the + default `ggsave` call. + + Returns: + A dictionary containing: + - command_executed: The Rscript command that was run. + - stdout: Standard output from the R script. + - stderr: Standard error from the R script. + - output_files: A list of paths to any generated output files. + - error: An error message if the R script execution failed. + """ + # Input validation + if not r_script_content.strip(): + raise ValueError("r_script_content cannot be empty.") + + if input_tree_file: + if not input_tree_file.is_file(): + raise FileNotFoundError(f"Input tree file not found: {input_tree_file}") + input_tree_file_posix = input_tree_file.as_posix() + else: + input_tree_file_posix = "" + + if input_annotation_file: + if not input_annotation_file.is_file(): + raise FileNotFoundError(f"Input annotation file not found: {input_annotation_file}") + input_annotation_file_posix = input_annotation_file.as_posix() + else: + input_annotation_file_posix = "" + + supported_formats = {"png", "pdf", "svg", "jpeg", "tiff", "bmp"} + if output_image_format.lower() not in supported_formats: + raise ValueError(f"Unsupported output image format: {output_image_format}. " + f"Supported formats are: {', '.join(supported_formats)}") + + if image_width <= 0: + raise ValueError("Image width must be a positive integer.") + if image_height <= 0: + raise ValueError("Image height must be a positive integer.") + if not output_filename_prefix: + raise ValueError("Output filename prefix cannot be empty.") + + with tempfile.TemporaryDirectory() as tmpdir: + work_dir = Path(tmpdir) + + # Define output image path for default ggsave + output_image_name = f"{output_filename_prefix}.{output_image_format.lower()}" + + # Construct the R script + r_code = f""" + # Load necessary libraries + suppressPackageStartupMessages(library(ggtree)) + suppressPackageStartupMessages(library(treeio)) + suppressPackageStartupMessages(library(ggplot2)) + suppressPackageStartupMessages(library(dplyr)) # Often useful for data manipulation + + # Set working directory for outputs + setwd("{work_dir.as_posix()}") + + # Make input file paths available as R variables + input_tree_file <- if ("{input_tree_file_posix}" != "") {{ + "{input_tree_file_posix}" + }} else {{ + NULL + }} + input_annotation_file <- if ("{input_annotation_file_posix}" != "") {{ + "{input_annotation_file_posix}" + }} else {{ + NULL + }} + + # Parameters for default ggsave + output_image_name_param <- "{output_image_name}" + image_width_param <- {image_width} + image_height_param <- {image_height} + output_image_format_param <- "{output_image_format.lower()}" + + # Determine units and DPI for ggsave based on format + units_val <- "in" # Default for vector graphics + dpi_val <- NULL # Default for vector graphics + + if (output_image_format_param %in% c("png", "jpeg", "tiff", "bmp")) {{ + units_val <- "px" + dpi_val <- 300 # Common DPI for raster images + }} else {{ # pdf, svg, etc. + # Convert pixels to inches for vector formats if input was in pixels + # Assuming 96 DPI for screen pixels to inches conversion if no specific DPI is given + image_width_param <- image_width_param / 96 + image_height_param <- image_height_param / 96 + }} + + # User-provided R script content + # This is where the user's custom ggtree logic should go. + # The user's script can use 'input_tree_file', 'input_annotation_file', + # 'output_image_name_param', 'image_width_param', 'image_height_param', + # 'units_val', 'dpi_val' if they wish to override or extend the default + # saving behavior. + {r_script_content} + + # Attempt to save the last ggplot object 'p' if it exists and + # the user's script hasn't explicitly saved a plot with the default name. + # This provides a fallback for simple plotting tasks. + if (exists("p") && inherits(p, "ggplot")) {{ + if (!file.exists(output_image_name_param)) {{ # Only save if user script didn't already save to this name + message(paste0("Saving ggplot object 'p' to ", output_image_name_param, " using default parameters.")) + ggsave(output_image_name_param, plot = p, width = image_width_param, height = image_height_param, units = units_val, dpi = dpi_val) + }} else {{ + message(paste0("File '", output_image_name_param, "' already exists. Skipping default ggsave.")) + }} + }} else {{ + message("No 'p' (ggplot object) found or saved by user script. No default image output will be generated.") + }} + """ + + r_script_file = work_dir / "run_ggtree.R" + r_script_file.write_text(r_code) + + command = ["Rscript", r_script_file.as_posix()] + + # Execute the R script + try: + process = subprocess.run( + command, + cwd=work_dir, + capture_output=True, + text=True, + check=True, + env=os.environ # Inherit environment to ensure R is found + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": f"Rscript execution failed with exit code {e.returncode}", + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Rscript command not found. Is R installed and in PATH?", + "output_files": [], + "error": "Rscript executable not found.", + } + + # Collect output files + output_files = [f.as_posix() for f in work_dir.iterdir() if f.is_file() and f != r_script_file] + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggtree/app/bioconductor-ggtree_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggtree/app/bioconductor-ggtree_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..81fed5ea43b28b9aac66c6564a52b63029d0fa6b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggtree/app/bioconductor-ggtree_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_manual_txt/mcp_bioconductor-ggtree/app/bioconductor-ggtree_server.py') +SERVER_NAME = 'biosci_bioconductor_ggtree' + + +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_manual_txt/mcp_bioconductor-ggtree/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggtree/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggtree/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggtree/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggtree/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b26bd3cd63d1531de3d839f1af8f1c8289770276 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggtree/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-ggtree: + build: . + image: mcp-bioconductor-ggtree:latest + container_name: mcp-bioconductor-ggtree + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-ggtree + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggtree/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggtree/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f86f271d340f923d10117919ff269c0123223824 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggtree/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-ggtree + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggtree/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggtree/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggtree/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-glmgampoi/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-glmgampoi/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1c5f58d07fa6b4051eee2ddb17e438690e1642f2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-glmgampoi/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-glmgampoi via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-glmgampoi -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-glmgampoi_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-glmgampoi_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-glmgampoi_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-glmgampoi/app/bioconductor-glmgampoi_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-glmgampoi/app/bioconductor-glmgampoi_server.py new file mode 100644 index 0000000000000000000000000000000000000000..38df15dffccb0bf6db55c00b115e4d203af4038a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-glmgampoi/app/bioconductor-glmgampoi_server.py @@ -0,0 +1,262 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Dict, Any + +@mcp.tool() +def fit_glm_gp( + data_path: str, + output_rds: str, + design_formula: str = "~1", + col_data_path: Optional[str] = None, + size_factors: str = "normed_sum", + overdispersion_shrinkage: bool = True, + on_disk: bool = False, +) -> Dict[str, Any]: + """ + Fit a Gamma-Poisson Generalized Linear Model (GLM) to count data. + Designed for large datasets like single-cell RNA-seq. + + Args: + data_path: Path to the input count matrix (CSV or TSV). Rows are genes, columns are samples. + output_rds: Path where the fitted model object (RDS format) will be saved. + design_formula: R-style formula string (e.g., '~ condition'). + col_data_path: Optional path to sample metadata (CSV or TSV). Rows must match columns in data_path. + size_factors: Method for normalization. Options: 'normed_sum', 'poscounts', 'median', or 'none'. + overdispersion_shrinkage: Whether to shrink overdispersion estimates towards a global trend. + on_disk: If True, uses HDF5-backed matrices to minimize memory usage for very large datasets. + """ + # Input validation + input_p = Path(data_path) + if not input_p.exists(): + raise FileNotFoundError(f"Input data file not found: {data_path}") + + output_p = Path(output_rds) + output_p.parent.mkdir(parents=True, exist_ok=True) + + col_data_arg = "NULL" + if col_data_path: + col_p = Path(col_data_path) + if not col_p.exists(): + raise FileNotFoundError(f"Metadata file not found: {col_data_path}") + col_data_arg = f"read_data('{col_data_path}')" + + # Map size_factors string to R logic + sf_val = f"'{size_factors}'" + if size_factors.lower() == "none": + sf_val = "FALSE" + + # Construct R script + r_script = f""" + library(glmGamPoi) + + read_data <- function(path) {{ + if (grepl('\\\\.tsv$', path, ignore.case = TRUE)) {{ + return(read.delim(path, row.names = 1, check.names = FALSE)) + }} else {{ + return(read.csv(path, row.names = 1, check.names = FALSE)) + }} + }} + + counts <- as.matrix(read_data('{data_path}')) + col_data <- {col_data_arg} + + fit <- glm_gp( + data = counts, + design = as.formula('{design_formula}'), + col_data = col_data, + size_factors = {sf_val}, + overdispersion_shrinkage = {str(overdispersion_shrinkage).upper()}, + on_disk = {str(on_disk).upper()} + ) + + saveRDS(fit, '{output_rds}') + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"glm_gp on {data_path}", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [output_rds] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd + } + +@mcp.tool() +def test_differential_expression( + fit_rds_path: str, + output_csv: str, + contrast: Optional[str] = None, + reduced_design: Optional[str] = None, +) -> Dict[str, Any]: + """ + Perform differential expression (DE) testing using a fitted glmGamPoi model. + + Args: + fit_rds_path: Path to the RDS file generated by fit_glm_gp. + output_csv: Path where the DE results (CSV) will be saved. + contrast: String specifying the contrast to test (e.g., 'condition_B - condition_A'). + reduced_design: Optional R-style formula for a reduced model to perform a Likelihood Ratio Test. + """ + fit_p = Path(fit_rds_path) + if not fit_p.exists(): + raise FileNotFoundError(f"Fitted model file not found: {fit_rds_path}") + + output_p = Path(output_csv) + output_p.parent.mkdir(parents=True, exist_ok=True) + + contrast_arg = "NULL" + if contrast: + # If it looks like a simple string, wrap in quotes; if it's complex, R handles it + contrast_arg = f"'{contrast}'" + + reduced_arg = "NULL" + if reduced_design: + reduced_arg = f"as.formula('{reduced_design}')" + + r_script = f""" + library(glmGamPoi) + fit <- readRDS('{fit_rds_path}') + res <- test_de( + fit, + contrast = {contrast_arg}, + reduced_design = {reduced_arg} + ) + write.csv(res, '{output_csv}', row.names = TRUE) + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"test_de on {fit_rds_path}", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [output_csv] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd + } + +@mcp.tool() +def get_overdispersion_estimates( + fit_rds_path: str, + output_csv: str +) -> Dict[str, Any]: + """ + Extract overdispersion estimates for each gene from a fitted glmGamPoi model. + + Args: + fit_rds_path: Path to the RDS file generated by fit_glm_gp. + output_csv: Path where the overdispersion estimates (CSV) will be saved. + """ + fit_p = Path(fit_rds_path) + if not fit_p.exists(): + raise FileNotFoundError(f"Fitted model file not found: {fit_rds_path}") + + r_script = f""" + library(glmGamPoi) + fit <- readRDS('{fit_rds_path}') + # Extract overdispersion and gene names + df <- data.frame( + gene = rownames(fit$Beta), + overdispersion = fit$overdispersions + ) + write.csv(df, '{output_csv}', row.names = FALSE) + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Extract overdispersion from {fit_rds_path}", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [output_csv] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd + } + +@mcp.tool() +def predict_glm_gp( + fit_rds_path: str, + output_csv: str, + newdata_path: Optional[str] = None, + type: str = "link" +) -> Dict[str, Any]: + """ + Predict values (e.g., log-counts or counts) from a fitted glmGamPoi model. + + Args: + fit_rds_path: Path to the RDS file generated by fit_glm_gp. + output_csv: Path where the predictions (CSV) will be saved. + newdata_path: Optional path to new sample metadata (CSV/TSV). If NULL, uses original data. + type: Type of prediction. 'link' (log-scale) or 'response' (original count scale). + """ + fit_p = Path(fit_rds_path) + if not fit_p.exists(): + raise FileNotFoundError(f"Fitted model file not found: {fit_rds_path}") + + newdata_arg = "NULL" + if newdata_path: + if not Path(newdata_path).exists(): + raise FileNotFoundError(f"New data file not found: {newdata_path}") + newdata_arg = f"read.csv('{newdata_path}', row.names = 1)" + + r_script = f""" + library(glmGamPoi) + fit <- readRDS('{fit_rds_path}') + newdata <- {newdata_arg} + preds <- predict(fit, newdata = newdata, type = '{type}') + write.csv(preds, '{output_csv}') + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"predict on {fit_rds_path}", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [output_csv] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-glmgampoi/app/bioconductor-glmgampoi_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-glmgampoi/app/bioconductor-glmgampoi_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..65060dac0f434afe5247160609adb965f9d4c611 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-glmgampoi/app/bioconductor-glmgampoi_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_manual_txt/mcp_bioconductor-glmgampoi/app/bioconductor-glmgampoi_server.py') +SERVER_NAME = 'biosci_bioconductor_glmgampoi' + + +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_manual_txt/mcp_bioconductor-glmgampoi/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-glmgampoi/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-glmgampoi/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-glmgampoi/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-glmgampoi/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7e864b31d24f33ded903f987db861839ba126d44 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-glmgampoi/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-glmgampoi: + build: . + image: mcp-bioconductor-glmgampoi:latest + container_name: mcp-bioconductor-glmgampoi + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-glmgampoi + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-glmgampoi/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-glmgampoi/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1515ec182b974acd906df6c00c468fa2ebab7a98 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-glmgampoi/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-glmgampoi + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-glmgampoi/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-glmgampoi/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-glmgampoi/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-go.db/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-go.db/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2069a4e8592c1da90c7837bb6d4c45e57bd872d8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-go.db/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-go.db via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-go.db -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-go.db_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-go.db_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-go.db_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-go.db/app/bioconductor-go.db_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-go.db/app/bioconductor-go.db_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5c170deb87ad31df741861c1639385656c58f5fa --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-go.db/app/bioconductor-go.db_server.py @@ -0,0 +1,327 @@ +import subprocess +import tempfile +import json +from pathlib import Path +from typing import List, Optional, Literal + +@mcp.tool() +def go_db_select( + keys: List[str], + columns: List[str] = ["GOID", "TERM", "ONTOLOGY", "DEFINITION"], + keytype: str = "GOID" +): + """ + General query tool for GO.db using the AnnotationDbi select interface. + + Args: + keys: A list of identifiers to look up (e.g., ["GO:0008150", "GO:0003674"]). + columns: The data columns to return. Available: "GOID", "TERM", "ONTOLOGY", "DEFINITION". + keytype: The type of keys provided. Usually "GOID". + """ + # Validate inputs + if not keys: + return {"error": "No keys provided for lookup."} + + # Format R vectors + keys_r = 'c("' + '","'.join(keys) + '")' + cols_r = 'c("' + '","'.join(columns) + '")' + + r_script = f""" + library(GO.db) + res <- select(GO.db, keys={keys_r}, columns={cols_r}, keytype="{keytype}") + write.csv(res, row.names=FALSE) + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"select(GO.db, keys={keys}, columns={columns}, keytype='{keytype}')", + "stdout": process.stdout, + "stderr": process.stderr, + "description": "Query results from GO.db" + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def go_db_get_hierarchy( + go_ids: List[str], + relation_type: Literal["PARENTS", "CHILDREN", "ANCESTOR", "OFFSPRING"] = "CHILDREN" +): + """ + Retrieve hierarchical relationships for Gene Ontology terms. + + Args: + go_ids: List of GO IDs (e.g., ["GO:0007049"]). + relation_type: The type of relationship to retrieve: + - PARENTS: Immediate parents in the GO DAG. + - CHILDREN: Immediate children in the GO DAG. + - ANCESTOR: All nodes above the term in the hierarchy. + - OFFSPRING: All nodes below the term in the hierarchy. + """ + if not go_ids: + return {"error": "No GO IDs provided."} + + # Map relation type to the internal GO.db object name + map_name = f"GO{relation_type}" + go_ids_r = 'c("' + '","'.join(go_ids) + '")' + + r_script = f""" + library(GO.db) + map_obj <- {map_name} + results <- mget({go_ids_r}, map_obj, ifnotfound=NA) + # Convert list to a flat data frame for output + df <- data.frame( + Query_ID = rep(names(results), sapply(results, length)), + Related_ID = unlist(results) + ) + write.csv(df, row.names=FALSE) + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"mget({go_ids}, {map_name})", + "stdout": process.stdout, + "stderr": process.stderr, + "relation": relation_type + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def go_db_get_term_details( + go_ids: List[str] +): + """ + Retrieve detailed information (Term, Ontology, Definition) for specific GO IDs. + + Args: + go_ids: List of GO IDs (e.g., ["GO:0008150"]). + """ + if not go_ids: + return {"error": "No GO IDs provided."} + + go_ids_r = 'c("' + '","'.join(go_ids) + '")' + + r_script = f""" + library(GO.db) + # GOTERM is a special mapping object in GO.db + results <- mget({go_ids_r}, GOTERM, ifnotfound=NA) + + output <- data.frame( + GOID = character(), + Term = character(), + Ontology = character(), + Definition = character(), + stringsAsFactors = FALSE + ) + + for (i in seq_along(results)) {{ + term_obj <- results[[i]] + if (!is.na(term_obj)) {{ + output <- rbind(output, data.frame( + GOID = GOID(term_obj), + Term = Term(term_obj), + Ontology = Ontology(term_obj), + Definition = Definition(term_obj) + )) + }} + }} + write.csv(output, row.names=FALSE) + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"mget({go_ids}, GOTERM)", + "stdout": process.stdout, + "stderr": process.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def go_db_get_synonyms( + go_ids: List[str] +): + """ + Retrieve synonyms for specific Gene Ontology terms. + + Args: + go_ids: List of GO IDs. + """ + if not go_ids: + return {"error": "No GO IDs provided."} + + go_ids_r = 'c("' + '","'.join(go_ids) + '")' + + r_script = f""" + library(GO.db) + results <- mget({go_ids_r}, GOSYNONYM, ifnotfound=NA) + df <- data.frame( + GOID = rep(names(results), sapply(results, length)), + Synonym = unlist(results) + ) + write.csv(df, row.names=FALSE) + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"mget({go_ids}, GOSYNONYM)", + "stdout": process.stdout, + "stderr": process.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def go_db_list_resources(): + """ + List all available columns and keytypes in the GO.db package. + """ + r_script = """ + library(GO.db) + cat("COLUMNS:\\n") + cat(columns(GO.db), sep=", ") + cat("\\n\\nKEYTYPES:\\n") + cat(keytypes(GO.db), sep=", ") + cat("\\n") + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "columns(GO.db); keytypes(GO.db)", + "stdout": process.stdout, + "stderr": process.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def go_db_get_obsolete(): + """ + Retrieve all obsolete Gene Ontology terms stored in the database. + """ + r_script = """ + library(GO.db) + obs_ids <- keys(GO.db, keytype="GOID") + # Filter for obsolete terms using the GOOBSOLETE map + obs_map <- as.list(GOOBSOLETE) + df <- data.frame( + GOID = names(obs_map), + Term = sapply(obs_map, Term), + Ontology = sapply(obs_map, Ontology), + Definition = sapply(obs_map, Definition) + ) + write.csv(df, row.names=FALSE) + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "as.list(GOOBSOLETE)", + "stdout": process.stdout, + "stderr": process.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def go_db_map_ontology_to_ids( + ontology: Literal["BP", "CC", "MF"] = "BP" +): + """ + Retrieve all GO IDs belonging to a specific ontology branch. + + Args: + ontology: The ontology branch to retrieve: + - BP: Biological Process + - CC: Cellular Component + - MF: Molecular Function + """ + # Map ontology to the internal GO.db map object + map_name = f"GO{ontology}MAP" + + r_script = f""" + library(GO.db) + # The MAP objects contain all IDs for that ontology + ids <- keys({map_name}) + cat(ids, sep="\\n") + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"keys(GO{ontology}MAP)", + "stdout": process.stdout, + "stderr": process.stderr, + "ontology": ontology + } + 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_manual_txt/mcp_bioconductor-go.db/app/bioconductor-go.db_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-go.db/app/bioconductor-go.db_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8d3ff4d78ea4bcf2cb0b8bc00efcb3109a99ed15 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-go.db/app/bioconductor-go.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_manual_txt/mcp_bioconductor-go.db/app/bioconductor-go.db_server.py') +SERVER_NAME = 'biosci_bioconductor_go_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_manual_txt/mcp_bioconductor-go.db/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-go.db/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-go.db/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-go.db/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-go.db/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..bcb222a73c2f27a64f265287d9ff4aa040928e68 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-go.db/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-go.db: + build: . + image: mcp-bioconductor-go.db:latest + container_name: mcp-bioconductor-go.db + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-go.db + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-go.db/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-go.db/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0607214ee0c410fe2635325e9264b0cba5fd89bb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-go.db/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-go.db + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-go.db/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-go.db/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-go.db/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-gosemsim/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-gosemsim/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..79759355a85d632d7922ea3c56930957dd4d59fa --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-gosemsim/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-gosemsim via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-gosemsim -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-gosemsim_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-gosemsim_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-gosemsim_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-gosemsim/app/bioconductor-gosemsim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-gosemsim/app/bioconductor-gosemsim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a83d96584324e0d1d15417d34fe9cd5131891f2f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-gosemsim/app/bioconductor-gosemsim_server.py @@ -0,0 +1,315 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Literal, Dict, Any + +# MCP decorator placeholder, as per the user's request to not import mcp +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +def _run_gosemsim_r_script(script_content: str, args: List[str]) -> Dict[str, Any]: + """ + A helper function to securely write and execute a temporary R script. + + This function handles the creation of a temporary R script file, executes it + with the provided arguments using `Rscript`, captures the output, and ensures + the temporary file is cleaned up afterward. It also includes robust error + + handling for cases where R is not installed or the script fails. + + Args: + script_content: A string containing the R code to be executed. + args: A list of string arguments to be passed to the R script. + + Returns: + A dictionary containing the execution details, including the command, + stdout, stderr, and return code. + """ + script_path = "" + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(script_content) + script_path = r_script_file.name + + command = ["Rscript", script_path] + args + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout.strip(), + "stderr": process.stderr.strip(), + "return_code": process.returncode, + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout.strip(), + "stderr": e.stderr.strip(), + "return_code": e.returncode, + "error": "R script execution failed. Check stderr for details from R." + } + finally: + if script_path and Path(script_path).exists(): + Path(script_path).unlink() + +@mcp.tool() +def gosemsim_gosim( + goid1: str, + goid2: str, + ont: Literal["BP", "MF", "CC"] = "MF", + measure: Literal["Wang", "Resnik", "Lin", "Rel", "Jiang"] = "Wang", + organism: Literal["human", "mouse", "rat", "yeast", "fly", "zebrafish"] = "human", +) -> Dict[str, Any]: + """ + Computes semantic similarity between two GO terms using GOSemSim::goSim. + + This tool requires R, the Bioconductor package GOSemSim, and the appropriate + organism annotation database (e.g., org.Hs.eg.db for human) to be installed. + + Args: + goid1: The first GO ID (e.g., "GO:0004022"). + goid2: The second GO ID (e.g., "GO:0004024"). + ont: The ontology to use. One of "BP", "MF", or "CC". + measure: The semantic similarity measure to use. + organism: The organism for which to compute the similarity. + + Returns: + A dictionary containing the execution result and the similarity score. + """ + if not goid1.startswith("GO:") or not goid2.startswith("GO:"): + raise ValueError("GO IDs must be in the format 'GO:#######'.") + + r_script_template = """ + args <- commandArgs(trailingOnly=TRUE) + if (length(args) != 5) stop("Internal error: Expected 5 arguments.", call.=FALSE) + goid1 <- args[1]; goid2 <- args[2]; ont <- args[3]; measure <- args[4]; organism <- args[5] + + suppressPackageStartupMessages(library(GOSemSim)) + org_db_map <- c("human"="org.Hs.eg.db", "mouse"="org.Mm.eg.db", "rat"="org.Rn.eg.db", "yeast"="org.Sc.sgd.db", "fly"="org.Dm.eg.db", "zebrafish"="org.Dr.eg.db") + org_db_pkg <- org_db_map[organism] + + if (!requireNamespace(org_db_pkg, quietly = TRUE)) stop(paste("Package", org_db_pkg, "is not installed."), call. = FALSE) + suppressPackageStartupMessages(library(org_db_pkg, character.only = TRUE)) + + sem_data <- godata(OrgDb = get(org_db_pkg), ont = ont, keytype = "ENTREZID") + result <- tryCatch(goSim(goid1, goid2, semData=sem_data, measure=measure), error = function(e) { message(e$message); NA }) + if (!is.na(result)) cat(result) else quit(status = 1) + """ + + script_args = [goid1, goid2, ont, measure, organism] + result = _run_gosemsim_r_script(r_script_template, script_args) + + if result.get("return_code") == 0 and result.get("stdout"): + try: + result["similarity_score"] = float(result["stdout"]) + except (ValueError, TypeError): + result["error"] = "Failed to parse similarity score from R script output." + + return result + +@mcp.tool() +def gosemsim_mgosim( + go_ids1: List[str], + go_ids2: List[str], + output_csv: Path, + ont: Literal["BP", "MF", "CC"] = "MF", + measure: Literal["Wang", "Resnik", "Lin", "Rel", "Jiang"] = "Wang", + combine: Literal["max", "avg", "rcmax", "BMA"] = "BMA", + organism: Literal["human", "mouse", "rat", "yeast", "fly", "zebrafish"] = "human", +) -> Dict[str, Any]: + """ + Computes semantic similarity between two sets of GO terms using GOSemSim::mgoSim. + + This tool requires R, GOSemSim, and the appropriate organism annotation database. + The resulting similarity matrix is saved to the specified output CSV file. + + Args: + go_ids1: A list of GO IDs for the first set. + go_ids2: A list of GO IDs for the second set. + output_csv: Path to save the resulting similarity matrix in CSV format. + ont: The ontology to use ("BP", "MF", or "CC"). + measure: The semantic similarity measure to use. + combine: The method to combine scores for GO term sets. + organism: The organism for which to compute the similarity. + + Returns: + A dictionary containing the execution result and the path to the output file. + """ + if not go_ids1 or not go_ids2: + raise ValueError("Input GO ID lists cannot be empty.") + for go_id in go_ids1 + go_ids2: + if not go_id.startswith("GO:"): + raise ValueError(f"Invalid GO ID format: {go_id}. Must be 'GO:#######'.") + + go_ids1_str = ",".join(go_ids1) + go_ids2_str = ",".join(go_ids2) + + r_script_template = """ + args <- commandArgs(trailingOnly=TRUE) + if (length(args) != 6) stop("Internal error: Expected 6 arguments.", call.=FALSE) + go_ids1 <- strsplit(args[1], ",")[[1]]; go_ids2 <- strsplit(args[2], ",")[[1]]; ont <- args[3]; measure <- args[4]; combine <- args[5]; organism <- args[6] + + suppressPackageStartupMessages(library(GOSemSim)) + org_db_map <- c("human"="org.Hs.eg.db", "mouse"="org.Mm.eg.db", "rat"="org.Rn.eg.db", "yeast"="org.Sc.sgd.db", "fly"="org.Dm.eg.db", "zebrafish"="org.Dr.eg.db") + org_db_pkg <- org_db_map[organism] + + if (!requireNamespace(org_db_pkg, quietly = TRUE)) stop(paste("Package", org_db_pkg, "is not installed."), call. = FALSE) + suppressPackageStartupMessages(library(org_db_pkg, character.only = TRUE)) + + sem_data <- godata(OrgDb = get(org_db_pkg), ont = ont, keytype = "ENTREZID") + result_matrix <- tryCatch(mgoSim(go_ids1, go_ids2, semData=sem_data, measure=measure, combine=combine), error = function(e) { message(e$message); NULL }) + if (!is.null(result_matrix)) write.csv(result_matrix, stdout(), row.names=TRUE, quote=FALSE) else quit(status = 1) + """ + + script_args = [go_ids1_str, go_ids2_str, ont, measure, combine, organism] + result = _run_gosemsim_r_script(r_script_template, script_args) + + output_files = [] + if result.get("return_code") == 0 and result.get("stdout"): + try: + output_csv.parent.mkdir(parents=True, exist_ok=True) + output_csv.write_text(result["stdout"]) + output_files.append(str(output_csv)) + except IOError as e: + result["error"] = f"Failed to write output file: {e}" + + result["output_files"] = output_files + return result + +@mcp.tool() +def gosemsim_genesim( + gene1: str, + gene2: str, + ont: Literal["BP", "MF", "CC"] = "MF", + measure: Literal["Wang", "Resnik", "Lin", "Rel", "Jiang"] = "Wang", + organism: Literal["human", "mouse", "rat", "yeast", "fly", "zebrafish"] = "human", + combine: Literal["max", "avg", "rcmax", "BMA"] = "BMA", +) -> Dict[str, Any]: + """ + Computes semantic similarity between two genes using GOSemSim::geneSim. + + This tool requires R, GOSemSim, and the appropriate organism annotation database. + Gene IDs should be Entrez Gene IDs. + + Args: + gene1: The first Entrez Gene ID. + gene2: The second Entrez Gene ID. + ont: The ontology to use ("BP", "MF", or "CC"). + measure: The semantic similarity measure to use. + organism: The organism for which to compute the similarity. + combine: The method to combine scores for the gene's GO term sets. + + Returns: + A dictionary containing the execution result and the similarity score. + """ + if not gene1.isdigit() or not gene2.isdigit(): + raise ValueError("Gene IDs must be numeric Entrez IDs.") + + r_script_template = """ + args <- commandArgs(trailingOnly=TRUE) + if (length(args) != 6) stop("Internal error: Expected 6 arguments.", call.=FALSE) + gene1 <- args[1]; gene2 <- args[2]; ont <- args[3]; measure <- args[4]; organism <- args[5]; combine <- args[6] + + suppressPackageStartupMessages(library(GOSemSim)) + org_db_map <- c("human"="org.Hs.eg.db", "mouse"="org.Mm.eg.db", "rat"="org.Rn.eg.db", "yeast"="org.Sc.sgd.db", "fly"="org.Dm.eg.db", "zebrafish"="org.Dr.eg.db") + org_db_pkg <- org_db_map[organism] + + if (!requireNamespace(org_db_pkg, quietly = TRUE)) stop(paste("Package", org_db_pkg, "is not installed."), call. = FALSE) + suppressPackageStartupMessages(library(org_db_pkg, character.only = TRUE)) + + sem_data <- godata(OrgDb = get(org_db_pkg), ont = ont, keytype = "ENTREZID") + result <- tryCatch(geneSim(gene1, gene2, semData=sem_data, measure=measure, combine=combine), error = function(e) { message(e$message); NA }) + if (!is.na(result$geneSim)) cat(result$geneSim) else quit(status = 1) + """ + + script_args = [gene1, gene2, ont, measure, organism, combine] + result = _run_gosemsim_r_script(r_script_template, script_args) + + if result.get("return_code") == 0 and result.get("stdout"): + try: + result["similarity_score"] = float(result["stdout"]) + except (ValueError, TypeError): + result["error"] = "Failed to parse similarity score from R script output." + + return result + +@mcp.tool() +def gosemsim_mgenesim( + genes1: List[str], + genes2: List[str], + output_csv: Path, + ont: Literal["BP", "MF", "CC"] = "MF", + measure: Literal["Wang", "Resnik", "Lin", "Rel", "Jiang"] = "Wang", + organism: Literal["human", "mouse", "rat", "yeast", "fly", "zebrafish"] = "human", + combine: Literal["max", "avg", "rcmax", "BMA"] = "BMA", +) -> Dict[str, Any]: + """ + Computes semantic similarity between two gene clusters using GOSemSim::mgeneSim. + + This tool requires R, GOSemSim, and the appropriate organism annotation database. + Gene IDs should be Entrez Gene IDs. The resulting similarity matrix is saved + to the specified output CSV file. + + Args: + genes1: A list of Entrez Gene IDs for the first cluster. + genes2: A list of Entrez Gene IDs for the second cluster. + output_csv: Path to save the resulting similarity matrix in CSV format. + ont: The ontology to use ("BP", "MF", or "CC"). + measure: The semantic similarity measure to use. + organism: The organism for which to compute the similarity. + combine: The method to combine scores for GO term sets. + + Returns: + A dictionary containing the execution result and the path to the output file. + """ + if not genes1 or not genes2: + raise ValueError("Input gene lists cannot be empty.") + for gene_id in genes1 + genes2: + if not gene_id.isdigit(): + raise ValueError(f"Invalid Gene ID format: {gene_id}. Must be a numeric Entrez ID.") + + genes1_str = ",".join(genes1) + genes2_str = ",".join(genes2) + + r_script_template = """ + args <- commandArgs(trailingOnly=TRUE) + if (length(args) != 6) stop("Internal error: Expected 6 arguments.", call.=FALSE) + genes1 <- strsplit(args[1], ",")[[1]]; genes2 <- strsplit(args[2], ",")[[1]]; ont <- args[3]; measure <- args[4]; organism <- args[5]; combine <- args[6] + + suppressPackageStartupMessages(library(GOSemSim)) + org_db_map <- c("human"="org.Hs.eg.db", "mouse"="org.Mm.eg.db", "rat"="org.Rn.eg.db", "yeast"="org.Sc.sgd.db", "fly"="org.Dm.eg.db", "zebrafish"="org.Dr.eg.db") + org_db_pkg <- org_db_map[organism] + + if (!requireNamespace(org_db_pkg, quietly = TRUE)) stop(paste("Package", org_db_pkg, "is not installed."), call. = FALSE) + suppressPackageStartupMessages(library(org_db_pkg, character.only = TRUE)) + + sem_data <- godata(OrgDb = get(org_db_pkg), ont = ont, keytype = "ENTREZID") + result_matrix <- tryCatch(mgeneSim(genes1, genes2, semData=sem_data, measure=measure, combine=combine), error = function(e) { message(e$message); NULL }) + if (!is.null(result_matrix)) write.csv(result_matrix, stdout(), row.names=TRUE, quote=FALSE) else quit(status = 1) + """ + + script_args = [genes1_str, genes2_str, ont, measure, organism, combine] + result = _run_gosemsim_r_script(r_script_template, script_args) + + output_files = [] + if result.get("return_code") == 0 and result.get("stdout"): + try: + output_csv.parent.mkdir(parents=True, exist_ok=True) + output_csv.write_text(result["stdout"]) + output_files.append(str(output_csv)) + except IOError as e: + result["error"] = f"Failed to write output file: {e}" + + result["output_files"] = output_files + return result \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-gosemsim/app/bioconductor-gosemsim_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-gosemsim/app/bioconductor-gosemsim_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1093791134811e3222ae97c9961fe4e090c9616b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-gosemsim/app/bioconductor-gosemsim_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_manual_txt/mcp_bioconductor-gosemsim/app/bioconductor-gosemsim_server.py') +SERVER_NAME = 'biosci_bioconductor_gosemsim' + + +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_manual_txt/mcp_bioconductor-gosemsim/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-gosemsim/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-gosemsim/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-gosemsim/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-gosemsim/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e0264312aed56c58603128d118ddb6f05d42616d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-gosemsim/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-gosemsim: + build: . + image: mcp-bioconductor-gosemsim:latest + container_name: mcp-bioconductor-gosemsim + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-gosemsim + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-gosemsim/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-gosemsim/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8f13aa43e05a5c4edac218b82b7b0981931e9030 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-gosemsim/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-gosemsim + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-gosemsim/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-gosemsim/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-gosemsim/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-graph/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-graph/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d094aacd7f9cef99a6c0332a22fdfeb4a493e2f8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-graph/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-graph via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-graph -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-graph_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-graph_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-graph_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-graph/app/bioconductor-graph_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-graph/app/bioconductor-graph_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ffcc177dc10e28785eb6a77a34a334468ba030d6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-graph/app/bioconductor-graph_server.py @@ -0,0 +1,374 @@ +import subprocess +import tempfile +import json +from pathlib import Path +from typing import List, Optional, Union + +@mcp.tool() +def graph_nel_create( + nodes: List[str], + edge_from: List[str], + edge_to: List[str], + output_rds: str, + edgemode: str = "undirected", + weights: Optional[List[float]] = None +): + """ + Create a graphNEL object (Node Edge List) and save it as an RDS file. + + :param nodes: List of node names. + :param edge_from: List of source nodes for edges. + :param edge_to: List of target nodes for edges. + :param output_rds: Path to save the resulting R graph object (.rds). + :param edgemode: Either 'directed' or 'undirected'. + :param weights: Optional list of numeric weights for each edge. + """ + if len(edge_from) != len(edge_to): + return {"error": "edge_from and edge_to must have the same length"} + if weights and len(weights) != len(edge_from): + return {"error": "weights must have the same length as edges"} + if edgemode not in ["directed", "undirected"]: + return {"error": "edgemode must be 'directed' or 'undirected'"} + + output_path = Path(output_rds).resolve() + + # Prepare R script + r_nodes = ", ".join([f"'{n}'" for n in nodes]) + r_from = ", ".join([f"'{n}'" for n in edge_from]) + r_to = ", ".join([f"'{n}'" for n in edge_to]) + r_weights = ", ".join([str(w) for w in weights]) if weights else "NULL" + + r_script = f""" + library(graph) + nodes <- c({r_nodes}) + edge_from <- c({r_from}) + edge_to <- c({r_to}) + weights <- {r_weights} + + g <- new("graphNEL", nodes=nodes, edgemode='{edgemode}') + if (!is.null(weights)) {{ + g <- addEdge(edge_from, edge_to, g, weights) + }} else {{ + g <- addEdge(edge_from, edge_to, g) + }} + saveRDS(g, '{output_path}') + """ + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as f: + f.write(r_script) + tmp_script = f.name + + result = subprocess.run(["Rscript", tmp_script], capture_output=True, text=True, check=True) + return { + "command_executed": f"Rscript {tmp_script}", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stdout": e.stdout, "stderr": e.stderr} + finally: + if Path(tmp_script).exists(): + Path(tmp_script).unlink() + +@mcp.tool() +def graph_am_create( + adj_matrix_csv: str, + output_rds: str, + edgemode: str = "undirected" +): + """ + Create a graphAM object (Adjacency Matrix) from a CSV file and save as RDS. + + :param adj_matrix_csv: Path to a CSV file containing the adjacency matrix (with headers/row names). + :param output_rds: Path to save the resulting R graph object (.rds). + :param edgemode: Either 'directed' or 'undirected'. + """ + input_path = Path(adj_matrix_csv).resolve() + output_path = Path(output_rds).resolve() + + if not input_path.exists(): + return {"error": f"Input file {adj_matrix_csv} not found"} + + r_script = f""" + library(graph) + mat <- as.matrix(read.csv('{input_path}', row.names=1)) + g <- new("graphAM", adjMat=mat, edgemode='{edgemode}') + saveRDS(g, '{output_path}') + """ + + try: + result = subprocess.run(["Rscript", "-e", r_script], capture_output=True, text=True, check=True) + return { + "command_executed": "Rscript -e ...", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stdout": e.stdout, "stderr": e.stderr} + +@mcp.tool() +def graph_get_details( + input_rds: str +): + """ + Retrieve basic information about a graph object (nodes, edges, degree, edgemode). + + :param input_rds: Path to the R graph object (.rds). + """ + input_path = Path(input_rds).resolve() + if not input_path.exists(): + return {"error": f"Input file {input_rds} not found"} + + r_script = f""" + library(graph) + g <- readRDS('{input_path}') + cat("--- Summary ---\\n") + print(g) + cat("\\n--- Nodes ---\\n") + print(nodes(g)) + cat("\\n--- Edges ---\\n") + print(edges(g)) + cat("\\n--- Degree ---\\n") + print(degree(g)) + cat("\\n--- Edge Mode ---\\n") + cat(edgemode(g)) + """ + + try: + result = subprocess.run(["Rscript", "-e", r_script], capture_output=True, text=True, check=True) + return { + "command_executed": "Rscript -e ...", + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stdout": e.stdout, "stderr": e.stderr} + +@mcp.tool() +def graph_modify_elements( + input_rds: str, + output_rds: str, + add_nodes: Optional[List[str]] = None, + remove_nodes: Optional[List[str]] = None, + add_edges_from: Optional[List[str]] = None, + add_edges_to: Optional[List[str]] = None, + remove_edges_from: Optional[List[str]] = None, + remove_edges_to: Optional[List[str]] = None +): + """ + Add or remove nodes and edges from an existing graph object. + + :param input_rds: Path to the existing R graph object (.rds). + :param output_rds: Path to save the modified graph object. + :param add_nodes: List of node names to add. + :param remove_nodes: List of node names to remove. + :param add_edges_from: List of source nodes for new edges. + :param add_edges_to: List of target nodes for new edges. + :param remove_edges_from: List of source nodes for edges to remove. + :param remove_edges_to: List of target nodes for edges to remove. + """ + input_path = Path(input_rds).resolve() + output_path = Path(output_rds).resolve() + + if not input_path.exists(): + return {"error": f"Input file {input_rds} not found"} + + def to_r_vec(plist): + return "c(" + ", ".join([f"'{x}'" for x in plist]) + ")" if plist else "NULL" + + r_add_nodes = to_r_vec(add_nodes) + r_rem_nodes = to_r_vec(remove_nodes) + r_add_from = to_r_vec(add_edges_from) + r_add_to = to_r_vec(add_edges_to) + r_rem_from = to_r_vec(remove_edges_from) + r_rem_to = to_r_vec(remove_edges_to) + + r_script = f""" + library(graph) + g <- readRDS('{input_path}') + + # Add Nodes + an <- {r_add_nodes} + if (!is.null(an)) g <- addNode(an, g) + + # Add Edges + af <- {r_add_from}; at <- {r_add_to} + if (!is.null(af) && !is.null(at)) g <- addEdge(af, at, g) + + # Remove Edges + rf <- {r_rem_from}; rt <- {r_rem_to} + if (!is.null(rf) && !is.null(rt)) g <- removeEdge(rf, rt, g) + + # Remove Nodes + rn <- {r_rem_nodes} + if (!is.null(rn)) g <- removeNode(rn, g) + + saveRDS(g, '{output_path}') + """ + + try: + result = subprocess.run(["Rscript", "-e", r_script], capture_output=True, text=True, check=True) + return { + "command_executed": "Rscript -e ...", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stdout": e.stdout, "stderr": e.stderr} + +@mcp.tool() +def graph_export_matrix( + input_rds: str, + output_csv: str +): + """ + Export a graph object's adjacency matrix to a CSV file. + + :param input_rds: Path to the R graph object (.rds). + :param output_csv: Path to save the adjacency matrix as CSV. + """ + input_path = Path(input_rds).resolve() + output_path = Path(output_csv).resolve() + + if not input_path.exists(): + return {"error": f"Input file {input_rds} not found"} + + r_script = f""" + library(graph) + g <- readRDS('{input_path}') + mat <- as(g, "matrix") + write.csv(mat, '{output_path}') + """ + + try: + result = subprocess.run(["Rscript", "-e", r_script], capture_output=True, text=True, check=True) + return { + "command_executed": "Rscript -e ...", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stdout": e.stdout, "stderr": e.stderr} + +@mcp.tool() +def graph_set_operations( + input_rds_1: str, + input_rds_2: str, + output_rds: str, + operation: str = "intersection" +): + """ + Perform set operations (intersection, union, complement) on two graphs. + + :param input_rds_1: Path to the first R graph object (.rds). + :param input_rds_2: Path to the second R graph object (.rds). + :param output_rds: Path to save the resulting graph object. + :param operation: One of 'intersection', 'union', or 'complement'. + """ + path1 = Path(input_rds_1).resolve() + path2 = Path(input_rds_2).resolve() + out_path = Path(output_rds).resolve() + + if not path1.exists() or not path2.exists(): + return {"error": "One or both input files not found"} + + if operation not in ["intersection", "union", "complement"]: + return {"error": "Operation must be 'intersection', 'union', or 'complement'"} + + r_func = { + "intersection": "intersection", + "union": "join", + "complement": "complement" + }[operation] + + r_script = f""" + library(graph) + g1 <- readRDS('{path1}') + g2 <- readRDS('{path2}') + res <- {r_func}(g1, g2) + saveRDS(res, '{out_path}') + """ + + try: + result = subprocess.run(["Rscript", "-e", r_script], capture_output=True, text=True, check=True) + return { + "command_executed": "Rscript -e ...", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_path)] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stdout": e.stdout, "stderr": e.stderr} + +@mcp.tool() +def graph_subgraph( + input_rds: str, + nodes: List[str], + output_rds: str +): + """ + Create a subgraph containing only the specified nodes. + + :param input_rds: Path to the R graph object (.rds). + :param nodes: List of node names to include in the subgraph. + :param output_rds: Path to save the resulting subgraph object. + """ + input_path = Path(input_rds).resolve() + output_path = Path(output_rds).resolve() + + if not input_path.exists(): + return {"error": f"Input file {input_rds} not found"} + + r_nodes = ", ".join([f"'{n}'" for n in nodes]) + r_script = f""" + library(graph) + g <- readRDS('{input_path}') + sub_g <- subGraph(c({r_nodes}), g) + saveRDS(sub_g, '{output_path}') + """ + + try: + result = subprocess.run(["Rscript", "-e", r_script], capture_output=True, text=True, check=True) + return { + "command_executed": "Rscript -e ...", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stdout": e.stdout, "stderr": e.stderr} + +@mcp.tool() +def graph_clustering_info( + input_rds: str +): + """ + Calculate clustering information for the graph (connected components). + + :param input_rds: Path to the R graph object (.rds). + """ + input_path = Path(input_rds).resolve() + if not input_path.exists(): + return {"error": f"Input file {input_rds} not found"} + + r_script = f""" + library(graph) + g <- readRDS('{input_path}') + cat("--- Connected Components ---\\n") + print(connComp(g)) + """ + + try: + result = subprocess.run(["Rscript", "-e", r_script], capture_output=True, text=True, check=True) + return { + "command_executed": "Rscript -e ...", + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stdout": e.stdout, "stderr": e.stderr} \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-graph/app/bioconductor-graph_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-graph/app/bioconductor-graph_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1a5d1eb95b9c50bb2e6185628b353c70c1931bca --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-graph/app/bioconductor-graph_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_manual_txt/mcp_bioconductor-graph/app/bioconductor-graph_server.py') +SERVER_NAME = 'biosci_bioconductor_graph' + + +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_manual_txt/mcp_bioconductor-graph/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-graph/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-graph/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-graph/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-graph/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e381d6f96261f88e640b44f179e11c5daaf6a92d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-graph/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-graph: + build: . + image: mcp-bioconductor-graph:latest + container_name: mcp-bioconductor-graph + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-graph + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-graph/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-graph/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bf5c6395ba1581a2cb6bfed8ca295707e071d324 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-graph/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-graph + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-graph/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-graph/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-graph/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hcatonsildata/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hcatonsildata/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a2e06873042488f4adf3a3d6e09eb83fc0f670cc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hcatonsildata/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-hcatonsildata via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-hcatonsildata -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-hcatonsildata_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-hcatonsildata_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-hcatonsildata_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hcatonsildata/app/bioconductor-hcatonsildata_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hcatonsildata/app/bioconductor-hcatonsildata_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ce33bf01581e3e6c0e78a678a98fb41e2d2097da --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hcatonsildata/app/bioconductor-hcatonsildata_server.py @@ -0,0 +1,155 @@ +import subprocess +import tempfile +import shutil +from pathlib import Path +from typing import Optional, List, Dict, Any + +# Mock decorator for standalone execution +class mcp: + def tool(func): + return func + +@mcp.tool +def hcatonsildata_load( + output_file: Path, + version: str = "3.1.3", + ensembl: bool = False, + location: bool = True, + output_format: str = "h5ad", +) -> Dict[str, Any]: + """ + Loads the HCATonsilData object from Bioconductor and saves it to a specified file format. + + This tool acts as a wrapper around the R/Bioconductor HCATonsilData package, + which provides access to a SingleCellExperiment object of human tonsil data from the + Human Cell Atlas project. Since the package itself is not a command-line tool, this + function generates and executes an R script to load the data and export it. + + Args: + output_file: The path to the output file where the data object will be saved. + version: The version of the dataset to load. Must be either "3.1.3" or "2.0.0". + ensembl: A boolean indicating whether to use Ensembl identifiers for gene annotation. + If False, gene symbols are used. + location: A boolean indicating whether to download the data to a default + ExperimentHub cache location. + output_format: The format for the output file. Must be either "h5ad" (for AnnData) + or "rds" (for an R Data Serialization file). + + Returns: + A dictionary containing the execution details, including the command, + stdout, stderr, and the path to the output file. + """ + # 1. Input Validation + allowed_versions = ["3.1.3", "2.0.0"] + if version not in allowed_versions: + raise ValueError(f"Invalid version '{version}'. Must be one of {allowed_versions}.") + + allowed_formats = ["h5ad", "rds"] + if output_format not in allowed_formats: + raise ValueError(f"Invalid output_format '{output_format}'. Must be one of {allowed_formats}.") + + if not shutil.which("Rscript"): + raise FileNotFoundError("Rscript executable not found in PATH. R is required to run this tool.") + + # 2. File Path Handling + output_file = Path(output_file).resolve() + output_file.parent.mkdir(parents=True, exist_ok=True) + + # Convert Python bools to R's TRUE/FALSE strings + ensembl_r = str(ensembl).upper() + location_r = str(location).upper() + + # 3. R Script Generation + r_script_content = f""" + # Ensure all required packages are available + if (!requireNamespace("BiocManager", quietly = TRUE)) {{ + install.packages("BiocManager", repos = "http://cran.us.r-project.org") + }} + if (!requireNamespace("HCATonsilData", quietly = TRUE)) {{ + BiocManager::install("HCATonsilData", update=FALSE, ask=FALSE) + }} + + if ("{output_format}" == "h5ad") {{ + if (!requireNamespace("zellkonverter", quietly = TRUE)) {{ + BiocManager::install("zellkonverter", update=FALSE, ask=FALSE) + }} + library(zellkonverter) + }} + + library(HCATonsilData) + library(SingleCellExperiment) + + cat("Loading HCATonsilData version {version}...\\n") + + # Load the data object + sce <- HCATonsilData( + version = "{version}", + ensembl = {ensembl_r}, + location = {location_r} + ) + + cat("Saving data object to {str(output_file)} in {output_format} format...\\n") + + # Save the object in the specified format + if ("{output_format}" == "h5ad") {{ + writeH5AD(sce, file = "{str(output_file)}", overwrite = TRUE) + }} else if ("{output_format}" == "rds") {{ + saveRDS(sce, file = "{str(output_file)}") + }} + + cat("Process complete.\\n") + """ + + # 4. Subprocess Execution + command = [] + stdout_str = "" + stderr_str = "" + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_r_script: + tmp_r_script.write(r_script_content) + script_path = tmp_r_script.name + + command = ["Rscript", script_path] + + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + stdout_str = process.stdout + stderr_str = process.stderr + + except subprocess.CalledProcessError as e: + # 5. Error Handling + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + "error": "R script execution failed.", + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Rscript executable not found. Please ensure R is installed and in your system's PATH.", + "return_code": 1, + "error": "Dependency not found.", + "output_files": [] + } + finally: + # Clean up the temporary R script + if 'script_path' in locals() and Path(script_path).exists(): + Path(script_path).unlink() + + # 6. Structured Result Return + return { + "command_executed": " ".join(command), + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": [str(output_file)] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hcatonsildata/app/bioconductor-hcatonsildata_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hcatonsildata/app/bioconductor-hcatonsildata_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d1f74df5b3bef023f855ae8aa53356bcd7cfcfae --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hcatonsildata/app/bioconductor-hcatonsildata_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_manual_txt/mcp_bioconductor-hcatonsildata/app/bioconductor-hcatonsildata_server.py') +SERVER_NAME = 'biosci_bioconductor_hcatonsildata' + + +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_manual_txt/mcp_bioconductor-hcatonsildata/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hcatonsildata/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hcatonsildata/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hcatonsildata/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hcatonsildata/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..26b78c36f0c42e04db4de93abfa037953221a302 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hcatonsildata/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-hcatonsildata: + build: . + image: mcp-bioconductor-hcatonsildata:latest + container_name: mcp-bioconductor-hcatonsildata + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-hcatonsildata + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hcatonsildata/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hcatonsildata/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0fb5f539e7d8c659bb01c6cc21fdc219a3330885 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hcatonsildata/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-hcatonsildata + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hcatonsildata/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hcatonsildata/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hcatonsildata/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hdf5array/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hdf5array/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f2c0510d772e52fc655c301f1f3fd7380e937f81 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hdf5array/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-hdf5array via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-hdf5array -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-hdf5array_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-hdf5array_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-hdf5array_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hdf5array/app/bioconductor-hdf5array_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hdf5array/app/bioconductor-hdf5array_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a4048de346ad70d73d03a0fc0339fb993b097ab8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hdf5array/app/bioconductor-hdf5array_server.py @@ -0,0 +1,460 @@ +import subprocess +import tempfile +import textwrap +from pathlib import Path +from typing import Dict, List, Optional, Union + +# MCP decorator is not defined in this context, so we'll use a placeholder. +# In a real MCP environment, this would be: from mcp import tool +class mcp: + def tool(func): + return func + +@mcp.tool +def write_hdf5_array( + input_file: Path, + output_hdf5: Path, + dataset_name: str, + input_format: str = "csv", + chunk_dim: Optional[str] = None, + compression_level: int = 6, + as_integer: bool = False, + csv_header: bool = True, + csv_row_names_col: Optional[int] = 1, +) -> Dict[str, Union[str, Dict[str, str]]]: + """ + Converts a data file (CSV, TSV, or RDS) into an HDF5 file using HDF5Array. + + This tool is a wrapper around the HDF5Array::writeHDF5Array R function. + It requires R and the Bioconductor 'HDF5Array' package to be installed. + """ + # 1. Input validation + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if not output_hdf5.parent.exists(): + raise FileNotFoundError(f"Output directory does not exist: {output_hdf5.parent}") + if input_format not in ["csv", "tsv", "rds"]: + raise ValueError("input_format must be one of 'csv', 'tsv', or 'rds'.") + if not (0 <= compression_level <= 9): + raise ValueError("compression_level must be between 0 and 9.") + if chunk_dim: + try: + [int(d) for d in chunk_dim.split(',')] + except ValueError: + raise ValueError("chunk_dim must be a comma-separated string of integers (e.g., '100,1000').") + + # 2. R script for execution + r_script_content = textwrap.dedent(""" + suppressPackageStartupMessages({ + library(optparse) + library(HDF5Array) + }) + + option_list <- list( + make_option("--input", type="character", help="Input file path (CSV, TSV, or RDS)."), + make_option("--output", type="character", help="Output HDF5 file path."), + make_option("--name", type="character", help="Name for the dataset within the HDF5 file."), + make_option("--format", type="character", default="csv", help="Input file format [csv, tsv, rds]."), + make_option("--chunkdim", type="character", default=NULL, help="Comma-separated chunk dimensions."), + make_option("--level", type="integer", default=6, help="Compression level (0-9)."), + make_option("--as_integer", action="store_true", default=FALSE, help="Coerce data to integer."), + make_option("--header", action="store_true", default=TRUE, help="Does the CSV/TSV have a header?"), + make_option("--rownames", type="integer", default=NULL, help="Column number for row names in CSV/TSV.") + ) + + args <- parse_args(OptionParser(option_list=option_list)) + + # Read input data + message("Reading input file: ", args$input) + if (args$format == "rds") { + data_matrix <- readRDS(args$input) + } else if (args$format == "csv") { + data_matrix <- read.csv(args$input, header=args$header, row.names=args$rownames, check.names=FALSE) + } else if (args$format == "tsv") { + data_matrix <- read.delim(args$input, header=args$header, row.names=args$rownames, check.names=FALSE) + } else { + stop("Unsupported format: ", args$format) + } + + if (!is.matrix(data_matrix)) { + message("Input data is not a matrix, coercing...") + data_matrix <- as.matrix(data_matrix) + } + + if (args$as_integer) { + message("Coercing data to integer...") + storage.mode(data_matrix) <- "integer" + } + + # Parse chunk dimensions + chunk_dims <- NULL + if (!is.null(args$chunkdim)) { + chunk_dims <- as.integer(strsplit(args$chunkdim, ",")[[1]]) + message("Using chunk dimensions: ", paste(chunk_dims, collapse=", ")) + } + + # Write HDF5 array + message("Writing HDF5 array to: ", args$output) + writeHDF5Array( + x = data_matrix, + filepath = args$output, + name = args$name, + chunkdim = chunk_dims, + level = args$level, + with.dimnames = TRUE, + verbose = TRUE + ) + message("Successfully created HDF5 file.") + """) + + # 3. Subprocess execution + cmd = [ + "Rscript", "-", + "--input", str(input_file), + "--output", str(output_hdf5), + "--name", dataset_name, + "--format", input_format, + "--level", str(compression_level), + ] + if chunk_dim: + cmd.extend(["--chunkdim", chunk_dim]) + if as_integer: + cmd.append("--as_integer") + if csv_header: + cmd.append("--header") + if csv_row_names_col is not None: + cmd.extend(["--rownames", str(csv_row_names_col)]) + + try: + with tempfile.NamedTemporaryFile(mode='w', delete=True, suffix=".R") as r_script_file: + r_script_file.write(r_script_content) + r_script_file.flush() + + # Rebuild command to use the script file + cmd[1] = r_script_file.name + + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {"output_hdf5": str(output_hdf5)}, + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + error_message = ( + f"HDF5Array R script failed with exit code {e.returncode}.\n" + f"This may be due to missing R packages ('optparse', 'HDF5Array').\n" + f"Please install them in R using:\n" + f"install.packages('optparse')\n" + f"if (!requireNamespace('BiocManager', quietly = TRUE)) install.packages('BiocManager')\n" + f"BiocManager::install('HDF5Array')\n\n" + f"STDOUT:\n{e.stdout}\n" + f"STDERR:\n{e.stderr}" + ) + raise RuntimeError(error_message) from e + + +@mcp.tool +def save_hdf5_summarized_experiment( + input_rds: Path, + output_dir: Path, + prefix: Optional[str] = None, + replace: bool = False, +) -> Dict[str, Union[str, Dict[str, str]]]: + """ + Saves a SummarizedExperiment object from an RDS file to an HDF5-backed format. + + This tool wraps the HDF5Array::saveHDF5SummarizedExperiment R function. + It requires R and the Bioconductor packages 'HDF5Array' and 'SummarizedExperiment'. + """ + # 1. Input validation + if not input_rds.exists(): + raise FileNotFoundError(f"Input RDS file not found: {input_rds}") + if output_dir.exists() and not output_dir.is_dir(): + raise ValueError(f"Output path exists but is not a directory: {output_dir}") + if output_dir.exists() and any(output_dir.iterdir()) and not replace: + raise FileExistsError(f"Output directory {output_dir} is not empty. Use replace=True to overwrite.") + + output_dir.mkdir(parents=True, exist_ok=True) + + # 2. R script for execution + r_script_content = textwrap.dedent(""" + suppressPackageStartupMessages({ + library(optparse) + library(HDF5Array) + library(SummarizedExperiment) + }) + + option_list <- list( + make_option("--input", type="character", help="Input RDS file containing a SummarizedExperiment object."), + make_option("--outdir", type="character", help="Output directory to save the HDF5SummarizedExperiment."), + make_option("--prefix", type="character", default=NULL, help="Optional prefix for file names."), + make_option("--replace", action="store_true", default=FALSE, help="Replace existing directory content.") + ) + + args <- parse_args(OptionParser(option_list=option_list)) + + message("Reading SummarizedExperiment object from: ", args$input) + se <- readRDS(args$input) + + if (!is(se, "SummarizedExperiment")) { + stop("The object in the RDS file is not a SummarizedExperiment.") + } + + message("Saving HDF5SummarizedExperiment to: ", args$outdir) + saveHDF5SummarizedExperiment( + x = se, + dir = args$outdir, + prefix = args$prefix, + replace = args$replace, + verbose = TRUE + ) + message("Successfully saved HDF5SummarizedExperiment.") + """) + + # 3. Subprocess execution + cmd = [ + "Rscript", "-", + "--input", str(input_rds), + "--outdir", str(output_dir), + ] + if prefix: + cmd.extend(["--prefix", prefix]) + if replace: + cmd.append("--replace") + + try: + with tempfile.NamedTemporaryFile(mode='w', delete=True, suffix=".R") as r_script_file: + r_script_file.write(r_script_content) + r_script_file.flush() + + cmd[1] = r_script_file.name + + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {"output_directory": str(output_dir)}, + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + error_message = ( + f"HDF5Array R script failed with exit code {e.returncode}.\n" + f"This may be due to missing R packages ('optparse', 'HDF5Array', 'SummarizedExperiment').\n" + f"Please install them in R using BiocManager.\n\n" + f"STDOUT:\n{e.stdout}\n" + f"STDERR:\n{e.stderr}" + ) + raise RuntimeError(error_message) from e + + +@mcp.tool +def export_hdf5_summarized_experiment( + input_dir: Path, + output_dir: Path, + assay_names: Optional[str] = None, + export_coldata: bool = True, + export_rowdata: bool = True, +) -> Dict[str, Union[str, Dict[str, str]]]: + """ + Loads an HDF5SummarizedExperiment and exports its components to CSV files. + + This tool wraps HDF5Array::loadHDF5SummarizedExperiment and exports data. + Requires R and the Bioconductor packages 'HDF5Array' and 'SummarizedExperiment'. + """ + # 1. Input validation + if not input_dir.is_dir(): + raise FileNotFoundError(f"Input directory not found: {input_dir}") + if output_dir.exists() and not output_dir.is_dir(): + raise ValueError(f"Output path exists but is not a directory: {output_dir}") + + output_dir.mkdir(parents=True, exist_ok=True) + + # 2. R script for execution + r_script_content = textwrap.dedent(""" + suppressPackageStartupMessages({ + library(optparse) + library(HDF5Array) + library(SummarizedExperiment) + }) + + option_list <- list( + make_option("--indir", type="character", help="Input directory of the HDF5SummarizedExperiment."), + make_option("--outdir", type="character", help="Output directory for exported CSV files."), + make_option("--assays", type="character", default=NULL, help="Comma-separated list of assays to export (default: all)."), + make_option("--coldata", action="store_true", default=FALSE, help="Export colData to CSV."), + make_option("--rowdata", action="store_true", default=FALSE, help="Export rowData to CSV.") + ) + + args <- parse_args(OptionParser(option_list=option_list)) + + message("Loading HDF5SummarizedExperiment from: ", args$indir) + se <- loadHDF5SummarizedExperiment(dir = args$indir) + + assays_to_export <- assayNames(se) + if (!is.null(args$assays)) { + assays_to_export <- intersect(assays_to_export, strsplit(args$assays, ",")[[1]]) + } + + if (length(assays_to_export) > 0) { + for (aname in assays_to_export) { + message("Exporting assay: ", aname) + out_path <- file.path(args$outdir, paste0("assay_", aname, ".csv")) + mat <- as.matrix(assay(se, aname)) + write.csv(mat, file=out_path, quote=FALSE, row.names=TRUE) + } + } + + if (args$coldata) { + message("Exporting colData") + out_path <- file.path(args$outdir, "coldata.csv") + write.csv(as.data.frame(colData(se)), file=out_path, quote=FALSE, row.names=TRUE) + } + + if (args$rowdata) { + message("Exporting rowData") + out_path <- file.path(args$outdir, "rowdata.csv") + write.csv(as.data.frame(rowData(se)), file=out_path, quote=FALSE, row.names=TRUE) + } + + message("Export complete.") + """) + + # 3. Subprocess execution + cmd = [ + "Rscript", "-", + "--indir", str(input_dir), + "--outdir", str(output_dir), + ] + if assay_names: + cmd.extend(["--assays", assay_names]) + if export_coldata: + cmd.append("--coldata") + if export_rowdata: + cmd.append("--rowdata") + + try: + with tempfile.NamedTemporaryFile(mode='w', delete=True, suffix=".R") as r_script_file: + r_script_file.write(r_script_content) + r_script_file.flush() + + cmd[1] = r_script_file.name + + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + output_files = [str(p) for p in output_dir.glob("*.csv")] + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {"output_directory": str(output_dir), "exported_files": output_files}, + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + error_message = ( + f"HDF5Array R script failed with exit code {e.returncode}.\n" + f"This may be due to missing R packages or an invalid HDF5SummarizedExperiment directory.\n\n" + f"STDOUT:\n{e.stdout}\n" + f"STDERR:\n{e.stderr}" + ) + raise RuntimeError(error_message) from e + + +@mcp.tool +def inspect_hdf5_array( + input_hdf5: Path, + dataset_name: str, +) -> Dict[str, str]: + """ + Inspects an HDF5 file and prints properties of a specific HDF5Array dataset. + + This tool provides information like dimensions and chunking without loading data. + Requires R and the Bioconductor 'HDF5Array' package. + """ + # 1. Input validation + if not input_hdf5.exists(): + raise FileNotFoundError(f"Input HDF5 file not found: {input_hdf5}") + + # 2. R script for execution + r_script_content = textwrap.dedent(""" + suppressPackageStartupMessages({ + library(optparse) + library(HDF5Array) + }) + + option_list <- list( + make_option("--file", type="character", help="Input HDF5 file path."), + make_option("--name", type="character", help="Name of the dataset to inspect.") + ) + + args <- parse_args(OptionParser(option_list=option_list)) + + # Load the HDF5 array seed + HDF5_dataset <- HDF5Array(args$file, args$name) + + # Print properties + cat("Dataset:", name(HDF5_dataset), "\\n") + cat("Filepath:", path(HDF5_dataset), "\\n") + cat("Dimensions:", paste(dim(HDF5_dataset), collapse=" x "), "\\n") + cat("Datatype:", class(HDF5_dataset@seed@first_val), "\\n") + cat("Chunking:", paste(chunkdim(HDF5_dataset), collapse=" x "), "\\n") + """) + + # 3. Subprocess execution + cmd = [ + "Rscript", "-", + "--file", str(input_hdf5), + "--name", dataset_name, + ] + + try: + with tempfile.NamedTemporaryFile(mode='w', delete=True, suffix=".R") as r_script_file: + r_script_file.write(r_script_content) + r_script_file.flush() + + cmd[1] = r_script_file.name + + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + error_message = ( + f"HDF5Array R script failed with exit code {e.returncode}.\n" + f"This may be due to a missing R package, an incorrect file path, or a non-existent dataset name ('{dataset_name}').\n\n" + f"STDOUT:\n{e.stdout}\n" + f"STDERR:\n{e.stderr}" + ) + raise RuntimeError(error_message) from e \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hdf5array/app/bioconductor-hdf5array_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hdf5array/app/bioconductor-hdf5array_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a61b618420b5474801ce95d2e7ed9d7a7fe963fc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hdf5array/app/bioconductor-hdf5array_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_manual_txt/mcp_bioconductor-hdf5array/app/bioconductor-hdf5array_server.py') +SERVER_NAME = 'biosci_bioconductor_hdf5array' + + +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_manual_txt/mcp_bioconductor-hdf5array/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hdf5array/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hdf5array/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hdf5array/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hdf5array/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..97bfa9f0817812b9b034da837a26e1ca56d332f8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hdf5array/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-hdf5array: + build: . + image: mcp-bioconductor-hdf5array:latest + container_name: mcp-bioconductor-hdf5array + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-hdf5array + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hdf5array/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hdf5array/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0d5fae2ca90a31c0f18e23fab27e79852206c4dc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hdf5array/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-hdf5array + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hdf5array/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hdf5array/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hdf5array/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hoodscanr/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hoodscanr/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aec6ef0262e5e91545dd92f443010da377b15b4d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hoodscanr/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-hoodscanr via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-hoodscanr -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-hoodscanr_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-hoodscanr_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-hoodscanr_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hoodscanr/app/bioconductor-hoodscanr_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hoodscanr/app/bioconductor-hoodscanr_server.py new file mode 100644 index 0000000000000000000000000000000000000000..000dd399219a7d6c90bff6f52623cba3943c1b19 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hoodscanr/app/bioconductor-hoodscanr_server.py @@ -0,0 +1,332 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +@mcp.tool() +def hoodscanr_estimate_radius( + input_spe_path: str, + k: int = 6, + method: str = "mean", +) -> Dict[str, Any]: + """ + Estimate the search radius for neighborhood scanning based on the k-nearest neighbors + of cells in a SpatialExperiment object. + + Args: + input_spe_path: Path to the input SpatialExperiment object saved as an RDS file. + k: Number of nearest neighbors to consider for radius estimation. Default is 6. + method: Method to summarize distances ('mean' or 'median'). Default is 'mean'. + """ + input_path = Path(input_spe_path) + if not input_path.exists(): + return {"error": f"Input file {input_spe_path} does not exist."} + + if k <= 0: + return {"error": "Parameter 'k' must be a positive integer."} + + if method not in ["mean", "median"]: + return {"error": "Parameter 'method' must be either 'mean' or 'median'."} + + # R script to estimate radius + r_command = f""" + library(hoodscanR) + library(SpatialExperiment) + spe <- readRDS('{input_spe_path}') + radius <- estimate_radius(spe, k = {k}, method = '{method}') + cat(radius) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_command], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"hoodscanR::estimate_radius(spe, k={k}, method='{method}')", + "estimated_radius": float(result.stdout.strip()), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + except ValueError: + return { + "error": "Could not parse radius from R output", + "stdout": result.stdout + } + +@mcp.tool() +def hoodscanr_hoodscan( + input_spe_path: str, + output_spe_path: str, + radius: float, + focal_cell_type: Optional[str] = None, + neighbor_cell_type: Optional[str] = None, +) -> Dict[str, Any]: + """ + Perform cellular neighborhood scanning on a SpatialExperiment object. + + Args: + input_spe_path: Path to the input SpatialExperiment RDS file. + output_spe_path: Path where the updated SpatialExperiment RDS file will be saved. + radius: The search radius for identifying neighbors. + focal_cell_type: Optional; specific cell type to act as the center of neighborhoods. + neighbor_cell_type: Optional; specific cell type to look for in the neighborhood. + """ + input_path = Path(input_spe_path) + if not input_path.exists(): + return {"error": f"Input file {input_spe_path} does not exist."} + + if radius <= 0: + return {"error": "Radius must be a positive number."} + + focal_arg = f"'{focal_cell_type}'" if focal_cell_type else "NULL" + neighbor_arg = f"'{neighbor_cell_type}'" if neighbor_cell_type else "NULL" + + r_command = f""" + library(hoodscanR) + library(SpatialExperiment) + spe <- readRDS('{input_spe_path}') + spe <- hoodscan(spe, radius = {radius}, focal_cell_type = {focal_arg}, neighbor_cell_type = {neighbor_arg}) + saveRDS(spe, '{output_spe_path}') + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_command], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"hoodscanR::hoodscan(spe, radius={radius})", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_spe_path] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def hoodscanr_calc_colocalisation( + input_spe_path: str, + output_csv_path: str, + focal_cell_type: Optional[str] = None, + neighbor_cell_type: Optional[str] = None, +) -> Dict[str, Any]: + """ + Calculate the colocalisation matrix between cell types based on neighborhood scanning results. + + Args: + input_spe_path: Path to the SpatialExperiment RDS file (must have been processed by hoodscan). + output_csv_path: Path to save the colocalisation matrix as a CSV file. + focal_cell_type: Optional; filter for specific focal cell types. + neighbor_cell_type: Optional; filter for specific neighbor cell types. + """ + input_path = Path(input_spe_path) + if not input_path.exists(): + return {"error": f"Input file {input_spe_path} does not exist."} + + focal_arg = f"'{focal_cell_type}'" if focal_cell_type else "NULL" + neighbor_arg = f"'{neighbor_cell_type}'" if neighbor_cell_type else "NULL" + + r_command = f""" + library(hoodscanR) + library(SpatialExperiment) + spe <- readRDS('{input_spe_path}') + coloc_mat <- calc_colocalisation(spe, focal_cell_type = {focal_arg}, neighbor_cell_type = {neighbor_arg}) + write.csv(as.matrix(coloc_mat), '{output_csv_path}') + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_command], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "hoodscanR::calc_colocalisation(spe)", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_csv_path] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def hoodscanr_calc_spatial_correlation( + input_spe_path: str, + output_csv_path: str, + focal_cell_type: Optional[str] = None, + neighbor_cell_type: Optional[str] = None, +) -> Dict[str, Any]: + """ + Calculate the spatial correlation between cell types. + + Args: + input_spe_path: Path to the SpatialExperiment RDS file. + output_csv_path: Path to save the spatial correlation matrix as a CSV file. + focal_cell_type: Optional; filter for specific focal cell types. + neighbor_cell_type: Optional; filter for specific neighbor cell types. + """ + input_path = Path(input_spe_path) + if not input_path.exists(): + return {"error": f"Input file {input_spe_path} does not exist."} + + focal_arg = f"'{focal_cell_type}'" if focal_cell_type else "NULL" + neighbor_arg = f"'{neighbor_cell_type}'" if neighbor_cell_type else "NULL" + + r_command = f""" + library(hoodscanR) + library(SpatialExperiment) + spe <- readRDS('{input_spe_path}') + corr_mat <- calc_spatial_correlation(spe, focal_cell_type = {focal_arg}, neighbor_cell_type = {neighbor_arg}) + write.csv(as.matrix(corr_mat), '{output_csv_path}') + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_command], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "hoodscanR::calc_spatial_correlation(spe)", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_csv_path] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def hoodscanr_plot_colocalisation( + input_spe_path: str, + output_plot_path: str, + focal_cell_type: Optional[str] = None, + neighbor_cell_type: Optional[str] = None, + width: int = 8, + height: int = 6, +) -> Dict[str, Any]: + """ + Generate a heatmap of the colocalisation matrix. + + Args: + input_spe_path: Path to the SpatialExperiment RDS file. + output_plot_path: Path to save the plot (e.g., 'plot.png' or 'plot.pdf'). + focal_cell_type: Optional; filter for specific focal cell types. + neighbor_cell_type: Optional; filter for specific neighbor cell types. + width: Width of the output plot in inches. Default is 8. + height: Height of the output plot in inches. Default is 6. + """ + input_path = Path(input_spe_path) + if not input_path.exists(): + return {"error": f"Input file {input_spe_path} does not exist."} + + focal_arg = f"'{focal_cell_type}'" if focal_cell_type else "NULL" + neighbor_arg = f"'{neighbor_cell_type}'" if neighbor_cell_type else "NULL" + + r_command = f""" + library(hoodscanR) + library(SpatialExperiment) + library(ggplot2) + spe <- readRDS('{input_spe_path}') + p <- plot_colocalisation(spe, focal_cell_type = {focal_arg}, neighbor_cell_type = {neighbor_arg}) + ggsave('{output_plot_path}', plot = p, width = {width}, height = {height}) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_command], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "hoodscanR::plot_colocalisation(spe)", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_plot_path] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def hoodscanr_plot_spatial_correlation( + input_spe_path: str, + output_plot_path: str, + focal_cell_type: Optional[str] = None, + neighbor_cell_type: Optional[str] = None, + width: int = 8, + height: int = 6, +) -> Dict[str, Any]: + """ + Generate a heatmap of the spatial correlation matrix. + + Args: + input_spe_path: Path to the SpatialExperiment RDS file. + output_plot_path: Path to save the plot (e.g., 'plot.png' or 'plot.pdf'). + focal_cell_type: Optional; filter for specific focal cell types. + neighbor_cell_type: Optional; filter for specific neighbor cell types. + width: Width of the output plot in inches. Default is 8. + height: Height of the output plot in inches. Default is 6. + """ + input_path = Path(input_spe_path) + if not input_path.exists(): + return {"error": f"Input file {input_spe_path} does not exist."} + + focal_arg = f"'{focal_cell_type}'" if focal_cell_type else "NULL" + neighbor_arg = f"'{neighbor_cell_type}'" if neighbor_cell_type else "NULL" + + r_command = f""" + library(hoodscanR) + library(SpatialExperiment) + library(ggplot2) + spe <- readRDS('{input_spe_path}') + p <- plot_spatial_correlation(spe, focal_cell_type = {focal_arg}, neighbor_cell_type = {neighbor_arg}) + ggsave('{output_plot_path}', plot = p, width = {width}, height = {height}) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_command], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "hoodscanR::plot_spatial_correlation(spe)", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_plot_path] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hoodscanr/app/bioconductor-hoodscanr_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hoodscanr/app/bioconductor-hoodscanr_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8617dbabd837d5b59855258342c92aed9d9a1949 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hoodscanr/app/bioconductor-hoodscanr_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_manual_txt/mcp_bioconductor-hoodscanr/app/bioconductor-hoodscanr_server.py') +SERVER_NAME = 'biosci_bioconductor_hoodscanr' + + +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_manual_txt/mcp_bioconductor-hoodscanr/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hoodscanr/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hoodscanr/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hoodscanr/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hoodscanr/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..0426723e9abd2c36b5abba66ed9c683241551437 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hoodscanr/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-hoodscanr: + build: . + image: mcp-bioconductor-hoodscanr:latest + container_name: mcp-bioconductor-hoodscanr + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-hoodscanr + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hoodscanr/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hoodscanr/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b8b491acfe93cc48db6a171302ddf659bd416dfe --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hoodscanr/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-hoodscanr + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hoodscanr/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hoodscanr/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-hoodscanr/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-humanhippocampus2024/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-humanhippocampus2024/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..657d5caae0f47ddd16435cd28d8d155ca109ca3a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-humanhippocampus2024/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-humanhippocampus2024 via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-humanhippocampus2024 -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-humanhippocampus2024_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-humanhippocampus2024_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-humanhippocampus2024_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-humanhippocampus2024/app/bioconductor-humanhippocampus2024_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-humanhippocampus2024/app/bioconductor-humanhippocampus2024_server.py new file mode 100644 index 0000000000000000000000000000000000000000..15629ad9313efe505b2503538aad0603d44d631b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-humanhippocampus2024/app/bioconductor-humanhippocampus2024_server.py @@ -0,0 +1,197 @@ +import subprocess +import tempfile +import os +from pathlib import Path +from typing import Optional, List, Dict, Any + +# Note: mcp is not imported as per instructions. +# The @mcp.tool decorator is assumed to be available in the environment. + +def _run_r_script(r_script_content: str, env: Optional[Dict[str, str]] = None) -> Dict[str, Any]: + """ + Helper function to execute an R script. + + Args: + r_script_content: The R script as a string. + env: A dictionary of environment variables to pass to the R process. + + Returns: + A dictionary containing stdout, stderr, and the executed command. + + Raises: + subprocess.CalledProcessError: If the R script execution fails. + """ + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R") as temp_r_script: + temp_r_script.write(r_script_content) + temp_r_script_path = Path(temp_r_script.name) + + command = ["Rscript", str(temp_r_script_path)] + + # Merge current environment with provided environment variables + full_env = os.environ.copy() + if env: + full_env.update(env) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + env=full_env + ) + stdout = result.stdout + stderr = result.stderr + except subprocess.CalledProcessError as e: + os.remove(temp_r_script_path) + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed with exit code {e.returncode}" + } + finally: + os.remove(temp_r_script_path) + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": [] + } + +@mcp.tool() +def list_humanhippocampus2024_datasets() -> Dict[str, Any]: + """ + Lists available datasets provided by the bioconductor-humanhippocampus2024 R package. + + This tool queries the ExperimentHub for datasets associated with the + humanHippocampus2024 package, providing their IDs, titles, and descriptions. + """ + r_script = """ + # Ensure BiocManager is installed + if (!requireNamespace("BiocManager", quietly = TRUE)) { + install.packages("BiocManager", repos="https://cloud.r-project.org") + } + # Ensure humanHippocampus2024 is installed + if (!requireNamespace("humanHippocampus2024", quietly = TRUE)) { + BiocManager::install("humanHippocampus2024", update=FALSE, ask=FALSE) + } + + library(ExperimentHub) + library(humanHippocampus2024) # Load to ensure package data is registered with EH + + eh <- ExperimentHub() + + # Query for datasets specifically from humanHippocampus2024 + # We use the package name as a query term, which ExperimentHub often uses for tagging. + records <- mcols(query(eh, "humanHippocampus2024")) + + if (nrow(records) > 0) { + cat("Available datasets from humanHippocampus2024:\\n") + for (i in 1:nrow(records)) { + cat(sprintf(" ID: %s\\n", records$eh_id[i])) + cat(sprintf(" Title: %s\\n", records$title[i])) + cat(sprintf(" Description: %s\\n", records$description[i])) + if (!is.null(records$tags[[i]])) { + cat(sprintf(" Tags: %s\\n", paste(records$tags[[i]], collapse=", "))) + } + cat("---\\n") + } + } else { + cat("No datasets found for humanHippocampus2024.\\n") + } + """ + + try: + result = _run_r_script(r_script) + return { + "command_executed": result["command_executed"], + "stdout": result["stdout"], + "stderr": result["stderr"], + "output_files": [] + } + except Exception as e: + return { + "command_executed": "Rscript ...", + "stdout": "", + "stderr": str(e), + "error": "Failed to list datasets." + } + + +@mcp.tool() +def get_humanhippocampus2024_dataset( + eh_id: str, + output_file: Path, +) -> Dict[str, Any]: + """ + Retrieves a specific dataset from the bioconductor-humanhippocampus2024 R package + via its ExperimentHub ID and saves it as an R RDS file. + + Args: + eh_id: The ExperimentHub ID of the dataset to retrieve (e.g., "EHXXXX"). + output_file: The path where the retrieved R object will be saved as an RDS file. + The file will contain the R object (e.g., SpatialExperiment or SummarizedExperiment). + """ + if not eh_id: + raise ValueError("ExperimentHub ID (eh_id) cannot be empty.") + if not output_file.parent.exists(): + output_file.parent.mkdir(parents=True, exist_ok=True) + + r_script = f""" + # Ensure BiocManager is installed + if (!requireNamespace("BiocManager", quietly = TRUE)) {{ + install.packages("BiocManager", repos="https://cloud.r-project.org") + }} + # Ensure humanHippocampus2024 is installed + if (!requireNamespace("humanHippocampus2024", quietly = TRUE)) {{ + BiocManager::install("humanHippocampus2024", update=FALSE, ask=FALSE) + }} + + library(ExperimentHub) + library(humanHippocampus2024) # Load to ensure package data is registered with EH + + eh <- ExperimentHub() + + eh_id <- Sys.getenv("MCP_EH_ID") + output_file <- Sys.getenv("MCP_OUTPUT_FILE") + + if (is.null(eh_id) || eh_id == "") {{ + stop("ExperimentHub ID (MCP_EH_ID) not provided.") + }} + if (is.null(output_file) || output_file == "") {{ + stop("Output file path (MCP_OUTPUT_FILE) not provided.") + }} + + # Retrieve the dataset + data_object <- eh[[eh_id]] + + # Save the R object to an RDS file + saveRDS(data_object, file = output_file) + cat(sprintf("Dataset '%s' saved to '%s'\\n", eh_id, output_file)) + """ + + env_vars = { + "MCP_EH_ID": eh_id, + "MCP_OUTPUT_FILE": str(output_file) + } + + try: + result = _run_r_script(r_script, env=env_vars) + if "error" in result: + raise RuntimeError(result["error"] + "\n" + result["stderr"]) + + return { + "command_executed": result["command_executed"], + "stdout": result["stdout"], + "stderr": result["stderr"], + "output_files": [str(output_file)] + } + except Exception as e: + return { + "command_executed": "Rscript ...", + "stdout": "", + "stderr": str(e), + "error": f"Failed to retrieve dataset '{eh_id}'." + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-humanhippocampus2024/app/bioconductor-humanhippocampus2024_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-humanhippocampus2024/app/bioconductor-humanhippocampus2024_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9b3820e264dc8ba277d80a7d7e4259a33564b96d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-humanhippocampus2024/app/bioconductor-humanhippocampus2024_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_manual_txt/mcp_bioconductor-humanhippocampus2024/app/bioconductor-humanhippocampus2024_server.py') +SERVER_NAME = 'biosci_bioconductor_humanhippocampus2024' + + +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_manual_txt/mcp_bioconductor-humanhippocampus2024/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-humanhippocampus2024/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-humanhippocampus2024/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-humanhippocampus2024/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-humanhippocampus2024/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f6c04c4f39989e3f24678d3ea5957ba1b5fc8606 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-humanhippocampus2024/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-humanhippocampus2024: + build: . + image: mcp-bioconductor-humanhippocampus2024:latest + container_name: mcp-bioconductor-humanhippocampus2024 + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-humanhippocampus2024 + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-humanhippocampus2024/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-humanhippocampus2024/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..682a932cbf75e6be5805bde576d31c0ff961bc1f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-humanhippocampus2024/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-humanhippocampus2024 + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-humanhippocampus2024/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-humanhippocampus2024/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-humanhippocampus2024/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcdatasets/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcdatasets/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..bee303f346ca8a9a652ec42afbe739b3498c6f29 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcdatasets/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-imcdatasets via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-imcdatasets -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-imcdatasets_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-imcdatasets_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-imcdatasets_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcdatasets/app/bioconductor-imcdatasets_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcdatasets/app/bioconductor-imcdatasets_server.py new file mode 100644 index 0000000000000000000000000000000000000000..468cf4ded8d46651348c9ded64b502d5726f54a5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcdatasets/app/bioconductor-imcdatasets_server.py @@ -0,0 +1,206 @@ +import subprocess +import tempfile +from pathlib import Path +import logging +from typing import Literal, List, Dict, Any, Optional + +# Setup logging +logging.basicConfig(level=logging.INFO) +log = logging.getLogger(__name__) + +# Mock the mcp.tool decorator for standalone execution +def mcp_tool_mock(*args, **kwargs): + def decorator(func): + return func + return decorator + +mcp = type('mcp', (), {'tool': mcp_tool_mock}) + +@mcp.tool() +def download_imcdataset( + dataset: Literal[ + "Damond_2016_IMdata", + "Damond_2019_hyperion", + "JacksonFischer_2020_squamous", + "Zanotelli_2020_SCLC", + "Kuett_2022_TMA", + ], + output_dir: Path, + save_sce: bool = True, + save_images: bool = True, + save_masks: bool = True, +) -> Dict[str, Any]: + """ + Downloads and processes a specified Imaging Mass Cytometry (IMC) dataset from the imcdatasets Bioconductor package. + + This tool fetches a dataset, which typically consists of a SingleCellExperiment object, + multichannel images, and cell masks. It saves these components into standard file formats. + + Args: + dataset: The name of the IMC dataset to download. + output_dir: The directory where the output files will be saved. + save_sce: If True, saves the SingleCellExperiment object as an AnnData (.h5ad) file. + save_images: If True, saves the multichannel images as multi-page TIFF files. + save_masks: If True, saves the cell segmentation masks as multi-page TIFF files. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output file paths. + """ + # 1. Input Validation + if not (save_sce or save_images or save_masks): + raise ValueError("At least one of 'save_sce', 'save_images', or 'save_masks' must be True.") + + try: + output_dir.mkdir(parents=True, exist_ok=True) + except Exception as e: + log.error(f"Failed to create output directory {output_dir}: {e}") + raise + + # 2. R Script Generation + # Convert Python bools to R's "TRUE" / "FALSE" strings + r_save_sce = "TRUE" if save_sce else "FALSE" + r_save_images = "TRUE" if save_images else "FALSE" + r_save_masks = "TRUE" if save_masks else "FALSE" + + # The R script handles two cases: + # - Datasets that return a list of (sce, images, masks). + # - The special case 'Damond_2016_IMdata' which returns only a SingleCellExperiment object. + r_script = f""" + # Load required libraries quietly + suppressPackageStartupMessages(library(imcdatasets)) + suppressPackageStartupMessages(library(SingleCellExperiment)) + suppressPackageStartupMessages(library(cytomapper)) + suppressPackageStartupMessages(library(sceasy)) + suppressPackageStartupMessages(library(tiff)) + + output_dir <- "{output_dir.resolve()}" + dataset_name <- "{dataset}" + + # Load the dataset + cat(paste0("Loading dataset: ", dataset_name, "\\n")) + data_object <- get(dataset_name)() + cat("Dataset loaded successfully.\\n") + + # Check the type of the returned object and process accordingly + if (is(data_object, "SingleCellExperiment")) {{ + # Case 1: The function returns a single SingleCellExperiment object + if ({r_save_sce}) {{ + cat("Saving SingleCellExperiment object...\\n") + sce_file <- file.path(output_dir, paste0(dataset_name, "_sce.h5ad")) + tryCatch({{ + sceasy::convertFormat(data_object, from="sce", to="anndata", outFile=sce_file) + cat(paste0("SCE object saved to: ", sce_file, "\\n")) + }}, error = function(e) {{ + cat(paste0("Error saving SCE object: ", e$message, "\\n")) + }}) + }} + if ({r_save_images} || {r_save_masks}) {{ + cat(paste0("Warning: The ", dataset_name, " dataset does not contain separate image or mask objects.\\n")) + }} + }} else if (is.list(data_object) && all(c("sce", "images", "masks") %in% names(data_object))) {{ + # Case 2: The function returns a list containing sce, images, and masks + if ({r_save_sce}) {{ + cat("Saving SingleCellExperiment object...\\n") + sce_file <- file.path(output_dir, paste0(dataset_name, "_sce.h5ad")) + tryCatch({{ + sceasy::convertFormat(data_object$sce, from="sce", to="anndata", outFile=sce_file) + cat(paste0("SCE object saved to: ", sce_file, "\\n")) + }}, error = function(e) {{ + cat(paste0("Error saving SCE object: ", e$message, "\\n")) + }}) + }} + + if ({r_save_images}) {{ + cat("Saving images...\\n") + images <- data_object$images + for (image_name in names(images)) {{ + img_file <- file.path(output_dir, paste0(image_name, "_image.tiff")) + tryCatch({{ + img_array <- as.array(images[[image_name]]) + tiff::write_tiff(img_array, path = img_file, compression = "LZW") + cat(paste0("Image saved to: ", img_file, "\\n")) + }}, error = function(e) {{ + cat(paste0("Error saving image '", image_name, "': ", e$message, "\\n")) + }}) + }} + }} + + if ({r_save_masks}) {{ + cat("Saving masks...\\n") + masks <- data_object$masks + for (mask_name in names(masks)) {{ + mask_file <- file.path(output_dir, paste0(mask_name, "_mask.tiff")) + tryCatch({{ + mask_array <- as.array(masks[[mask_name]]) + tiff::write_tiff(mask_array, path = mask_file, compression = "LZW") + cat(paste0("Mask saved to: ", mask_file, "\\n")) + }}, error = function(e) {{ + cat(paste0("Error saving mask '", mask_name, "': ", e$message, "\\n")) + }}) + }} + }} + }} else {{ + stop("The loaded dataset has an unexpected format.") + }} + + cat("Processing complete.\\n") + """ + + # 3. Subprocess Execution + command_executed = "" + output_files = [] + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_script: + tmp_script.write(r_script) + script_path = tmp_script.name + + command = ["Rscript", script_path] + command_executed = " ".join(command) + log.info(f"Executing command: {command_executed}") + + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + cwd=output_dir + ) + + # 4. Collect Output + stdout = process.stdout + stderr = process.stderr + log.info("R script executed successfully.") + log.info(f"STDOUT:\n{stdout}") + if stderr: + log.warning(f"STDERR:\n{stderr}") + + # Scan output directory for created files + output_files = [str(f.resolve()) for f in output_dir.glob('*') if f.is_file()] + + except subprocess.CalledProcessError as e: + log.error(f"Error executing R script for dataset {dataset}.") + log.error(f"Return code: {e.returncode}") + log.error(f"STDOUT: {e.stdout}") + log.error(f"STDERR: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": "R script execution failed." + } + except FileNotFoundError: + log.error("Rscript not found. Please ensure R is installed and in your PATH.") + raise + finally: + # Clean up the temporary script file + if 'script_path' in locals() and Path(script_path).exists(): + Path(script_path).unlink() + + # 5. Return Structured Output + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcdatasets/app/bioconductor-imcdatasets_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcdatasets/app/bioconductor-imcdatasets_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d0aee1370b222540a47fc1539c10387de49ab968 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcdatasets/app/bioconductor-imcdatasets_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_manual_txt/mcp_bioconductor-imcdatasets/app/bioconductor-imcdatasets_server.py') +SERVER_NAME = 'biosci_bioconductor_imcdatasets' + + +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_manual_txt/mcp_bioconductor-imcdatasets/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcdatasets/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcdatasets/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcdatasets/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcdatasets/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..41853f3acb7b7da635ed5756adf5ba7b65095d56 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcdatasets/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-imcdatasets: + build: . + image: mcp-bioconductor-imcdatasets:latest + container_name: mcp-bioconductor-imcdatasets + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-imcdatasets + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcdatasets/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcdatasets/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c8f39ab71b3d84a2c641c4fb6d5b428b17319af6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcdatasets/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-imcdatasets + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcdatasets/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcdatasets/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcdatasets/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcrtools/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcrtools/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ba94b99931ffc59e28a5684f5d74096eb1da097e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcrtools/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-imcrtools via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-imcrtools -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-imcrtools_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-imcrtools_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-imcrtools_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcrtools/app/bioconductor-imcrtools_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcrtools/app/bioconductor-imcrtools_server.py new file mode 100644 index 0000000000000000000000000000000000000000..48c3f021176322ef2436083a16061bfa9acedf31 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcrtools/app/bioconductor-imcrtools_server.py @@ -0,0 +1,417 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, Literal, List +import logging + +# Configure logging +logging.basicConfig(level=logging.INFO) + +@mcp.tool() +def build_spatial_graph( + input_object: Path, + output_rds: Path, + img_id: str, + type: Literal["knn", "delaunay", "expansion", "voronoi"], + k: Optional[int] = 5, + max_dist: Optional[float] = None, + directed: bool = False, + name: str = "spatial_graph", +) -> dict: + """ + Constructs a spatial graph to represent cell-cell interactions. + + This function builds a graph where nodes are cells and edges represent spatial proximity. + The graph is added to the colPair slot of the SpatialExperiment object. + + Args: + input_object: Path to the input SpatialExperiment object in RDS format. + output_rds: Path to save the output SpatialExperiment object with the graph in RDS format. + img_id: The column name in colData that identifies images. Graphs are built per image. + type: The type of graph to build. + k: The number of nearest neighbors for the 'knn' graph type. + max_dist: The maximum distance for graph construction using the 'expansion' type. + directed: Should the graph be directed? Defaults to FALSE. + name: The name under which to store the graph in the colPair slot. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output RDS file. + """ + # Input validation + if not input_object.is_file(): + raise FileNotFoundError(f"Input file not found: {input_object}") + if type == "knn" and (k is None or k <= 0): + raise ValueError("Parameter 'k' must be a positive integer for 'knn' graph type.") + if type == "expansion" and (max_dist is None or max_dist <= 0): + raise ValueError("Parameter 'max_dist' must be a positive float for 'expansion' graph type.") + + r_script_content = f""" + library(imcRtools) + library(SpatialExperiment) + library(S4Vectors) + library(igraph) + + args <- commandArgs(trailingOnly=TRUE) + input_rds_path <- args[1] + output_rds_path <- args[2] + p_img_id <- args[3] + p_type <- args[4] + p_k <- if (args[5] == "NULL") NULL else as.integer(args[5]) + p_max_dist <- if (args[6] == "NULL") NULL else as.numeric(args[6]) + p_directed <- as.logical(args[7]) + p_name <- args[8] + + spe <- readRDS(input_rds_path) + + spe <- buildSpatialGraph(spe, + img_id = p_img_id, + type = p_type, + k = p_k, + max_dist = p_max_dist, + directed = p_directed, + name = p_name) + + saveRDS(spe, file = output_rds_path) + """ + + cmd_args = [ + str(input_object), + str(output_rds), + img_id, + type, + str(k) if k is not None else "NULL", + str(max_dist) if max_dist is not None else "NULL", + "TRUE" if directed else "FALSE", + name, + ] + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = r_script_file.name + + command = ["Rscript", r_script_path] + cmd_args + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + logging.info(f"Successfully built spatial graph for {input_object}") + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_rds)] + } + except subprocess.CalledProcessError as e: + logging.error(f"Error in build_spatial_graph: {e.stderr}") + raise RuntimeError(f"R script execution failed: {e.stderr}") + finally: + Path(r_script_path).unlink() + + +@mcp.tool() +def aggregate_neighbors( + input_object: Path, + output_rds: Path, + col_pair_name: str, + aggregate_by: Literal["metadata", "expression"], + count_by: Optional[str] = None, + assay_type: str = "counts", + name: str = "aggregated_neighbors", +) -> dict: + """ + Aggregates features of neighboring cells for each cell. + + This function summarizes information from neighboring cells, such as cell types or + mean marker expression, and adds it to the colData of the SpatialExperiment object. + + Args: + input_object: Path to the input SpatialExperiment object (RDS format) containing a spatial graph. + output_rds: Path to save the updated SpatialExperiment object (RDS format). + col_pair_name: The name of the graph in colPair(object) to use for aggregation. + aggregate_by: Whether to aggregate cell 'metadata' (e.g., cell types) or marker 'expression'. + count_by: If aggregating by metadata, the colData column to use for counting (e.g., 'cell_type'). + assay_type: If aggregating by expression, the assay to use for summarization. + name: The name for the output data frame in colData(object). + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output RDS file. + """ + # Input validation + if not input_object.is_file(): + raise FileNotFoundError(f"Input file not found: {input_object}") + if aggregate_by == "metadata" and count_by is None: + raise ValueError("Parameter 'count_by' must be specified when 'aggregate_by' is 'metadata'.") + + r_script_content = f""" + library(imcRtools) + library(SpatialExperiment) + + args <- commandArgs(trailingOnly=TRUE) + input_rds_path <- args[1] + output_rds_path <- args[2] + p_col_pair_name <- args[3] + p_aggregate_by <- args[4] + p_count_by <- if (args[5] == "NULL") NULL else args[5] + p_assay_type <- args[6] + p_name <- args[7] + + spe <- readRDS(input_rds_path) + + spe <- aggregateNeighbors(spe, + colPairName = p_col_pair_name, + aggregate_by = p_aggregate_by, + count_by = p_count_by, + assay_type = p_assay_type, + name = p_name) + + saveRDS(spe, file = output_rds_path) + """ + + cmd_args = [ + str(input_object), + str(output_rds), + col_pair_name, + aggregate_by, + count_by if count_by is not None else "NULL", + assay_type, + name, + ] + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = r_script_file.name + + command = ["Rscript", r_script_path] + cmd_args + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + logging.info(f"Successfully aggregated neighbors for {input_object}") + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_rds)] + } + except subprocess.CalledProcessError as e: + logging.error(f"Error in aggregate_neighbors: {e.stderr}") + raise RuntimeError(f"R script execution failed: {e.stderr}") + finally: + Path(r_script_path).unlink() + + +@mcp.tool() +def test_interactions( + input_object: Path, + output_csv: Path, + group_by: str, + label: str, + col_pair_name: str = "spatial_graph", + method: Literal["classic", "histocat", "patch"] = "classic", + permutations: int = 1000, + p_adjust_method: str = "BH", +) -> dict: + """ + Performs permutation testing to find significant cell-cell interactions. + + This function tests for spatial attraction or avoidance between cell types by comparing + observed interaction counts to a null distribution generated by permuting cell labels. + + Args: + input_object: Path to the input SpatialExperiment object (RDS format). + output_csv: Path to save the interaction testing results as a CSV file. + group_by: The colData column for grouping images before testing (e.g., patient ID). + label: The colData column containing cell type labels. + col_pair_name: The name of the graph in colPair(object) to use. + method: The permutation method to use. + permutations: The number of permutations to perform. + p_adjust_method: Method for multiple testing correction. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output CSV file. + """ + # Input validation + if not input_object.is_file(): + raise FileNotFoundError(f"Input file not found: {input_object}") + if permutations <= 0: + raise ValueError("Number of permutations must be a positive integer.") + + r_script_content = f""" + library(imcRtools) + library(SpatialExperiment) + library(data.table) + + args <- commandArgs(trailingOnly=TRUE) + input_rds_path <- args[1] + output_csv_path <- args[2] + p_group_by <- args[3] + p_label <- args[4] + p_col_pair_name <- args[5] + p_method <- args[6] + p_permutations <- as.integer(args[7]) + p_p_adjust_method <- args[8] + + spe <- readRDS(input_rds_path) + + interaction_results <- testInteractions(spe, + group_by = p_group_by, + label = p_label, + colPairName = p_col_pair_name, + method = p_method, + permutations = p_permutations, + p_adjust_method = p_p_adjust_method) + + fwrite(interaction_results, file = output_csv_path) + """ + + cmd_args = [ + str(input_object), + str(output_csv), + group_by, + label, + col_pair_name, + method, + str(permutations), + p_adjust_method, + ] + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = r_script_file.name + + command = ["Rscript", r_script_path] + cmd_args + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + logging.info(f"Successfully tested interactions for {input_object}") + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_csv)] + } + except subprocess.CalledProcessError as e: + logging.error(f"Error in test_interactions: {e.stderr}") + raise RuntimeError(f"R script execution failed: {e.stderr}") + finally: + Path(r_script_path).unlink() + + +@mcp.tool() +def plot_spatial_graph( + input_object: Path, + output_image: Path, + img_id: str, + node_color_by: Optional[str] = None, + node_shape_by: Optional[str] = None, + node_size_by: Optional[str] = None, + col_pair_name: str = "spatial_graph", + draw_edges: bool = True, + directed: bool = False, +) -> dict: + """ + Visualizes the spatial graph for a specific image. + + This function generates a plot of cells (nodes) and their spatial interactions (edges) + for a single image ID. + + Args: + input_object: Path to the input SpatialExperiment object (RDS format). + output_image: Path to save the output plot (e.g., plot.png, plot.pdf). + img_id: The specific image ID to plot from the 'img_id' column used in build_spatial_graph. + node_color_by: The colData column to color nodes by (e.g., 'cell_type'). + node_shape_by: The colData column to shape nodes by. + node_size_by: The colData column to size nodes by. + col_pair_name: The name of the graph to visualize. + draw_edges: Whether to draw the edges of the graph. + directed: Are the edges directed? Passed to ggraph. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output image file. + """ + # Input validation + if not input_object.is_file(): + raise FileNotFoundError(f"Input file not found: {input_object}") + if not output_image.suffix in [".png", ".pdf", ".svg", ".jpeg", ".tiff"]: + raise ValueError("Output image format must be one of: .png, .pdf, .svg, .jpeg, .tiff") + + r_script_content = f""" + library(imcRtools) + library(SpatialExperiment) + library(ggplot2) + + args <- commandArgs(trailingOnly=TRUE) + input_rds_path <- args[1] + output_image_path <- args[2] + p_img_id <- args[3] + p_node_color_by <- if (args[4] == "NULL") NULL else args[4] + p_node_shape_by <- if (args[5] == "NULL") NULL else args[5] + p_node_size_by <- if (args[6] == "NULL") NULL else args[6] + p_col_pair_name <- args[7] + p_draw_edges <- as.logical(args[8]) + p_directed <- as.logical(args[9]) + + spe <- readRDS(input_rds_path) + + p <- plotSpatialGraph(spe, + img_id = p_img_id, + node_color_by = p_node_color_by, + node_shape_by = p_node_shape_by, + node_size_by = p_node_size_by, + colPairName = p_col_pair_name, + draw_edges = p_draw_edges, + directed = p_directed) + + ggsave(output_image_path, plot = p, width = 10, height = 10) + """ + + cmd_args = [ + str(input_object), + str(output_image), + img_id, + node_color_by if node_color_by is not None else "NULL", + node_shape_by if node_shape_by is not None else "NULL", + node_size_by if node_size_by is not None else "NULL", + col_pair_name, + "TRUE" if draw_edges else "FALSE", + "TRUE" if directed else "FALSE", + ] + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = r_script_file.name + + command = ["Rscript", r_script_path] + cmd_args + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + logging.info(f"Successfully plotted spatial graph for image {img_id}") + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_image)] + } + except subprocess.CalledProcessError as e: + logging.error(f"Error in plot_spatial_graph: {e.stderr}") + raise RuntimeError(f"R script execution failed: {e.stderr}") + finally: + Path(r_script_path).unlink() \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcrtools/app/bioconductor-imcrtools_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcrtools/app/bioconductor-imcrtools_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3a2ab40c8a64057feaf0099c96312d9adb52055d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcrtools/app/bioconductor-imcrtools_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_manual_txt/mcp_bioconductor-imcrtools/app/bioconductor-imcrtools_server.py') +SERVER_NAME = 'biosci_bioconductor_imcrtools' + + +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_manual_txt/mcp_bioconductor-imcrtools/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcrtools/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcrtools/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcrtools/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcrtools/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..54888b25732061ffab696c3587f02a60521a4730 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcrtools/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-imcrtools: + build: . + image: mcp-bioconductor-imcrtools:latest + container_name: mcp-bioconductor-imcrtools + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-imcrtools + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcrtools/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcrtools/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e4bc94537dfa36fb7175c850db3ec2ee151d5dc7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcrtools/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-imcrtools + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcrtools/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcrtools/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-imcrtools/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-impute/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-impute/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7bdefc8af871aa387cfff8bcbd04cac3c1ed7fff --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-impute/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-impute via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-impute -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-impute_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-impute_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-impute_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-impute/app/bioconductor-impute_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-impute/app/bioconductor-impute_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b203d73e3610f70d3c9df908e4040416d5cabc3f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-impute/app/bioconductor-impute_server.py @@ -0,0 +1,170 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided by the MCP framework. +def tool(func): + def wrapper(*args, **kwargs): + # In a real scenario, the MCP framework would handle + # the execution environment, dependency management, etc. + return func(*args, **kwargs) + return wrapper + +mcp = type("mcp", (), {"tool": tool}) + + +@mcp.tool +def impute_knn( + data: Path, + output_file: Path, + k: int = 10, + rowmax: float = 0.5, + colmax: float = 0.8, + maxp: int = 1500, + rng_seed: int = 362436069, + input_separator: str = "\t", + has_header: bool = True, + row_names_column: int = 1, +) -> dict: + """ + Imputes missing values in a microarray data matrix using the k-Nearest Neighbors (KNN) algorithm. + + This function is a wrapper for the `impute.knn` function from the Bioconductor 'impute' package. + It takes a data matrix with missing values (represented as NA) and fills them in by averaging + the values from the 'k' most similar rows (genes). + + Args: + data: Path to the input data matrix file (e.g., CSV or TSV). Missing values should be represented as 'NA'. + output_file: Path to save the imputed data matrix. + k: The number of nearest neighbors to use for imputation. + rowmax: The maximum allowed percentage of missing values in any row. Rows exceeding this threshold are not imputed and returned as all NAs. + colmax: The maximum allowed percentage of missing values in any column. If any column exceeds this, the program will abort. + maxp: The maximum number of genes to process in a single batch. If the dataset is larger, it will be processed in chunks. + rng_seed: Seed for the random number generator to ensure reproducibility. + input_separator: The delimiter used in the input file (e.g., '\\t' for TSV, ',' for CSV). + has_header: A boolean indicating if the input file has a header row. + row_names_column: The 1-based index of the column containing row names. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output file paths. + """ + # 1. Input validation + if not data.is_file(): + raise FileNotFoundError(f"Input file not found: {data}") + if k <= 0: + raise ValueError("The number of neighbors 'k' must be a positive integer.") + if not (0.0 <= rowmax <= 1.0): + raise ValueError("'rowmax' must be a float between 0.0 and 1.0.") + if not (0.0 <= colmax <= 1.0): + raise ValueError("'colmax' must be a float between 0.0 and 1.0.") + if maxp <= 0: + raise ValueError("'maxp' must be a positive integer.") + if row_names_column <= 0: + raise ValueError("'row_names_column' must be a positive integer.") + + # 2. R script generation + r_script_content = f""" + # Load the required library + if (!requireNamespace("impute", quietly = TRUE)) {{ + stop("The 'impute' package is not installed. Please install it from Bioconductor.") + }} + library(impute) + + # Define parameters + input_file <- "{data.resolve()}" + output_file <- "{output_file.resolve()}" + k_val <- {k} + rowmax_val <- {rowmax} + colmax_val <- {colmax} + maxp_val <- {maxp} + rng_seed_val <- {rng_seed} + sep_char <- "{input_separator}" + header_bool <- {"TRUE" if has_header else "FALSE"} + row_names_col_idx <- {row_names_column} + + # Read the input data + # Using tryCatch to provide a more informative error message + data_matrix <- tryCatch({{ + as.matrix(read.table( + input_file, + header=header_bool, + sep=sep_char, + row.names=row_names_col_idx, + as.is=TRUE, + check.names=FALSE + )) + }}, error = function(e) {{ + stop(paste("Failed to read the input file:", e$message)) + }}) + + # Set the seed for reproducibility + set.seed(rng_seed_val) + + # Perform KNN imputation + # The result is a list, with the imputed data in the 'data' element + imputed_result <- impute.knn( + data_matrix, + k = k_val, + rowmax = rowmax_val, + colmax = colmax_val, + maxp = maxp_val + ) + imputed_data <- imputed_result$data + + # Write the imputed data to the output file + write.table( + imputed_data, + file = output_file, + sep = sep_char, + quote = FALSE, + col.names = NA # Keeps column names and adds a blank for the row names column + ) + + cat("Imputation complete. Output written to", output_file, "\\n") + """ + + # 3. Subprocess execution + command = [] + stdout_str = "" + stderr_str = "" + + try: + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R") as r_script_file: + r_script_file.write(r_script_content) + script_path = r_script_file.name + + command = ["Rscript", script_path] + + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + stdout_str = process.stdout + stderr_str = process.stderr + + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": "R script execution failed." + } + finally: + # Clean up the temporary R script + if 'script_path' in locals() and Path(script_path).exists(): + Path(script_path).unlink() + + # 4. Structured result return + return { + "command_executed": " ".join(command), + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": [str(output_file)] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-impute/app/bioconductor-impute_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-impute/app/bioconductor-impute_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d9042b35f4fdaf4ec502bf34ccf23ab820bd56fb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-impute/app/bioconductor-impute_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_manual_txt/mcp_bioconductor-impute/app/bioconductor-impute_server.py') +SERVER_NAME = 'biosci_bioconductor_impute' + + +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_manual_txt/mcp_bioconductor-impute/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-impute/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-impute/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-impute/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-impute/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..48eaf8a733f4024b5f7383bdc2cf9078f1c076f8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-impute/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-impute: + build: . + image: mcp-bioconductor-impute:latest + container_name: mcp-bioconductor-impute + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-impute + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-impute/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-impute/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2203a61220545c7d82d1989a22a9cb738b501456 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-impute/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-impute + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-impute/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-impute/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-impute/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-interactivedisplaybase/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-interactivedisplaybase/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6f4cd2a5c71838a423aa572705e3c4403719003d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-interactivedisplaybase/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-interactivedisplaybase via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-interactivedisplaybase -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-interactivedisplaybase_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-interactivedisplaybase_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-interactivedisplaybase_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-interactivedisplaybase/app/bioconductor-interactivedisplaybase_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-interactivedisplaybase/app/bioconductor-interactivedisplaybase_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c503755ef07c3b80f7e7814e656e2ee57cab68ed --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-interactivedisplaybase/app/bioconductor-interactivedisplaybase_server.py @@ -0,0 +1,36 @@ +import subprocess +from pathlib import Path +from typing import Optional + +# MCP decorator is omitted as per instructions +# @mcp.tool() + +def interactive_display_base(): + """ + Placeholder for the deprecated Bioconductor R library 'interactiveDisplayBase'. + + This package is an R library for building interactive Shiny applications and does not + provide a command-line interface. It is also deprecated and has been removed from + Bioconductor. As such, it cannot be executed as a standard command-line tool. + This function returns an informative message instead of executing a command. + """ + # This is not a command-line tool. The core functionality is to provide + # methods within an R session to generate interactive Shiny displays. + # This is fundamentally incompatible with the non-interactive MCP model. + # The package is also deprecated. + # Therefore, this function does not execute any subprocess. + # It returns a structured message explaining the situation. + + info_message = ( + "The 'bioconductor-interactivedisplaybase' package is an R library for " + "creating interactive Shiny applications and does not have a command-line interface. " + "It is also deprecated and removed from Bioconductor. " + "Therefore, it cannot be executed as a command-line tool." + ) + + return { + "command_executed": "", + "stdout": info_message, + "stderr": "This is an informational message, not an error.", + "output_files": [] + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-interactivedisplaybase/app/bioconductor-interactivedisplaybase_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-interactivedisplaybase/app/bioconductor-interactivedisplaybase_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7f7abe01448696169f5555dfcf69a8afe6b3a53f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-interactivedisplaybase/app/bioconductor-interactivedisplaybase_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_manual_txt/mcp_bioconductor-interactivedisplaybase/app/bioconductor-interactivedisplaybase_server.py') +SERVER_NAME = 'biosci_bioconductor_interactivedisplaybase' + + +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_manual_txt/mcp_bioconductor-interactivedisplaybase/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-interactivedisplaybase/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-interactivedisplaybase/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-interactivedisplaybase/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-interactivedisplaybase/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..27fcbcd7b100fb67df8f591cfedd0287e52a7609 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-interactivedisplaybase/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-interactivedisplaybase: + build: . + image: mcp-bioconductor-interactivedisplaybase:latest + container_name: mcp-bioconductor-interactivedisplaybase + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-interactivedisplaybase + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-interactivedisplaybase/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-interactivedisplaybase/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..638e635c19674a5a595d4c598bcfedd9f61d7e11 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-interactivedisplaybase/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-interactivedisplaybase + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-interactivedisplaybase/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-interactivedisplaybase/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-interactivedisplaybase/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-iranges/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-iranges/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..78c8aad093ce7b8c16bd39ced21755f4ca8bea80 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-iranges/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-iranges via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-iranges -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-iranges_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-iranges_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-iranges_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-iranges/app/bioconductor-iranges_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-iranges/app/bioconductor-iranges_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9a01a671b4a997f461c83b9ff6373c8a35f64b79 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-iranges/app/bioconductor-iranges_server.py @@ -0,0 +1,123 @@ +import subprocess +from pathlib import Path +from typing import Optional, List + +# MCP decorator is included as per the instructions. +# No import is provided as it's assumed to be in the execution environment. + +@mcp.tool() +def run_iranges_script( + script_file: Optional[Path] = None, + expression: Optional[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 in an environment with the bioconductor-iranges package. + + This tool is a wrapper for the Rscript command-line interpreter. Since + bioconductor-iranges is an R library, this tool allows you to run scripts + that leverage its functionality. You must provide either a script file or an + R expression string to execute. + + Args: + script_file: Path to the R script file to be executed. + expression: An R expression string to be executed directly. + Mutually exclusive with script_file. + script_args: A list of arguments to be passed to the R script. + verbose: Print information on progress. Corresponds to --verbose. + default_packages: Comma-separated list of package names to be loaded, + or 'NULL'. Corresponds to --default-packages. + save: Save the workspace at the end of the session. Corresponds to --save. + no_environ: Don't read the site and user environment files. + Corresponds to --no-environ. + no_site_file: Don't read the site-wide Rprofile. + Corresponds to --no-site-file. + no_init_file: Don't read the user R profile. Corresponds to --no-init-file. + restore: Restore previously saved objects at startup. + Corresponds to --restore. + vanilla: Combine --no-save, --no-restore, --no-site-file, + --no-init-file and --no-environ. Corresponds to --vanilla. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list + of output files (which will be empty as output is script-dependent). + """ + # 1. Input Validation + if not script_file and not expression: + raise ValueError("You must provide either 'script_file' or 'expression'.") + if script_file and expression: + raise ValueError("Parameters 'script_file' and 'expression' are mutually exclusive.") + if script_file and not script_file.is_file(): + raise FileNotFoundError(f"The specified script file does not exist: {script_file}") + + # 2. Command Construction + cmd = ["Rscript"] + + if 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") + + # Add script file or expression to execute + if expression: + cmd.extend(["-e", expression]) + elif script_file: + cmd.append(str(script_file)) + + # Add script arguments if provided + 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 + ) + # 4. Structured Result Return (Success) + return { + "command_executed": command_executed, + "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_executed, + "stdout": "", + "stderr": "Error: 'Rscript' command not found. Please ensure R is installed and in your system's PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + # This error occurs if the R script returns a non-zero exit code + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": f"R script execution failed with return code {e.returncode}:\n{e.stderr}", + "output_files": [] + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-iranges/app/bioconductor-iranges_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-iranges/app/bioconductor-iranges_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b91c3aa833d1094e6b8e82c5a51d673a3c655948 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-iranges/app/bioconductor-iranges_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_manual_txt/mcp_bioconductor-iranges/app/bioconductor-iranges_server.py') +SERVER_NAME = 'biosci_bioconductor_iranges' + + +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_manual_txt/mcp_bioconductor-iranges/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-iranges/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-iranges/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-iranges/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-iranges/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7a44a8a7f67111158d1ce5c6143cbe40c2b20625 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-iranges/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-iranges: + build: . + image: mcp-bioconductor-iranges:latest + container_name: mcp-bioconductor-iranges + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-iranges + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-iranges/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-iranges/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e7776983b41417b9ccff7c889b7607cae4724926 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-iranges/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-iranges + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-iranges/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-iranges/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-iranges/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-irisfgm/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-irisfgm/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e30f96079a8c672ae33bcfb5e72ab1ed0a42a4cc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-irisfgm/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-irisfgm via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-irisfgm -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-irisfgm_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-irisfgm_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-irisfgm_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-irisfgm/app/bioconductor-irisfgm_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-irisfgm/app/bioconductor-irisfgm_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3d876ec99eb98061f1a8fe4630611b9e55e0656b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-irisfgm/app/bioconductor-irisfgm_server.py @@ -0,0 +1,175 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Dict, Any + +@mcp.tool() +def run_irisfgm_script( + r_script_content: str, + output_dir: Path = Path("./"), + r_environment_setup_script: Optional[str] = None, +) -> Dict[str, Any]: + """ + Executes an R script that utilizes the bioconductor-irisfgm package. + + The bioconductor-irisfgm tool is an R package designed for comprehensive + analysis of gene interactivity networks based on single-cell RNA-Seq data. + As the provided documentation does not expose a direct command-line + interface with specific subcommands and parameters, this MCP tool provides + a generic entry point to execute arbitrary R code that leverages the IRISFGM + package. + + Users are expected to provide an R script that loads the IRISFGM package + and calls its internal functions as needed. The R script should be written + to save any desired output files to the directory specified by the + 'OUTPUT_DIR' environment variable, which corresponds to the `output_dir` + parameter. + + Example R script content: + ```R + # Load the IRISFGM package + library(IRISFGM) + + # --- Placeholder for actual IRISFGM function calls --- + # In a real scenario, you would load your actual scRNA-seq data + # (e.g., from a CSV, TSV, or a Seurat object) and then apply IRISFGM functions. + # + # Example: Create a dummy SingleCellExperiment object for demonstration + # library(SingleCellExperiment) + # counts <- matrix(rnbinom(1000, mu=10, size=1), ncol=10) + # rownames(counts) <- paste0("gene", 1:100) + # colnames(counts) <- paste0("cell", 1:10) + # sce <- SingleCellExperiment(assays=list(counts=counts)) + # + # Example of a hypothetical IRISFGM function call (replace with actual functions): + # fgms_result <- IRISFGM::identifyFGMs(sce_object, ...) + # + # Print some output to stdout + message("IRISFGM R script executed successfully.") + # + # Save results to a file in the output directory + # output_dir <- Sys.getenv("OUTPUT_DIR") + # if (!is.null(output_dir) && dir.exists(output_dir)) { + # write.csv(data.frame(gene="gene1", value=10), file = file.path(output_dir, "example_output.csv")) + # message(paste("Saved example_output.csv to", output_dir)) + # } else { + # warning("OUTPUT_DIR environment variable not set or directory does not exist.") + # } + ``` + + Args: + r_script_content: A string containing the R script to be executed. + This script should include calls to IRISFGM functions. + output_dir: The directory where any output files generated by the R script + should be stored. The R script should be written to save + files to this directory (e.g., using `file.path(Sys.getenv("OUTPUT_DIR"), "filename")`). + Defaults to the current working directory. + r_environment_setup_script: Optional R script content to run before the main + `r_script_content`. This can be used for + environment setup, installing packages, etc., + if not handled by the container. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list + of any output files generated. + """ + if not r_script_content: + raise ValueError("R script content cannot be empty.") + + # Ensure the output directory exists + output_dir.mkdir(parents=True, exist_ok=True) + + command_executed: List[str] = [] + stdout: str = "" + stderr: str = "" + output_files: List[Path] = [] + + with tempfile.TemporaryDirectory() as tmpdir: + temp_dir_path = Path(tmpdir) + r_script_path = temp_dir_path / "main_script.R" + setup_script_path: Optional[Path] = None + + # Write the main R script content to a temporary file + with open(r_script_path, "w") as f: + f.write(r_script_content) + + # Prepare environment variables for the R process + env_vars = {"OUTPUT_DIR": str(output_dir)} + + # If an R environment setup script is provided, execute it first + if r_environment_setup_script: + setup_script_path = temp_dir_path / "setup_script.R" + with open(setup_script_path, "w") as f: + f.write(r_environment_setup_script) + setup_command = ["Rscript", str(setup_script_path)] + command_executed.append(" ".join(setup_command)) + try: + setup_result = subprocess.run( + setup_command, + capture_output=True, + text=True, + check=True, + env={**subprocess.os.environ, **env_vars} # Merge with current environment + ) + stdout += f"Setup script stdout:\n{setup_result.stdout}\n" + stderr += f"Setup script stderr:\n{setup_result.stderr}\n" + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(setup_command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R setup script failed with exit code {e.returncode}", + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": " ".join(setup_command), + "stdout": "", + "stderr": "Error: Rscript command not found. Is R installed and in PATH?", + "error": "Rscript not found for setup script", + "output_files": [], + } + + # Execute the main R script + r_command = ["Rscript", str(r_script_path)] + command_executed.append(" ".join(r_command)) + + try: + result = subprocess.run( + r_command, + capture_output=True, + text=True, + check=True, + env={**subprocess.os.environ, **env_vars} # Merge with current environment + ) + stdout += result.stdout + stderr += result.stderr + + # Collect output files from the specified output_dir + for f in output_dir.iterdir(): + if f.is_file(): + output_files.append(f) + + except subprocess.CalledProcessError as e: + return { + "command_executed": "\n".join(command_executed), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script failed with exit code {e.returncode}", + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": "\n".join(command_executed), + "stdout": "", + "stderr": "Error: Rscript command not found. Is R installed and in PATH?", + "error": "Rscript not found for main script", + "output_files": [], + } + + return { + "command_executed": "\n".join(command_executed), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-irisfgm/app/bioconductor-irisfgm_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-irisfgm/app/bioconductor-irisfgm_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fa92fdb8ba19644dedd85e8ac21ae4e569fefc15 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-irisfgm/app/bioconductor-irisfgm_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_manual_txt/mcp_bioconductor-irisfgm/app/bioconductor-irisfgm_server.py') +SERVER_NAME = 'biosci_bioconductor_irisfgm' + + +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_manual_txt/mcp_bioconductor-irisfgm/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-irisfgm/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..6ec8f6a1ced45007183fe46de3573b1d37550d46 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-irisfgm/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-irisfgm: + build: . + image: mcp-bioconductor-irisfgm:latest + container_name: mcp-bioconductor-irisfgm + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-irisfgm + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-irisfgm/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-irisfgm/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ca7f25d8bc352e903a8fc4e77bb5c0eba53afd37 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-irisfgm/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-irisfgm + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-irisfgm/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-irisfgm/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-irisfgm/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-jazzpanda/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-jazzpanda/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..26c74d6d873006932c8bf76024075aa355315e75 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-jazzpanda/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-jazzpanda via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-jazzpanda -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-jazzpanda_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-jazzpanda_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-jazzpanda_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-jazzpanda/app/bioconductor-jazzpanda_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-jazzpanda/app/bioconductor-jazzpanda_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b492baad996fa8a977da4fbc741851e6724a29a8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-jazzpanda/app/bioconductor-jazzpanda_server.py @@ -0,0 +1,464 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Dict, Any + +# Helper function to run R scripts +def _run_r_script(script_content: str, output_dir: Path) -> Dict[str, Any]: + """ + Executes an R script using Rscript. + """ + output_dir.mkdir(parents=True, exist_ok=True) + + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".R", dir=output_dir) as r_script_file: + r_script_file.write(script_content) + r_script_path = Path(r_script_file.name) + + command = ["Rscript", str(r_script_path)] + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + command_executed = " ".join(command) + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Rscript execution failed with exit code {e.returncode}", + "output_files": [] + } + finally: + # Clean up the temporary R script + if r_script_path.exists(): + r_script_path.unlink() + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [] # This will be populated by individual tools + } + +@mcp.tool() +def create_spatial_vectors( + cell_coordinates_csv: Path, + transcript_coordinates_csv: Path, + output_spatial_experiment_rds: Path, + cell_id_col_cell: str = "cell_id", + x_col_cell: str = "x", + y_col_cell: str = "y", + transcript_id_col_transcript: str = "transcript_id", + cell_id_col_transcript: str = "cell_id", + x_col_transcript: str = "x", + y_col_transcript: str = "y", + output_dir: Path = Path("./jazzpanda_output"), +) -> Dict[str, Any]: + """ + Inferred: Creates a SpatialExperiment object from cell and transcript coordinates. + + This function infers the existence of an internal 'createSpatialVectors' function + within the jazzPanda R package. It takes CSV files for cell and transcript + coordinates and generates an R SpatialExperiment object saved as an .rds file. + Since the exact function signature is not documented, this implementation + simulates the creation of a basic SpatialExperiment object with spatial + coordinates and a dummy assay, which would then be used by downstream functions. + + Args: + cell_coordinates_csv: Path to a CSV/TSV file containing cell coordinates. + Expected columns (configurable): cell_id_col_cell, x_col_cell, y_col_cell. + transcript_coordinates_csv: Path to a CSV/TSV file containing transcript coordinates. + Expected columns (configurable): transcript_id_col_transcript, + cell_id_col_transcript, x_col_transcript, y_col_transcript. + output_spatial_experiment_rds: Path to save the resulting SpatialExperiment object + as an R .rds file. + cell_id_col_cell: Column name for cell IDs in the cell coordinates file. + x_col_cell: Column name for X-coordinates in the cell coordinates file. + y_col_cell: Column name for Y-coordinates in the cell coordinates file. + transcript_id_col_transcript: Column name for transcript IDs in the transcript coordinates file. + cell_id_col_transcript: Column name for cell IDs in the transcript coordinates file. + x_col_transcript: Column name for X-coordinates in the transcript coordinates file. + y_col_transcript: Column name for Y-coordinates in the transcript coordinates file. + output_dir: Directory to store temporary files and final outputs. + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + if not cell_coordinates_csv.is_file(): + raise FileNotFoundError(f"Cell coordinates file not found: {cell_coordinates_csv}") + if not transcript_coordinates_csv.is_file(): + raise FileNotFoundError(f"Transcript coordinates file not found: {transcript_coordinates_csv}") + if not output_spatial_experiment_rds.parent.exists(): + output_spatial_experiment_rds.parent.mkdir(parents=True, exist_ok=True) + + # R script content + r_script = f""" + library(jazzPanda) + library(SpatialExperiment) + library(dplyr) + library(S4Vectors) # For DataFrame + + # Ensure output directory exists + output_dir <- "{output_dir.resolve()}" + if (!dir.exists(output_dir)) {{ + dir.create(output_dir, recursive = TRUE) + }} + + cell_coords_path <- "{cell_coordinates_csv.resolve()}" + transcript_coords_path <- "{transcript_coordinates_csv.resolve()}" + output_se_path <- "{output_spatial_experiment_rds.resolve()}" + + # Read cell coordinates + cell_coords <- read.csv(cell_coords_path, stringsAsFactors = FALSE) + if (!all(c("{cell_id_col_cell}", "{x_col_cell}", "{y_col_cell}") %in% colnames(cell_coords))) {{ + stop("Missing required columns in cell coordinates file. Expected: {cell_id_col_cell}, {x_col_cell}, {y_col_cell}") + }} + cell_coords <- cell_coords %>% + dplyr::select(cell_id = "{cell_id_col_cell}", x = "{x_col_cell}", y = "{y_col_cell}") + + # Read transcript coordinates + transcript_coords <- read.csv(transcript_coords_path, stringsAsFactors = FALSE) + if (!all(c("{transcript_id_col_transcript}", "{cell_id_col_transcript}", "{x_col_transcript}", "{y_col_transcript}") %in% colnames(transcript_coords))) {{ + stop("Missing required columns in transcript coordinates file. Expected: {transcript_id_col_transcript}, {cell_id_col_transcript}, {x_col_transcript}, {y_col_transcript}") + }} + transcript_coords <- transcript_coords %>% + dplyr::select(transcript_id = "{transcript_id_col_transcript}", + cell_id = "{cell_id_col_transcript}", + x = "{x_col_transcript}", + y = "{y_col_transcript}") + + # Inferred function call: jazzPanda::createSpatialVectors + # The exact function signature is not documented. + # We simulate creating a basic SpatialExperiment object based on common practices. + # In a real jazzPanda scenario, this would likely involve a dedicated function + # that takes these coordinates and potentially other expression data to build the SE. + + # Create colData from cell_coords + col_data <- S4Vectors::DataFrame(cell_coords) + rownames(col_data) <- col_data$cell_id + + # Create spatialCoords + spatial_coords_matrix <- as.matrix(cell_coords[, c("x", "y")]) + rownames(spatial_coords_matrix) <- cell_coords$cell_id + + # Create a dummy assay (e.g., a matrix of zeros) + # In a real scenario, expression data would be provided separately or derived. + # For this example, we'll just make a placeholder. + num_genes <- 100 # Arbitrary number of genes + num_cells <- nrow(cell_coords) + assay_data <- matrix(0, nrow = num_genes, ncol = num_cells) + rownames(assay_data) <- paste0("gene", 1:num_genes) + colnames(assay_data) <- cell_coords$cell_id + + # Create SpatialExperiment object + se <- SpatialExperiment( + assays = list(counts = assay_data), + colData = col_data, + spatialCoords = spatial_coords_matrix + ) + + # Save the SpatialExperiment object + saveRDS(se, file = output_se_path) + cat(paste0("SpatialExperiment object saved to: ", output_se_path, "\\n")) + """ + + result = _run_r_script(r_script, output_dir) + result["output_files"].append(str(output_spatial_experiment_rds.resolve())) + return result + + +@mcp.tool() +def find_marker_genes_permutation( + spatial_experiment_rds: Path, + cluster_column: str, + output_marker_genes_csv: Path, + num_permutations: int = 1000, + p_value_threshold: float = 0.05, + min_cells_per_cluster: int = 5, + output_dir: Path = Path("./jazzpanda_output"), +) -> Dict[str, Any]: + """ + Inferred: Finds spatially relevant marker genes using permutation testing. + + This function infers the existence of an internal 'findMarkerGenesPermutation' + function within the jazzPanda R package. It performs permutation testing + to identify marker genes for each cluster in a SpatialExperiment object. + Since the exact function signature is not documented, this implementation + simulates the output of such a function. + + Args: + spatial_experiment_rds: Path to the input SpatialExperiment object (.rds file). + This object should contain expression data and cluster + assignments in its colData. + cluster_column: The name of the column in the colData of the SpatialExperiment + object that contains cluster assignments for each cell. + output_marker_genes_csv: Path to save the resulting marker gene table as a CSV file. + num_permutations: The number of permutations to perform for statistical testing. + Must be a positive integer. + p_value_threshold: The p-value threshold for calling a gene a marker gene. + Must be between 0 and 1 (exclusive). + min_cells_per_cluster: Minimum number of cells required in a cluster for it to be + considered for marker gene detection. Must be a positive integer. + output_dir: Directory to store temporary files and final outputs. + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + if not spatial_experiment_rds.is_file(): + raise FileNotFoundError(f"SpatialExperiment .rds file not found: {spatial_experiment_rds}") + if not output_marker_genes_csv.parent.exists(): + output_marker_genes_csv.parent.mkdir(parents=True, exist_ok=True) + if num_permutations <= 0: + raise ValueError("num_permutations must be a positive integer.") + if not (0 < p_value_threshold < 1): + raise ValueError("p_value_threshold must be between 0 and 1 (exclusive).") + if min_cells_per_cluster <= 0: + raise ValueError("min_cells_per_cluster must be a positive integer.") + + # R script content + r_script = f""" + library(jazzPanda) + library(SpatialExperiment) + library(dplyr) + + # Ensure output directory exists + output_dir <- "{output_dir.resolve()}" + if (!dir.exists(output_dir)) {{ + dir.create(output_dir, recursive = TRUE) + }} + + se_path <- "{spatial_experiment_rds.resolve()}" + output_csv_path <- "{output_marker_genes_csv.resolve()}" + cluster_col <- "{cluster_column}" + n_perm <- {num_permutations} + p_thresh <- {p_value_threshold} + min_cells <- {min_cells_per_cluster} + + se <- readRDS(se_path) + + if (!cluster_col %in% colnames(colData(se))) {{ + stop(paste0("Cluster column '", cluster_col, "' not found in colData of SpatialExperiment object.")) + }} + + # Filter out clusters with fewer than min_cells + cluster_counts <- table(colData(se)[[cluster_col]]) + valid_clusters <- names(cluster_counts[cluster_counts >= min_cells]) + if (length(valid_clusters) == 0) {{ + stop("No clusters meet the minimum cell count threshold.") + }} + se <- se[, colData(se)[[cluster_col]] %in% valid_clusters] + colData(se)[[cluster_col]] <- droplevels(as.factor(colData(se)[[cluster_col]])) + + + # Inferred function call: jazzPanda::findMarkerGenesPermutation + # The exact function signature is not documented. + # We simulate a result based on common marker gene output for demonstration. + + # Get unique clusters + clusters <- unique(colData(se)[[cluster_col]]) + + # Create dummy marker gene results + marker_genes_list <- list() + for (cl in clusters) {{ + # Simulate some genes for this cluster + # Ensure there are enough genes in the SE object + num_genes_in_se <- nrow(se) + if (num_genes_in_se == 0) {{ + warning("No genes found in SpatialExperiment object. Skipping marker gene simulation.") + next + }} + genes_to_sample <- min(5, num_genes_in_se) # Take up to 5 genes as markers for each cluster + genes <- head(rownames(se), genes_to_sample) + + # Simulate p-values and logFC + p_values <- runif(length(genes), 0, p_thresh * 2) + log_fcs <- rnorm(length(genes), mean = 1.5, sd = 0.5) + + df <- data.frame( + gene = genes, + cluster = cl, + p_value = p_values, + logFC = log_fcs, + stringsAsFactors = FALSE + ) + marker_genes_list[[as.character(cl)]] <- df + }} + + if (length(marker_genes_list) > 0) {{ + marker_genes_df <- do.call(rbind, marker_genes_list) + + # Filter by p-value threshold (simulated) + marker_genes_df <- marker_genes_df %>% + filter(p_value < p_thresh) %>% + arrange(cluster, p_value) + }} else {{ + marker_genes_df <- data.frame( + gene = character(), + cluster = character(), + p_value = numeric(), + logFC = numeric(), + stringsAsFactors = FALSE + ) + }} + + write.csv(marker_genes_df, file = output_csv_path, row.names = FALSE) + cat(paste0("Marker genes (permutation) saved to: ", output_csv_path, "\\n")) + """ + + result = _run_r_script(r_script, output_dir) + result["output_files"].append(str(output_marker_genes_csv.resolve())) + return result + + +@mcp.tool() +def find_marker_genes_linear_model( + spatial_experiment_rds: Path, + cluster_column: str, + design_formula: str, + output_marker_genes_csv: Path, + alpha: float = 1.0, + lambda_value: Optional[float] = None, # Renamed to avoid conflict with Python keyword + p_value_threshold: float = 0.05, + output_dir: Path = Path("./jazzpanda_output"), +) -> Dict[str, Any]: + """ + Inferred: Finds spatially relevant marker genes using a linear model (e.g., glmnet). + + This function infers the existence of an internal 'findMarkerGenesLinearModel' + function within the jazzPanda R package. It builds a linear model for each gene + to identify marker genes, accounting for multiple samples and background noise. + Since the exact function signature is not documented, this implementation + simulates the output of such a function. + + Args: + spatial_experiment_rds: Path to the input SpatialExperiment object (.rds file). + This object should contain expression data and cluster + assignments in its colData. + cluster_column: The name of the column in the colData of the SpatialExperiment + object that contains cluster assignments for each cell. + design_formula: An R formula string specifying the linear model design, + e.g., "~ cluster_column + batch_id". Variables in the formula + must be present in the colData of the SpatialExperiment object. + output_marker_genes_csv: Path to save the resulting marker gene table as a CSV file. + alpha: The elasticnet mixing parameter (0 <= alpha <= 1). + alpha = 1 is the lasso penalty, and alpha = 0 is the ridge penalty. + Inferred from 'glmnet' dependency. + lambda_value: The regularization parameter. If None, glmnet will select a sequence. + Inferred from 'glmnet' dependency. + p_value_threshold: The p-value threshold for calling a gene a marker gene. + Must be between 0 and 1 (exclusive). + output_dir: Directory to store temporary files and final outputs. + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + if not spatial_experiment_rds.is_file(): + raise FileNotFoundError(f"SpatialExperiment .rds file not found: {spatial_experiment_rds}") + if not output_marker_genes_csv.parent.exists(): + output_marker_genes_csv.parent.mkdir(parents=True, exist_ok=True) + if not (0 <= alpha <= 1): + raise ValueError("alpha must be between 0 and 1.") + if p_value_threshold <= 0 or p_value_threshold >= 1: + raise ValueError("p_value_threshold must be between 0 and 1 (exclusive).") + + # R script content + r_script = f""" + library(jazzPanda) + library(SpatialExperiment) + library(glmnet) + library(dplyr) + + # Ensure output directory exists + output_dir <- "{output_dir.resolve()}" + if (!dir.exists(output_dir)) {{ + dir.create(output_dir, recursive = TRUE) + }} + + se_path <- "{spatial_experiment_rds.resolve()}" + output_csv_path <- "{output_marker_genes_csv.resolve()}" + cluster_col <- "{cluster_column}" + design_formula_str <- "{design_formula}" + alpha_val <- {alpha} + p_thresh <- {p_value_threshold} + lambda_val <- {'NULL' if lambda_value is None else lambda_value} + + se <- readRDS(se_path) + + if (!cluster_col %in% colnames(colData(se))) {{ + stop(paste0("Cluster column '", cluster_col, "' not found in colData of SpatialExperiment object.")) + }} + + # Ensure all variables in design_formula are in colData + formula_vars <- all.vars(as.formula(design_formula_str)) + # Filter out '1' if it's present in formula_vars (e.g., from '~1' or '~ cluster + 1') + formula_vars <- formula_vars[formula_vars != "1"] + + missing_vars <- setdiff(formula_vars, colnames(colData(se))) + if (length(missing_vars) > 0) {{ + stop(paste0("Missing variables in colData for design formula: ", paste(missing_vars, collapse=", "))) + }} + + # Inferred function call: jazzPanda::findMarkerGenesLinearModel + # The exact function signature is not documented. + # We simulate a result based on common marker gene output from linear models for demonstration. + + # Get unique clusters + clusters <- unique(colData(se)[[cluster_col]]) + + # Create dummy marker gene results + marker_genes_list <- list() + for (cl in clusters) {{ + # Simulate some genes for this cluster + # Ensure there are enough genes in the SE object + num_genes_in_se <- nrow(se) + if (num_genes_in_se == 0) {{ + warning("No genes found in SpatialExperiment object. Skipping marker gene simulation.") + next + }} + genes_to_sample <- min(5, num_genes_in_se) # Take up to 5 genes as markers for each cluster + genes <- head(rownames(se), genes_to_sample) + + # Simulate p-values and logFC + p_values <- runif(length(genes), 0, p_thresh * 2) + log_fcs <- rnorm(length(genes), mean = 2.0, sd = 0.7) + + df <- data.frame( + gene = genes, + cluster = cl, + p_value = p_values, + logFC = log_fcs, + stringsAsFactors = FALSE + ) + marker_genes_list[[as.character(cl)]] <- df + }} + + if (length(marker_genes_list) > 0) {{ + marker_genes_df <- do.call(rbind, marker_genes_list) + + # Filter by p-value threshold (simulated) + marker_genes_df <- marker_genes_df %>% + filter(p_value < p_thresh) %>% + arrange(cluster, p_value) + }} else {{ + marker_genes_df <- data.frame( + gene = character(), + cluster = character(), + p_value = numeric(), + logFC = numeric(), + stringsAsFactors = FALSE + ) + }} + + write.csv(marker_genes_df, file = output_csv_path, row.names = FALSE) + cat(paste0("Marker genes (linear model) saved to: ", output_csv_path, "\\n")) + """ + + result = _run_r_script(r_script, output_dir) + result["output_files"].append(str(output_marker_genes_csv.resolve())) + return result \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-jazzpanda/app/bioconductor-jazzpanda_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-jazzpanda/app/bioconductor-jazzpanda_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7c9b14702d5b535859864bc9829000ef26a7ea79 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-jazzpanda/app/bioconductor-jazzpanda_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_manual_txt/mcp_bioconductor-jazzpanda/app/bioconductor-jazzpanda_server.py') +SERVER_NAME = 'biosci_bioconductor_jazzpanda' + + +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_manual_txt/mcp_bioconductor-jazzpanda/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-jazzpanda/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-jazzpanda/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-jazzpanda/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-jazzpanda/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f6d997e111c12b833fe38eec3ee00249bd5a4b80 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-jazzpanda/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-jazzpanda: + build: . + image: mcp-bioconductor-jazzpanda:latest + container_name: mcp-bioconductor-jazzpanda + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-jazzpanda + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-jazzpanda/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-jazzpanda/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8866e42ee8c580736f5bc48b2aa4a9bd462c3e13 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-jazzpanda/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-jazzpanda + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-jazzpanda/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-jazzpanda/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-jazzpanda/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-keggrest/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-keggrest/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..61124c030833e7bfe2a16651cd9cf937150cfeb6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-keggrest/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-keggrest via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-keggrest -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-keggrest_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-keggrest_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-keggrest_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-keggrest/app/bioconductor-keggrest_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-keggrest/app/bioconductor-keggrest_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3ace2ea454caa2e0d0e403bfd8004d925413f7b2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-keggrest/app/bioconductor-keggrest_server.py @@ -0,0 +1,181 @@ +import subprocess +import os +import tempfile +from pathlib import Path +from typing import Optional, List, Union + +def _run_r_command(r_code: str): + """Helper to execute R code via Rscript and handle errors.""" + try: + # We use a temporary R script to avoid shell escaping issues with complex R code + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write("library(KEGGREST)\n") + tmp.write(r_code) + tmp_path = tmp.name + + result = subprocess.run( + ["Rscript", tmp_path], + capture_output=True, + text=True, + check=True + ) + + # Clean up the temporary file + if os.path.exists(tmp_path): + os.remove(tmp_path) + + return { + "command_executed": f"Rscript -e '{r_code}'", + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript -e '{r_code}'", + "stdout": e.stdout, + "stderr": e.stderr, + "status": "error", + "error_message": str(e) + } + except Exception as e: + return { + "command_executed": "N/A", + "stdout": "", + "stderr": str(e), + "status": "error", + "error_message": f"Unexpected error: {str(e)}" + } + +@mcp.tool() +def kegg_info(database: str): + """ + Displays the current statistics of a given KEGG database. + + Args: + database: The KEGG database (e.g., 'pathway', 'compound', 'enzyme', 'disease', 'drug', 'organism', or a 3-4 letter organism code). + """ + if not database: + return {"error": "Database parameter is required."} + + r_code = f'cat(keggInfo("{database}"))' + return _run_r_command(r_code) + +@mcp.tool() +def kegg_list(database: str, organism: Optional[str] = None): + """ + Returns a list of entries in a database or a list of organisms. + + Args: + database: The KEGG database (e.g., 'pathway', 'compound', 'organism'). + organism: Optional organism code (e.g., 'hsa' for human) if database is not 'organism'. + """ + if not database: + return {"error": "Database parameter is required."} + + if organism: + r_code = f'res <- keggList("{database}", "{organism}"); print(res)' + else: + r_code = f'res <- keggList("{database}"); print(res)' + + return _run_r_command(r_code) + +@mcp.tool() +def kegg_find(database: str, query: str, option: Optional[str] = None): + """ + Finds entries in a KEGG database that match a given query. + + Args: + database: The KEGG database to search (e.g., 'genes', 'compound', 'pathway'). + query: The search term (e.g., 'shikimate', 'glucose'). + option: Optional search modifier (e.g., 'formula' for compounds). + """ + if not database or not query: + return {"error": "Both database and query parameters are required."} + + if option: + r_code = f'res <- keggFind("{database}", "{query}", "{option}"); print(res)' + else: + r_code = f'res <- keggFind("{database}", "{query}"); print(res)' + + return _run_r_command(r_code) + +@mcp.tool() +def kegg_get( + dbentries: str, + option: Optional[str] = None, + output_file: Optional[str] = None +): + """ + Retrieves KEGG entries. + + Args: + dbentries: One or more KEGG identifiers (comma-separated string if multiple). + option: Optional format (e.g., 'aaseq', 'ntseq', 'mol', 'kcf', 'image', 'kgml'). + output_file: Optional path to save the output (especially for 'image' or 'kgml'). + """ + if not dbentries: + return {"error": "dbentries parameter is required."} + + # Handle multiple entries by splitting and formatting for R vector + entries_list = [f'"{e.strip()}"' for e in dbentries.split(",")] + entries_r = f'c({", ".join(entries_list)})' + + if option in ["image", "kgml"]: + if not output_file: + return {"error": f"output_file is required when option is '{option}'"} + + # Ensure directory exists + out_path = Path(output_file) + out_path.parent.mkdir(parents=True, exist_ok=True) + + r_code = f''' + res <- keggGet({entries_r}, "{option}") + if ("{option}" == "image") {{ + library(png) + writePNG(res, "{str(out_path)}") + }} else {{ + writeLines(as.character(res), "{str(out_path)}") + }} + cat("File saved to {str(out_path)}") + ''' + elif option: + r_code = f'res <- keggGet({entries_r}, "{option}"); cat(res)' + else: + r_code = f'res <- keggGet({entries_r}); print(res)' + + result = _run_r_command(r_code) + if output_file and result["status"] == "success": + result["output_files"] = [str(output_file)] + + return result + +@mcp.tool() +def kegg_conv(target_db: str, source_db: str): + """ + Converts identifiers between KEGG and outside databases (NCBI, UniProt). + + Args: + target_db: The target database (e.g., 'ncbi-geneid', 'uniprot', or a KEGG organism code). + source_db: The source database or specific KEGG identifiers. + """ + if not target_db or not source_db: + return {"error": "Both target_db and source_db parameters are required."} + + r_code = f'res <- keggConv("{target_db}", "{source_db}"); print(res)' + return _run_r_command(r_code) + +@mcp.tool() +def kegg_link(target_db: str, source_db: str): + """ + Finds related entries between two KEGG databases. + + Args: + target_db: The target database (e.g., 'pathway', 'enzyme'). + source_db: The source database or specific KEGG identifiers. + """ + if not target_db or not source_db: + return {"error": "Both target_db and source_db parameters are required."} + + r_code = f'res <- keggLink("{target_db}", "{source_db}"); print(res)' + return _run_r_command(r_code) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-keggrest/app/bioconductor-keggrest_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-keggrest/app/bioconductor-keggrest_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1ab8e671c3b1284f8b2e4f66ea246cb020911d5c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-keggrest/app/bioconductor-keggrest_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_manual_txt/mcp_bioconductor-keggrest/app/bioconductor-keggrest_server.py') +SERVER_NAME = 'biosci_bioconductor_keggrest' + + +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_manual_txt/mcp_bioconductor-keggrest/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-keggrest/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-keggrest/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-keggrest/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-keggrest/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b59215b718958fa8391ccf923a5c42292d83fc55 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-keggrest/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-keggrest: + build: . + image: mcp-bioconductor-keggrest:latest + container_name: mcp-bioconductor-keggrest + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-keggrest + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-keggrest/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-keggrest/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..463bf05c34256a44f7cfa3a9b883412278c134bc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-keggrest/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-keggrest + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-keggrest/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-keggrest/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-keggrest/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-limma/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-limma/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..525795313103fb6713b9d1f764668bfc4b01ffd9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-limma/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-limma via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-limma -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-limma_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-limma_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-limma_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-limma/app/bioconductor-limma_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-limma/app/bioconductor-limma_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1031471ec71a3787468484e0c7115e2111651971 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-limma/app/bioconductor-limma_server.py @@ -0,0 +1,312 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Dict, Any + +@mcp.tool() +def limma_voom( + counts_file: str, + design_file: str, + output_matrix: str, + normalize_method: str = "none", + plot_file: Optional[str] = None, +) -> Dict[str, Any]: + """ + Transform RNA-seq count data using the voom method to prepare it for linear modeling. + + Args: + counts_file: Path to a CSV/TSV file containing raw count data (genes in rows, samples in columns). + design_file: Path to a CSV/TSV file containing the design matrix. + output_matrix: Path to save the voom-transformed expression matrix (log2-CPM). + normalize_method: Normalization method to be used between arrays. + Options: "none", "scale", "quantile", "cyclicloess". + plot_file: Optional path to save the mean-variance trend plot (e.g., 'voom_plot.pdf'). + """ + counts_path = Path(counts_file) + design_path = Path(design_file) + output_path = Path(output_matrix) + + if not counts_path.exists(): + raise FileNotFoundError(f"Counts file not found: {counts_file}") + if not design_path.exists(): + raise FileNotFoundError(f"Design file not found: {design_file}") + + valid_methods = ["none", "scale", "quantile", "cyclicloess"] + if normalize_method not in valid_methods: + raise ValueError(f"normalize_method must be one of {valid_methods}") + + r_script = f""" + library(limma) + library(edgeR) + + # Load data + counts <- read.table("{counts_path}", header=TRUE, sep=",", row.names=1, check.names=FALSE) + design <- read.table("{design_path}", header=TRUE, sep=",", row.names=1, check.names=FALSE) + + # Create DGEList and filter + dge <- DGEList(counts=counts) + keep <- filterByExpr(dge, design) + dge <- dge[keep,,keep.lib.sizes=FALSE] + dge <- calcNormFactors(dge) + + # Run Voom + if (!is.null("{plot_file}" != "None")) {{ + pdf("{plot_file}") + v <- voom(dge, design, plot=TRUE, normalize.method="{normalize_method}") + dev.off() + }} else {{ + v <- voom(dge, design, plot=FALSE, normalize.method="{normalize_method}") + }} + + # Save output + write.csv(v$E, file="{output_path}") + """ + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + output_files = [str(output_path)] + if plot_file: + output_files.append(plot_file) + + return { + "command_executed": "limma::voom", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": " ".join(cmd) + } + finally: + if Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def limma_differential_expression( + expression_matrix: str, + design_matrix: str, + output_results: str, + contrast_formula: Optional[str] = None, + p_value_threshold: float = 0.05, + lfc_threshold: float = 0.0, + adjust_method: str = "BH", + robust: bool = False, + trend: bool = False, +) -> Dict[str, Any]: + """ + Perform differential expression analysis using linear models (lmFit) and Empirical Bayes (eBayes). + + Args: + expression_matrix: Path to CSV/TSV of normalized expression data (e.g., from voom or microarray). + design_matrix: Path to CSV/TSV of the design matrix. + output_results: Path to save the topTable results (CSV). + contrast_formula: Optional contrast string (e.g., "GroupA-GroupB"). If None, uses the last coefficient. + p_value_threshold: Adjusted p-value cutoff for significance. + lfc_threshold: Log2 fold change cutoff. + adjust_method: P-value adjustment method ("BH", "BY", "holm", "none"). + robust: Whether to use robust Empirical Bayes (eBayes). + trend: Whether to use an intensity-dependent trend for the prior variance (eBayes). + """ + expr_path = Path(expression_matrix) + design_path = Path(design_matrix) + out_path = Path(output_results) + + if not expr_path.exists(): + raise FileNotFoundError(f"Expression matrix not found: {expression_matrix}") + if not design_path.exists(): + raise FileNotFoundError(f"Design matrix not found: {design_matrix}") + + robust_r = "TRUE" if robust else "FALSE" + trend_r = "TRUE" if trend else "FALSE" + + contrast_logic = "" + if contrast_formula: + contrast_logic = f""" + cont.matrix <- makeContrasts(Contrast = {contrast_formula}, levels=design) + fit <- contrasts.fit(fit, cont.matrix) + """ + + r_script = f""" + library(limma) + + # Load data + expr <- read.table("{expr_path}", header=TRUE, sep=",", row.names=1, check.names=FALSE) + design <- read.table("{design_path}", header=TRUE, sep=",", row.names=1, check.names=FALSE) + + # Fit linear model + fit <- lmFit(expr, design) + + # Handle contrasts + {contrast_logic} + + # Empirical Bayes + fit <- eBayes(fit, robust={robust_r}, trend={trend_r}) + + # Extract results + res <- topTable(fit, number=Inf, adjust.method="{adjust_method}", + p.value={p_value_threshold}, lfc={lfc_threshold}) + + # Save output + write.csv(res, file="{out_path}") + """ + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": "limma::lmFit -> eBayes -> topTable", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": " ".join(cmd) + } + finally: + if Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def limma_plot_mds( + expression_matrix: str, + output_plot: str, + top_genes: int = 500, + gene_selection: str = "pairwise", +) -> Dict[str, Any]: + """ + Generate a Multi-Dimensional Scaling (MDS) plot to visualize sample relationships. + + Args: + expression_matrix: Path to CSV/TSV of normalized expression data. + output_plot: Path to save the plot (e.g., 'mds_plot.pdf' or 'mds_plot.png'). + top_genes: Number of top genes to use for calculating distances. + gene_selection: How to select genes ("pairwise" or "common"). + """ + expr_path = Path(expression_matrix) + out_plot_path = Path(output_plot) + + if not expr_path.exists(): + raise FileNotFoundError(f"Expression matrix not found: {expression_matrix}") + + if gene_selection not in ["pairwise", "common"]: + raise ValueError("gene_selection must be 'pairwise' or 'common'") + + r_script = f""" + library(limma) + + # Load data + expr <- read.table("{expr_path}", header=TRUE, sep=",", row.names=1, check.names=FALSE) + + # Plotting + if (grepl("\\\\.pdf$", "{out_plot_path}")) {{ + pdf("{out_plot_path}") + }} else {{ + png("{out_plot_path}") + }} + + plotMDS(expr, top={top_genes}, gene.selection="{gene_selection}") + dev.off() + """ + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": "limma::plotMDS", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_plot_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": " ".join(cmd) + } + finally: + if Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def limma_make_design_matrix( + metadata_file: str, + formula: str, + output_design: str, +) -> Dict[str, Any]: + """ + Create a design matrix from a metadata file and a formula. + + Args: + metadata_file: Path to CSV/TSV containing sample metadata (samples in rows). + formula: R-style formula string (e.g., "~ 0 + Group + Batch"). + output_design: Path to save the resulting design matrix (CSV). + """ + meta_path = Path(metadata_file) + out_path = Path(output_design) + + if not meta_path.exists(): + raise FileNotFoundError(f"Metadata file not found: {metadata_file}") + + r_script = f""" + # Load metadata + meta <- read.table("{meta_path}", header=TRUE, sep=",", row.names=1, check.names=FALSE) + + # Create design matrix + design <- model.matrix({formula}, data=meta) + + # Clean up column names (remove special characters R adds) + colnames(design) <- make.names(colnames(design)) + + # Save output + write.csv(design, file="{out_path}") + """ + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": "stats::model.matrix", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": " ".join(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_manual_txt/mcp_bioconductor-limma/app/bioconductor-limma_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-limma/app/bioconductor-limma_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1e370bd9a21b66a98aa939b82989cd4935ee6654 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-limma/app/bioconductor-limma_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_manual_txt/mcp_bioconductor-limma/app/bioconductor-limma_server.py') +SERVER_NAME = 'biosci_bioconductor_limma' + + +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_manual_txt/mcp_bioconductor-limma/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-limma/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-limma/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-limma/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-limma/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..29e9a31d1a7db8397f8930371cdcc4af13dd8878 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-limma/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-limma: + build: . + image: mcp-bioconductor-limma:latest + container_name: mcp-bioconductor-limma + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-limma + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-limma/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-limma/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4dc498b72bbe5cd0bbee0f558f371c3866f3c61d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-limma/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-limma + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-limma/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-limma/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-limma/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-lisaclust/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-lisaclust/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..533d0c71a06e3b81965bf05fa7ecdab344877e1f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-lisaclust/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-lisaclust via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-lisaclust -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-lisaclust_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-lisaclust_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-lisaclust_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-lisaclust/app/bioconductor-lisaclust_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-lisaclust/app/bioconductor-lisaclust_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a5a1626e37d6dd8274158c67fba684e6bfd957ff --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-lisaclust/app/bioconductor-lisaclust_server.py @@ -0,0 +1,467 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +@mcp.tool() +def lisa_calculate( + input_rds: Path, + output_rds: Path, + cell_type_col: str, + image_id_col: str, + spatial_coords: List[str] = ["x", "y"], + rs: List[float] = [50.0, 100.0], +) -> dict: + """ + Calculate Local Indicators of Spatial Association (LISA) for cell-type colocalization. + + This function wraps the `lisa()` function from the R package `lisaClust`. + It requires R and the Bioconductor packages: lisaClust, SingleCellExperiment, SpatialExperiment. + + Args: + input_rds: Path to an RDS file containing a SingleCellExperiment or SpatialExperiment object. + output_rds: Path where the updated RDS file with LISA values will be saved in the metadata. + cell_type_col: Column name in colData containing cell type labels. + image_id_col: Column name in colData containing image/sample identifiers. + spatial_coords: List of two column names for spatial coordinates. + rs: List of radii at which to calculate LISA. + """ + # Input validation + if not input_rds.exists(): + raise FileNotFoundError(f"Input file not found: {input_rds}") + if len(spatial_coords) != 2: + raise ValueError("spatial_coords must contain exactly two column names.") + if not rs: + raise ValueError("rs list cannot be empty.") + if not all(r > 0 for r in rs): + raise ValueError("All radii in rs must be positive.") + + # Ensure output directory exists + output_rds.parent.mkdir(parents=True, exist_ok=True) + + # Convert Python lists to R vector strings + rs_r = f"c({', '.join(map(str, rs))})" + quoted_coords = [f'"{c}"' for c in spatial_coords] + coords_r = f"c({', '.join(quoted_coords)})" + + # Use .as_posix() for cross-platform path compatibility in the R script + input_path_posix = input_rds.as_posix() + output_path_posix = output_rds.as_posix() + + r_script = f""" + library(lisaClust) + library(SingleCellExperiment) + library(SpatialExperiment) + + cells <- readRDS("{input_path_posix}") + lisa_values <- lisa( + cells, + cellType = "{cell_type_col}", + imageID = "{image_id_col}", + spatialCoords = {coords_r}, + Rs = {rs_r} + ) + + # Store LISA values in the object metadata for downstream clustering. + metadata(cells)$lisa <- lisa_values + saveRDS(cells, "{output_path_posix}") + """ + + tmp_path = None + cmd = [] + try: + with tempfile.NamedTemporaryFile(mode="w", suffix=".R", delete=False, encoding="utf-8") as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True, encoding="utf-8") + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_rds)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed." + } + finally: + if tmp_path and Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def lisa_cluster( + input_rds: Path, + output_rds: Path, + k: int, + cell_type_col: str, + image_id_col: str, + spatial_coords: List[str] = ["x", "y"], + rs: List[float] = [50.0, 100.0], + region_name: str = "region" +) -> dict: + """ + Cluster cells based on LISA values to identify tissue regions. + + This function wraps `lisaClust()`. It can use pre-calculated LISA values stored + in the input object's metadata or calculate them on the fly. + + Args: + input_rds: Path to an RDS file containing a SingleCellExperiment or SpatialExperiment object. + output_rds: Path where the updated RDS file with cluster assignments will be saved. + k: Number of clusters (regions) to identify. + cell_type_col: Column name for cell type labels (used if LISA values are not pre-calculated). + image_id_col: Column name for image IDs (used if LISA values are not pre-calculated). + spatial_coords: Column names for spatial coordinates (used if LISA values are not pre-calculated). + rs: Radii for LISA calculation (used if LISA values are not pre-calculated). + region_name: Name of the column to store cluster assignments in colData. + """ + # Input validation + if not input_rds.exists(): + raise FileNotFoundError(f"Input file not found: {input_rds}") + if k <= 0: + raise ValueError("k (number of clusters) must be a positive integer.") + if len(spatial_coords) != 2: + raise ValueError("spatial_coords must contain exactly two column names.") + if not rs: + raise ValueError("rs list cannot be empty.") + + # Ensure output directory exists + output_rds.parent.mkdir(parents=True, exist_ok=True) + + # Convert Python lists to R vector strings + rs_r = f"c({', '.join(map(str, rs))})" + quoted_coords = [f'"{c}"' for c in spatial_coords] + coords_r = f"c({', '.join(quoted_coords)})" + + # Use .as_posix() for cross-platform path compatibility + input_path_posix = input_rds.as_posix() + output_path_posix = output_rds.as_posix() + + r_script = f""" + library(lisaClust) + library(SingleCellExperiment) + library(SpatialExperiment) + + cells <- readRDS("{input_path_posix}") + + # lisaClust can use pre-calculated LISA values from metadata or calculate them. + # We pass all parameters; if metadata(cells)$lisa exists, it will be used, + # otherwise, lisa values will be calculated using the other provided parameters. + lisa_pre <- NULL + if ("lisa" %in% names(metadata(cells))) {{ + lisa_pre <- metadata(cells)$lisa + }} + + cells <- lisaClust( + cells, + k = {k}, + lisa = lisa_pre, + cellType = "{cell_type_col}", + imageID = "{image_id_col}", + spatialCoords = {coords_r}, + Rs = {rs_r} + ) + + # Rename the default 'region' column if a different name is requested + if ("{region_name}" != "region") {{ + colData(cells)[["{region_name}"]] <- colData(cells)$region + colData(cells)$region <- NULL + }} + + saveRDS(cells, "{output_path_posix}") + """ + + tmp_path = None + cmd = [] + try: + with tempfile.NamedTemporaryFile(mode="w", suffix=".R", delete=False, encoding="utf-8") as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True, encoding="utf-8") + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_rds)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed." + } + finally: + if tmp_path and Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def lisa_hatch_plot( + input_rds: Path, + output_plot: Path, + region_col: str = "region", + cell_type_col: str = "cellType", + image_id: Optional[str] = None, + width: int = 10, + height: int = 8 +) -> dict: + """ + Generate a hatch plot to visualize cell-type colocalization within identified regions. + + This function wraps the `hatchPlot()` function from `lisaClust`. + + Args: + input_rds: Path to an RDS file with lisaClust results. + output_plot: Path to save the output plot (e.g., plot.png, plot.pdf). + region_col: Column name in colData containing region clusters. + cell_type_col: Column name in colData containing cell type labels. + image_id: Specific ImageID to plot. If None, the first available image is used. + width: Width of the output plot in inches. + height: Height of the output plot in inches. + """ + # Input validation + if not input_rds.exists(): + raise FileNotFoundError(f"Input file not found: {input_rds}") + if width <= 0 or height <= 0: + raise ValueError("Plot width and height must be positive.") + + # Ensure output directory exists + output_plot.parent.mkdir(parents=True, exist_ok=True) + + # Use .as_posix() for cross-platform path compatibility + input_path_posix = input_rds.as_posix() + output_path_posix = output_plot.as_posix() + + # R logic to select an image_id if not provided + img_id_r = f'"{image_id}"' if image_id else "unique(colData(cells)$imageID)[1]" + + r_script = f""" + library(lisaClust) + library(ggplot2) + library(SingleCellExperiment) + + cells <- readRDS("{input_path_posix}") + + # Subset to a single image for plotting + image_to_plot <- {img_id_r} + cells_sub <- cells[, colData(cells)$imageID == image_to_plot] + + p <- hatchPlot( + cells_sub, + region = "{region_col}", + cellType = "{cell_type_col}" + ) + + ggsave("{output_path_posix}", plot = p, width = {width}, height = {height}) + """ + + tmp_path = None + cmd = [] + try: + with tempfile.NamedTemporaryFile(mode="w", suffix=".R", delete=False, encoding="utf-8") as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True, encoding="utf-8") + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_plot)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed." + } + finally: + if tmp_path and Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def lisa_region_map( + input_rds: Path, + output_plot: Path, + region_col: str = "region", + image_id: Optional[str] = None, + width: int = 10, + height: int = 8 +) -> dict: + """ + Generate a region map to visualize the spatial distribution of identified regions. + + This function wraps the `regionMap()` function from `lisaClust`. + + Args: + input_rds: Path to an RDS file with lisaClust results. + output_plot: Path to save the output plot (e.g., plot.png, plot.pdf). + region_col: Column name in colData containing region clusters. + image_id: Specific ImageID to plot. If None, the first available image is used. + width: Width of the output plot in inches. + height: Height of the output plot in inches. + """ + # Input validation + if not input_rds.exists(): + raise FileNotFoundError(f"Input file not found: {input_rds}") + if width <= 0 or height <= 0: + raise ValueError("Plot width and height must be positive.") + + # Ensure output directory exists + output_plot.parent.mkdir(parents=True, exist_ok=True) + + # Use .as_posix() for cross-platform path compatibility + input_path_posix = input_rds.as_posix() + output_path_posix = output_plot.as_posix() + + # R logic to select an image_id if not provided + img_id_r = f'"{image_id}"' if image_id else "unique(colData(cells)$imageID)[1]" + + r_script = f""" + library(lisaClust) + library(ggplot2) + library(SingleCellExperiment) + + cells <- readRDS("{input_path_posix}") + + # Subset to a single image for plotting + image_to_plot <- {img_id_r} + cells_sub <- cells[, colData(cells)$imageID == image_to_plot] + + p <- regionMap( + cells_sub, + region = "{region_col}" + ) + + ggsave("{output_path_posix}", plot = p, width = {width}, height = {height}) + """ + + tmp_path = None + cmd = [] + try: + with tempfile.NamedTemporaryFile(mode="w", suffix=".R", delete=False, encoding="utf-8") as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True, encoding="utf-8") + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_plot)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed." + } + finally: + if tmp_path and Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def lisa_heatmap( + input_rds: Path, + output_plot: Path, + region_col: str = "region", + width: int = 10, + height: int = 8 +) -> dict: + """ + Generate a heatmap of LISA values across identified regions. + + This function wraps the `lisaHeatmap()` function from `lisaClust`. + + Args: + input_rds: Path to an RDS file with lisaClust results and LISA values in metadata. + output_plot: Path to save the output heatmap (e.g., heatmap.png, heatmap.pdf). + region_col: Column name in colData containing region clusters. + width: Width of the output plot in inches. + height: Height of the output plot in inches. + """ + # Input validation + if not input_rds.exists(): + raise FileNotFoundError(f"Input file not found: {input_rds}") + if width <= 0 or height <= 0: + raise ValueError("Plot width and height must be positive.") + + # Ensure output directory exists + output_plot.parent.mkdir(parents=True, exist_ok=True) + + # Use .as_posix() for cross-platform path compatibility + input_path_posix = input_rds.as_posix() + output_path_posix = output_plot.as_posix() + + # Determine the R graphics device based on file extension + ext = output_plot.suffix.lower() + if ext == ".png": + device_open = f'png("{output_path_posix}", width = {width}, height = {height}, units = "in", res = 300)' + elif ext == ".pdf": + device_open = f'pdf("{output_path_posix}", width = {width}, height = {height})' + elif ext == ".svg": + device_open = f'svg("{output_path_posix}", width = {width}, height = {height})' + else: + # Default to png if extension is unknown or not supported by base R graphics + output_path_posix_with_ext = output_plot.with_suffix(".png").as_posix() + device_open = f'png("{output_path_posix_with_ext}", width = {width}, height = {height}, units = "in", res = 300)' + + r_script = f""" + library(lisaClust) + library(pheatmap) + library(SingleCellExperiment) + + cells <- readRDS("{input_path_posix}") + + # lisaHeatmap requires the LISA matrix, which should be in the metadata. + if (!"lisa" %in% names(metadata(cells))) {{ + stop("LISA values not found in metadata. Please run lisa_calculate first.") + }} + lisa_values <- metadata(cells)$lisa + + {device_open} + lisaHeatmap(cells, lisa = lisa_values, region = "{region_col}") + dev.off() + """ + + tmp_path = None + cmd = [] + try: + with tempfile.NamedTemporaryFile(mode="w", suffix=".R", delete=False, encoding="utf-8") as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True, encoding="utf-8") + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_plot)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed." + } + finally: + if tmp_path and Path(tmp_path).exists(): + Path(tmp_path).unlink() \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-lisaclust/app/bioconductor-lisaclust_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-lisaclust/app/bioconductor-lisaclust_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..99b83298805e7bbd1e16594d109b2a1554aa9046 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-lisaclust/app/bioconductor-lisaclust_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_manual_txt/mcp_bioconductor-lisaclust/app/bioconductor-lisaclust_server.py') +SERVER_NAME = 'biosci_bioconductor_lisaclust' + + +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_manual_txt/mcp_bioconductor-lisaclust/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-lisaclust/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-lisaclust/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-lisaclust/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-lisaclust/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..6b5ccf07a1d68d868fca6a5ae63566a0cbfe846d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-lisaclust/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-lisaclust: + build: . + image: mcp-bioconductor-lisaclust:latest + container_name: mcp-bioconductor-lisaclust + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-lisaclust + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-lisaclust/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-lisaclust/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5b912c84ed80ef4befecd4169101fad7e1ed0132 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-lisaclust/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-lisaclust + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-lisaclust/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-lisaclust/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-lisaclust/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mastr/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mastr/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7a616939e747f440f980604cbf5026f178643614 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mastr/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-mastr via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-mastr -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-mastr_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-mastr_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-mastr_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mastr/app/bioconductor-mastr_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mastr/app/bioconductor-mastr_server.py new file mode 100644 index 0000000000000000000000000000000000000000..900182693bcab90d3966c78b0908e3ffb4a551cc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mastr/app/bioconductor-mastr_server.py @@ -0,0 +1,200 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Union + +@mcp.tool() +def mastr_align( + fasta_input: str, + output_alignment: str, + iterations: int = 100, + temperature: float = 1.0, + cooling_rate: float = 0.9, + gap_open: float = -10.0, + gap_extend: float = -1.0, + use_structure: bool = True, + r_path: str = "Rscript" +): + """ + Perform Multiple Alignment of Structural RNAs (MASTR) using the Bioconductor mastr package. + + Args: + fasta_input: Path to the input FASTA file containing RNA sequences. + output_alignment: Path where the resulting alignment (FASTA format) will be saved. + iterations: Number of iterations for the simulated annealing (default: 100). + temperature: Initial temperature for simulated annealing (default: 1.0). + cooling_rate: Cooling rate for simulated annealing (default: 0.9). + gap_open: Penalty for opening a gap (default: -10.0). + gap_extend: Penalty for extending a gap (default: -1.0). + use_structure: Whether to incorporate secondary structure prediction (default: True). + r_path: Path to the Rscript executable (default: 'Rscript'). + """ + # Input validation + input_path = Path(fasta_input) + if not input_path.exists(): + return {"error": f"Input file not found: {fasta_input}"} + + output_path = Path(output_alignment) + output_path.parent.mkdir(parents=True, exist_ok=True) + + if iterations <= 0: + return {"error": "Iterations must be a positive integer."} + + if not (0 < cooling_rate < 1): + return {"error": "Cooling rate must be between 0 and 1."} + + # Create an R script to execute the mastr package + # Note: mastr is a Bioconductor package, so we use Rscript to interface with it. + r_script_content = f""" + library(mastr) + library(Biostrings) + + # Load sequences + seqs <- readRNAStringSet("{input_path.absolute()}") + + # Define parameters + params <- list( + iterations = {iterations}, + temp = {temperature}, + cooling = {cooling_rate}, + gapOpen = {gap_open}, + gapExtend = {gap_extend}, + useStructure = {"TRUE" if use_structure else "FALSE"} + ) + + # Run MASTR alignment + # Note: mastr() is the primary function in the Bioconductor package + alignment_result <- mastr(seqs, + iterations = params$iterations, + temp = params$temp, + cooling = params$cooling, + gapOpen = params$gapOpen, + gapExtend = params$gapExtend) + + # Write output + writeXStringSet(alignment_result, "{output_path.absolute()}") + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script_content) + tmp_path = tmp.name + + try: + # Execute the R script + process = subprocess.run( + [r_path, tmp_path], + capture_output=True, + text=True, + check=True + ) + + return { + "command_executed": f"{r_path} {tmp_path}", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_path.absolute())], + "status": "Success" + } + + except subprocess.CalledProcessError as e: + return { + "command_executed": f"{r_path} {tmp_path}", + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R execution failed. Ensure 'mastr' and 'Biostrings' packages are installed in R.", + "status": "Error" + } + finally: + # Cleanup temporary R script + if Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def mastr_score_alignment( + alignment_file: str, + r_path: str = "Rscript" +): + """ + Calculate the structural conservation score for an existing RNA alignment using mastr metrics. + + Args: + alignment_file: Path to the aligned FASTA/Stockholm file. + r_path: Path to the Rscript executable. + """ + input_path = Path(alignment_file) + if not input_path.exists(): + return {"error": f"Alignment file not found: {alignment_file}"} + + r_script_content = f""" + library(mastr) + library(Biostrings) + + aln <- readRNAStringSet("{input_path.absolute()}") + # Calculate conservation score based on mastr's internal scoring + # This typically involves base-pairing probabilities and covariance + score <- mastr:::calculateScore(aln) # Accessing internal scoring if exported or via wrapper + cat("Alignment_Score:", score, "\\n") + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script_content) + tmp_path = tmp.name + + try: + process = subprocess.run( + [r_path, tmp_path], + capture_output=True, + text=True, + check=True + ) + + return { + "command_executed": f"{r_path} {tmp_path}", + "stdout": process.stdout, + "stderr": process.stderr, + "status": "Success" + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stderr": e.stderr, + "status": "Error" + } + finally: + if Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def mastr_check_dependencies(r_path: str = "Rscript"): + """ + Verify if R and the required Bioconductor mastr package are installed and accessible. + + Args: + r_path: Path to the Rscript executable. + """ + r_script_content = """ + if (!requireNamespace("mastr", quietly = TRUE)) { + stop("Package 'mastr' not found. Please install it via BiocManager::install('mastr')") + } + if (!requireNamespace("Biostrings", quietly = TRUE)) { + stop("Package 'Biostrings' not found.") + } + cat("All dependencies are satisfied.\\n") + """ + + try: + process = subprocess.run( + [r_path, "-e", r_script_content], + capture_output=True, + text=True, + check=True + ) + return { + "status": "Ready", + "stdout": process.stdout + } + except Exception as e: + return { + "status": "Missing Dependencies", + "error": str(e) + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mastr/app/bioconductor-mastr_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mastr/app/bioconductor-mastr_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..eb2e264472de2c207ecdd88a874640e4e6b9960b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mastr/app/bioconductor-mastr_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_manual_txt/mcp_bioconductor-mastr/app/bioconductor-mastr_server.py') +SERVER_NAME = 'biosci_bioconductor_mastr' + + +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_manual_txt/mcp_bioconductor-mastr/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mastr/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mastr/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mastr/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mastr/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..aad69a69c3c0d8f60c9082670992d86ee3fb50f2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mastr/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-mastr: + build: . + image: mcp-bioconductor-mastr:latest + container_name: mcp-bioconductor-mastr + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-mastr + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mastr/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mastr/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..63a854e34eec69ad376ee17e9f2cb9abe6add82b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mastr/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-mastr + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mastr/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mastr/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mastr/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-matrixgenerics/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-matrixgenerics/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3884a414339405a05ed35204259e33ccac923b21 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-matrixgenerics/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-matrixgenerics via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-matrixgenerics -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-matrixgenerics_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-matrixgenerics_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-matrixgenerics_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-matrixgenerics/app/bioconductor-matrixgenerics_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-matrixgenerics/app/bioconductor-matrixgenerics_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c3463ffa08c93ca558b8e72d593237715090549e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-matrixgenerics/app/bioconductor-matrixgenerics_server.py @@ -0,0 +1,223 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Literal, Optional + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be imported. +def mcp_tool_decorator_placeholder(*args, **kwargs): + def decorator(func): + return func + return decorator + +mcp = type("mcp", (), {"tool": mcp_tool_decorator_placeholder}) + + +# A comprehensive list of functions provided by the MatrixGenerics package. +MatrixGenericsOperation = Literal[ + "colAlls", "colAnyNAs", "colAnys", "colAvgsPerRow", "colCounts", "colCummaxs", + "colCummins", "colCumprods", "colCumsums", "colDiffs", "colIQRDiffs", "colIQRs", + "colLogSumExps", "colMadDiffs", "colMads", "colMaxs", "colMeans2", "colMedians", + "colMins", "colOrderStats", "colProds", "colQuantiles", "colRanges", "colRanks", + "colSdDiffs", "colSds", "colSums2", "colTabulates", "colVarDiffs", "colVars", + "colWeightedMads", "colWeightedMeans", "colWeightedMedians", "colWeightedSds", + "colWeightedVars", "rowAlls", "rowAnyNAs", "rowAnys", "rowAvgsPerCol", + "rowCounts", "rowCummaxs", "rowCummins", "rowCumprods", "rowCumsums", + "rowDiffs", "rowIQRDiffs", "rowIQRs", "rowLogSumExps", "rowMadDiffs", + "rowMads", "rowMaxs", "rowMeans2", "rowMedians", "rowMins", "rowOrderStats", + "rowProds", "rowQuantiles", "rowRanges", "rowRanks", "rowSdDiffs", "rowSds", + "rowSums2", "rowTabulates", "rowVarDiffs", "rowVars", "rowWeightedMads", + "rowWeightedMeans", "rowWeightedMedians", "rowWeightedSds", "rowWeightedVars" +] + +TiesMethod = Literal["average", "first", "last", "random", "max", "min"] + +@mcp.tool() +def perform_matrix_statistic( + input_matrix: Path, + operation: MatrixGenericsOperation, + output_filename: str, + na_rm: bool = True, + delimiter: Literal[",", "\t"] = "\t", + has_header: bool = True, + has_rownames: bool = True, + probs: Optional[str] = None, + weights: Optional[Path] = None, + ties_method: TiesMethod = "average", + value: Optional[float] = None, + lag: int = 1, + differences: int = 1, + which: Optional[int] = None, + preserve_shape: bool = False +) -> dict: + """ + Performs a specified summary statistic on a matrix using the MatrixGenerics R package. + + This tool serves as a wrapper around the bioconductor-matrixgenerics R library, + which provides generic functions for matrix statistics. It reads a matrix from a file, + applies the chosen statistical operation, and saves the result to a new file. + + Args: + input_matrix: Path to the input matrix file (e.g., CSV or TSV). + operation: The summary statistic to compute. + output_filename: The name for the output file that will be created. + na_rm: If True, NA/NaN values are removed before computation. + delimiter: Delimiter used in the input matrix file (',' or '\t'). + has_header: Whether the input file has a header row. + has_rownames: Whether the first column of the input file contains row names. + probs: Comma-separated string of probabilities for quantile functions (e.g., "0.25,0.5,0.75"). + weights: Path to a single-column file of numeric weights for weighted operations. + ties_method: Method for handling ties in ranking functions. + value: The specific value to count for '*Counts' functions. + lag: The lag for '*Diffs' functions. + differences: The number of differences for '*Diffs' functions. + which: The order statistic to extract for '*OrderStats' functions. + preserve_shape: For '*Ranks' functions, if TRUE the output has the same dimensions as the input. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not input_matrix.is_file(): + raise FileNotFoundError(f"Input matrix file not found: {input_matrix}") + + if weights and not weights.is_file(): + raise FileNotFoundError(f"Weights file not found: {weights}") + + if not output_filename: + raise ValueError("Output filename cannot be empty.") + + # --- R Script Generation --- + r_script = f""" + # Load necessary library + if (!require("MatrixGenerics", quietly = TRUE)) {{ + stop("MatrixGenerics package is not installed.") + }} + + # --- Argument Parsing --- + args <- commandArgs(trailingOnly = TRUE) + input_file <- args[1] + output_file <- args[2] + operation <- args[3] + na_rm <- as.logical(args[4]) + sep <- args[5] + header <- as.logical(args[6]) + rownames_col <- if (as.logical(args[7])) 1 else NULL + probs_str <- args[8] + weights_file <- args[9] + ties_method <- args[10] + value_str <- args[11] + lag <- as.integer(args[12]) + differences <- as.integer(args[13]) + which_str <- args[14] + preserve_shape <- as.logical(args[15]) + + # --- Data Loading --- + tryCatch({{ + data <- read.delim(input_file, sep = sep, header = header, row.names = rownames_col, check.names = FALSE) + mat <- as.matrix(data) + }}, error = function(e) {{ + stop(paste("Error reading input matrix:", e$message)) + }}) + + # --- Dynamic Function Call --- + # Build the list of parameters + params <- list(x = mat) + + # Add common parameters if the function accepts them + func_args <- names(formals(operation)) + if ("na.rm" %in% func_args) params$na.rm <- na_rm + if ("ties.method" %in% func_args) params$ties.method <- ties_method + if ("value" %in% func_args && value_str != "NULL") params$value <- as.numeric(value_str) + if ("lag" %in% func_args) params$lag <- lag + if ("differences" %in% func_args) params$differences <- differences + if ("which" %in% func_args && which_str != "NULL") params$which <- as.integer(which_str) + if ("preserveShape" %in% func_args) params$preserveShape <- preserve_shape + + # Handle special parameters + if (grepl("Quantiles", operation) && probs_str != "NULL") {{ + params$probs <- as.numeric(strsplit(probs_str, ",")[[1]]) + }} + if (grepl("Weighted", operation) && weights_file != "NULL") {{ + tryCatch({{ + weights_vector <- read.table(weights_file, header = FALSE, colClasses = "numeric")[[1]] + params$w <- weights_vector + }}, error = function(e) {{ + stop(paste("Error reading weights file:", e$message)) + }}) + }} + + # Get the function from the package namespace + func <- get(operation, asNamespace("MatrixGenerics")) + + # Execute the function + result <- do.call(func, params) + + # --- Output Writing --- + # write.table is robust for vectors, matrices, and data.frames + write.table(result, file = output_file, sep = "\\t", quote = FALSE, col.names = NA) + """ + + with tempfile.TemporaryDirectory() as temp_dir: + temp_path = Path(temp_dir) + r_script_path = temp_path / "matrix_op.R" + with open(r_script_path, "w") as f: + f.write(r_script) + + output_path = Path.cwd() / output_filename + + # --- Command Construction --- + cmd = [ + "Rscript", + str(r_script_path), + str(input_matrix), + str(output_path), + operation, + str(na_rm).upper(), + "\\t" if delimiter == "\t" else ",", + str(has_header).upper(), + str(has_rownames).upper(), + probs if probs else "NULL", + str(weights) if weights else "NULL", + ties_method, + str(value) if value is not None else "NULL", + str(lag), + str(differences), + str(which) if which is not None else "NULL", + str(preserve_shape).upper() + ] + + # --- Subprocess Execution --- + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(map(str, cmd)), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": "R script execution failed." + } + except FileNotFoundError: + return { + "command_executed": " ".join(map(str, cmd)), + "stdout": "", + "stderr": "Rscript command not found. Please ensure R is installed and in your PATH.", + "output_files": [], + "error": "Dependency not found." + } + + # --- Structured Result Return --- + return { + "command_executed": " ".join(map(str, cmd)), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_path)] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-matrixgenerics/app/bioconductor-matrixgenerics_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-matrixgenerics/app/bioconductor-matrixgenerics_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..31bc6ff51db51b08634ceb88ef3c3f381df653b3 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-matrixgenerics/app/bioconductor-matrixgenerics_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_manual_txt/mcp_bioconductor-matrixgenerics/app/bioconductor-matrixgenerics_server.py') +SERVER_NAME = 'biosci_bioconductor_matrixgenerics' + + +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_manual_txt/mcp_bioconductor-matrixgenerics/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-matrixgenerics/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-matrixgenerics/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-matrixgenerics/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-matrixgenerics/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7bd9323b314d29fa4bdf3a49442b1ef41fe55464 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-matrixgenerics/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-matrixgenerics: + build: . + image: mcp-bioconductor-matrixgenerics:latest + container_name: mcp-bioconductor-matrixgenerics + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-matrixgenerics + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-matrixgenerics/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-matrixgenerics/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..55a5066ba648a0a9d45d2f77c2a3fd79a0e2230f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-matrixgenerics/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-matrixgenerics + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-matrixgenerics/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-matrixgenerics/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-matrixgenerics/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-merfishdata/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-merfishdata/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7823c41076fc0b5b374ed7430f528d63e59978fe --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-merfishdata/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-merfishdata via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-merfishdata -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-merfishdata_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-merfishdata_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-merfishdata_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-merfishdata/app/bioconductor-merfishdata_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-merfishdata/app/bioconductor-merfishdata_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a2d5e75fab4f2983437d1c783d33071d1f4a792e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-merfishdata/app/bioconductor-merfishdata_server.py @@ -0,0 +1,232 @@ +import subprocess +import json +from pathlib import Path +from typing import List, Dict, Optional, Union +import tempfile + +# No need to import mcp as per instructions + +def _run_r_script(r_code: str, output_dir: Optional[Path] = None) -> Dict[str, Union[str, List[Path]]]: + """ + Helper function to execute R code using Rscript. + + Args: + r_code: The R script code to execute. + output_dir: An optional directory where R might write files. If provided, + it ensures the directory exists. + + Returns: + A dictionary containing execution details, stdout, stderr, and any errors. + """ + if output_dir: + output_dir.mkdir(parents=True, exist_ok=True) + + # Use a temporary file for the R script to handle potentially long R code + # and ensure proper execution context. + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R", encoding='utf-8') as temp_r_script: + temp_r_script.write(r_code) + temp_r_script_path = Path(temp_r_script.name) + + command = ["Rscript", str(temp_r_script_path)] + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + stdout = process.stdout + stderr = process.stderr + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": [], # This helper doesn't track specific output files, main functions will + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": f"Rscript execution failed with exit code {e.returncode}", + } + finally: + # Clean up the temporary R script + if temp_r_script_path.exists(): + temp_r_script_path.unlink() + + +@mcp.tool() +def list_merfish_datasets() -> Dict[str, Union[str, List[Dict[str, str]]]]: + """ + Lists available MERFISH datasets from the Bioconductor ExperimentHub. + + This function queries the ExperimentHub for datasets provided by the + MerfishData package and returns their metadata, including unique + ExperimentHub IDs (eh_id). + + Returns: + A dictionary containing: + - 'command_executed': The Rscript command executed. + - 'stdout': Standard output from the R script. + - 'stderr': Standard error from the R script. + - 'datasets': A list of dictionaries, where each dictionary represents + a dataset with its metadata (e.g., title, description, eh_id). + - 'error': (Optional) Error message if the R script fails. + """ + r_script_code = """ + options(timeout = 600) # Increase timeout for BiocManager::install and ExperimentHub downloads + # Install BiocManager if not present + if (!require("BiocManager", quietly = TRUE)) install.packages("BiocManager", repos = "https://cloud.r-project.org") + # Install MerfishData and ExperimentHub if not present + if (!require("MerfishData", quietly = TRUE)) BiocManager::install("MerfishData", update = FALSE, ask = FALSE) + if (!require("ExperimentHub", quietly = TRUE)) BiocManager::install("ExperimentHub", update = FALSE, ask = FALSE) + # Install jsonlite for JSON output + if (!require("jsonlite", quietly = TRUE)) install.packages("jsonlite", repos = "https://cloud.r-project.org", update = FALSE, ask = FALSE) + + library(MerfishData) + library(ExperimentHub) + library(jsonlite) + + eh <- ExperimentHub() + merfish_resources <- query(eh, "MerfishData") + + # Extract metadata including the unique ExperimentHub ID (rownames) + metadata_df <- as.data.frame(mcols(merfish_resources)) + metadata_df$eh_id <- rownames(merfish_resources) # Add ID as a column + + # Convert to JSON and print to stdout + cat(toJSON(metadata_df, pretty = TRUE)) + """ + + result = _run_r_script(r_script_code) + + if "error" in result: + return result + + try: + datasets_json = result["stdout"] + # Attempt to parse JSON, but handle cases where R might print warnings/messages before JSON + # Find the first and last curly brace to isolate the JSON array/object + json_start = datasets_json.find('[') + json_end = datasets_json.rfind(']') + if json_start == -1 or json_end == -1: # If it's a single object, it might be { ... } + json_start = datasets_json.find('{') + json_end = datasets_json.rfind('}') + + if json_start != -1 and json_end != -1 and json_end > json_start: + clean_json_str = datasets_json[json_start : json_end + 1] + datasets_list = json.loads(clean_json_str) + else: + # If no valid JSON found, return raw stdout and an error + return { + "command_executed": result["command_executed"], + "stdout": result["stdout"], + "stderr": result["stderr"], + "datasets": [], + "error": "Could not parse JSON output from R script. Raw stdout returned.", + } + + return { + "command_executed": result["command_executed"], + "stdout": result["stdout"], + "stderr": result["stderr"], + "datasets": datasets_list, + } + except json.JSONDecodeError as e: + return { + "command_executed": result["command_executed"], + "stdout": result["stdout"], + "stderr": result["stderr"], + "datasets": [], + "error": f"Failed to decode JSON from R script stdout: {e}. Raw stdout: {result['stdout']}", + } + + +@mcp.tool() +def get_merfish_dataset( + dataset_id: str, + output_dir: Path, + output_filename: Optional[str] = None, +) -> Dict[str, Union[str, List[Path]]]: + """ + Downloads a specific MERFISH dataset from the Bioconductor ExperimentHub. + + The dataset is identified by its unique ExperimentHub ID (eh_id), which + can be obtained using the `list_merfish_datasets` function. The retrieved + R object (typically a SpatialExperiment or SingleCellExperiment) is saved + as an R Data Serialization (RDS) file. + + Args: + dataset_id: The unique ExperimentHub ID (eh_id) of the MERFISH dataset to download. + This ID can be found using `list_merfish_datasets`. + output_dir: The directory where the downloaded .rds file will be saved. + This directory will be created if it does not exist. + output_filename: Optional. The name of the output .rds file. If not provided, + it defaults to '{dataset_id}.rds'. + + Returns: + A dictionary containing: + - 'command_executed': The Rscript command executed. + - 'stdout': Standard output from the R script. + - 'stderr': Standard error from the R script. + - 'output_files': A list containing the path to the downloaded .rds file. + - 'error': (Optional) Error message if the R script fails. + """ + # Input validation + if not dataset_id: + raise ValueError("dataset_id cannot be empty.") + + output_dir.mkdir(parents=True, exist_ok=True) + + if output_filename: + if not output_filename.endswith(".rds"): + output_filename += ".rds" + output_file_path = output_dir / output_filename + else: + output_file_path = output_dir / f"{dataset_id}.rds" + + r_script_code = f""" + options(timeout = 600) # Increase timeout for BiocManager::install and ExperimentHub downloads + # Install BiocManager if not present + if (!require("BiocManager", quietly = TRUE)) install.packages("BiocManager", repos = "https://cloud.r-project.org") + # Install MerfishData and ExperimentHub if not present + if (!require("MerfishData", quietly = TRUE)) BiocManager::install("MerfishData", update = FALSE, ask = FALSE) + if (!require("ExperimentHub", quietly = TRUE)) BiocManager::install("ExperimentHub", update = FALSE, ask = FALSE) + + library(MerfishData) + library(ExperimentHub) + + dataset_id <- "{dataset_id}" + output_file <- "{output_file_path.as_posix()}" + + eh <- ExperimentHub() + + # Query for MerfishData resources specifically + merfish_resources <- query(eh, "MerfishData") + + # Check if the provided ID exists among MerfishData resources + if (!dataset_id %in% rownames(merfish_resources)) {{ + stop(paste0("Dataset ID '", dataset_id, "' not found among MerfishData resources in ExperimentHub.")) + }} + + # Retrieve the dataset + dataset_object <- eh[[dataset_id]] + + # Save the R object as an RDS file + saveRDS(dataset_object, file = output_file) + cat(paste0("Dataset '", dataset_id, "' successfully saved to ", output_file, "\\n")) + """ + + result = _run_r_script(r_script_code, output_dir=output_dir) + + if "error" in result: + return result + + # Add the output file to the list of output_files + result["output_files"].append(output_file_path) + return result \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-merfishdata/app/bioconductor-merfishdata_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-merfishdata/app/bioconductor-merfishdata_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d956185f38cb4b77761eb5821bf114b544ad816e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-merfishdata/app/bioconductor-merfishdata_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_manual_txt/mcp_bioconductor-merfishdata/app/bioconductor-merfishdata_server.py') +SERVER_NAME = 'biosci_bioconductor_merfishdata' + + +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_manual_txt/mcp_bioconductor-merfishdata/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-merfishdata/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-merfishdata/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-merfishdata/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-merfishdata/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..028f4ed20287df19fcee8ba50d198b3371380819 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-merfishdata/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-merfishdata: + build: . + image: mcp-bioconductor-merfishdata:latest + container_name: mcp-bioconductor-merfishdata + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-merfishdata + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-merfishdata/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-merfishdata/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1b4733c5a9506552925d4759b4bdf34f3bd8cff2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-merfishdata/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-merfishdata + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-merfishdata/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-merfishdata/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-merfishdata/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-metapod/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-metapod/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5c6a2b29f342a8ea28bc8a1d8f2327a8ed77fc1c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-metapod/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-metapod via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-metapod -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-metapod_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-metapod_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-metapod_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-metapod/app/bioconductor-metapod_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-metapod/app/bioconductor-metapod_server.py new file mode 100644 index 0000000000000000000000000000000000000000..029bc0916c2ef64ef81f7988a3b3b40eb0cbcd4c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-metapod/app/bioconductor-metapod_server.py @@ -0,0 +1,322 @@ +import subprocess +import tempfile +import os +from pathlib import Path +from typing import List, Optional, Dict, Any + +# No need to import mcp as per instructions + +@mcp.tool() +def combine_p_values( + p_values_file: Path, + output_file: Path, + weights_file: Optional[Path] = None, + method: str = "fisher", + log_p: bool = False, + na_rm: bool = False, + min_p: float = 0.0, + max_p: float = 1.0, + input_sep: str = ",", + input_header: bool = False, +) -> Dict[str, Any]: + """ + Combines p-values from differential analyses using various meta-analysis methods + provided by the bioconductor-metapod R package. + + This function wraps the `metapod::combinePValues` R function. It supports combining + a single vector of p-values or multiple sets of p-values (e.g., from different tests). + + Args: + p_values_file: Path to a file containing p-values. Each row should represent + a set of p-values to be combined. For a single vector of p-values, + the file can have one column. For multiple sets, it can have + multiple columns. + output_file: Path to the output file where the combined p-values will be written. + The output will be a CSV file. + weights_file: Optional path to a file containing weights corresponding to the p-values. + Must have the same structure (number of rows/columns) as `p_values_file`. + method: The method to use for combining p-values. + Allowed values: "fisher", "stouffer", "simes", "davies", "whitlock", + "fdr", "bonferroni", "none". + log_p: If TRUE, p-values are assumed to be log-transformed. + na_rm: If TRUE, NA p-values are removed before combination. + min_p: Minimum p-value to consider. Values below this will be set to min_p. + Must be between 0 and 1. + max_p: Maximum p-value to consider. Values above this will be set to max_p. + Must be between 0 and 1. + input_sep: The field separator character for input p-values and weights files. + Common values are "," for CSV and "\\t" for TSV. + input_header: If TRUE, the input p-values and weights files are assumed to have a header row. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + if not p_values_file.is_file(): + raise FileNotFoundError(f"Input p-values file not found: {p_values_file}") + if weights_file and not weights_file.is_file(): + raise FileNotFoundError(f"Input weights file not found: {weights_file}") + + if not (0.0 <= min_p <= 1.0): + raise ValueError("min_p must be between 0 and 1.") + if not (0.0 <= max_p <= 1.0): + raise ValueError("max_p must be between 0 and 1.") + if min_p > max_p: + raise ValueError("min_p cannot be greater than max_p.") + + allowed_methods = ["fisher", "stouffer", "simes", "davies", "whitlock", "fdr", "bonferroni", "none"] + if method not in allowed_methods: + raise ValueError(f"Invalid method: '{method}'. Must be one of {allowed_methods}") + + # Ensure output directory exists + output_file.parent.mkdir(parents=True, exist_ok=True) + + # Convert boolean to R's TRUE/FALSE + r_log_p = str(log_p).upper() + r_na_rm = str(na_rm).upper() + r_input_header = str(input_header).upper() + + # Create a temporary R script + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".R") as r_script_temp: + r_script_path = Path(r_script_temp.name) + r_script_temp.write(f""" + library(metapod) + + # Read p-values + p_values_data <- read.csv( + "{p_values_file}", + header={r_input_header}, + sep="{input_sep}", + stringsAsFactors=FALSE + ) + # metapod::combinePValues expects a numeric vector or a list of numeric vectors. + # If p_values_data is a data.frame, we convert it to a list of vectors (columns) + # or assume it's a single vector if it has one column. + if (ncol(p_values_data) == 1) {{ + p_values_input <- as.numeric(p_values_data[[1]]) + }} else {{ + p_values_input <- lapply(p_values_data, as.numeric) + }} + + weights_input <- NULL + if (!is.null("{weights_file}")) {{ + weights_data <- read.csv( + "{weights_file}", + header={r_input_header}, + sep="{input_sep}", + stringsAsFactors=FALSE + ) + if (ncol(weights_data) == 1) {{ + weights_input <- as.numeric(weights_data[[1]]) + }} else {{ + weights_input <- lapply(weights_data, as.numeric) + }} + }} + + # Call combinePValues + combined_p_values <- metapod::combinePValues( + p.values = p_values_input, + weights = weights_input, + method = "{method}", + log.p = {r_log_p}, + na.rm = {r_na_rm}, + min.p = {min_p}, + max.p = {max_p} + ) + + # Write results to output file + write.csv(combined_p_values, file = "{output_file}", row.names = FALSE) + """) + + command = ["Rscript", str(r_script_path)] + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + # Clean up the temporary script even if an error occurs + os.remove(r_script_path) + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Rscript execution failed with exit code {e.returncode}", + "output_files": [], + } + finally: + # Clean up the temporary R script + if r_script_path.exists(): + os.remove(r_script_path) + + if not output_file.is_file(): + stderr += f"\nError: Expected output file '{output_file}' was not created." + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_file)], + } + + +@mcp.tool() +def grouped_p_values( + p_values_file: Path, + groups_file: Path, + output_file: Path, + weights_file: Optional[Path] = None, + method: str = "fisher", + log_p: bool = False, + na_rm: bool = False, + min_p: float = 0.0, + max_p: float = 1.0, + input_sep: str = ",", + input_header: bool = False, +) -> Dict[str, Any]: + """ + Combines p-values within specified groups using various meta-analysis methods + provided by the bioconductor-metapod R package. + + This function wraps the `metapod::groupedPValues` R function. It requires a + separate file for group assignments for each p-value. + + Args: + p_values_file: Path to a file containing a single column of p-values. + groups_file: Path to a file containing a single column of group identifiers, + corresponding to each p-value in `p_values_file`. + output_file: Path to the output file where the combined p-values will be written. + The output will be a CSV file. + weights_file: Optional path to a file containing a single column of weights + corresponding to the p-values. + method: The method to use for combining p-values within groups. + Allowed values: "fisher", "stouffer", "simes", "davies", "whitlock", + "fdr", "bonferroni", "none". + log_p: If TRUE, p-values are assumed to be log-transformed. + na_rm: If TRUE, NA p-values are removed before combination. + min_p: Minimum p-value to consider. Values below this will be set to min_p. + Must be between 0 and 1. + max_p: Maximum p-value to consider. Values above this will be set to max_p. + Must be between 0 and 1. + input_sep: The field separator character for input p-values, groups, and weights files. + Common values are "," for CSV and "\\t" for TSV. + input_header: If TRUE, the input files are assumed to have a header row. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + if not p_values_file.is_file(): + raise FileNotFoundError(f"Input p-values file not found: {p_values_file}") + if not groups_file.is_file(): + raise FileNotFoundError(f"Input groups file not found: {groups_file}") + if weights_file and not weights_file.is_file(): + raise FileNotFoundError(f"Input weights file not found: {weights_file}") + + if not (0.0 <= min_p <= 1.0): + raise ValueError("min_p must be between 0 and 1.") + if not (0.0 <= max_p <= 1.0): + raise ValueError("max_p must be between 0 and 1.") + if min_p > max_p: + raise ValueError("min_p cannot be greater than max_p.") + + allowed_methods = ["fisher", "stouffer", "simes", "davies", "whitlock", "fdr", "bonferroni", "none"] + if method not in allowed_methods: + raise ValueError(f"Invalid method: '{method}'. Must be one of {allowed_methods}") + + # Ensure output directory exists + output_file.parent.mkdir(parents=True, exist_ok=True) + + # Convert boolean to R's TRUE/FALSE + r_log_p = str(log_p).upper() + r_na_rm = str(na_rm).upper() + r_input_header = str(input_header).upper() + + # Create a temporary R script + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".R") as r_script_temp: + r_script_path = Path(r_script_temp.name) + r_script_temp.write(f""" + library(metapod) + + # Read p-values (assuming single column) + p_values_input <- as.numeric(read.csv( + "{p_values_file}", + header={r_input_header}, + sep="{input_sep}", + stringsAsFactors=FALSE + )[[1]]) + + # Read groups (assuming single column) + groups_input <- as.factor(read.csv( + "{groups_file}", + header={r_input_header}, + sep="{input_sep}", + stringsAsFactors=FALSE + )[[1]]) + + weights_input <- NULL + if (!is.null("{weights_file}")) {{ + weights_input <- as.numeric(read.csv( + "{weights_file}", + header={r_input_header}, + sep="{input_sep}", + stringsAsFactors=FALSE + )[[1]]) + }} + + # Call groupedPValues + combined_p_values <- metapod::groupedPValues( + p.values = p_values_input, + groups = groups_input, + weights = weights_input, + method = "{method}", + log.p = {r_log_p}, + na.rm = {r_na_rm}, + min.p = {min_p}, + max.p = {max_p} + ) + + # Write results to output file + write.csv(combined_p_values, file = "{output_file}", row.names = FALSE) + """) + + command = ["Rscript", str(r_script_path)] + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + # Clean up the temporary script even if an error occurs + os.remove(r_script_path) + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Rscript execution failed with exit code {e.returncode}", + "output_files": [], + } + finally: + # Clean up the temporary R script + if r_script_path.exists(): + os.remove(r_script_path) + + if not output_file.is_file(): + stderr += f"\nError: Expected output file '{output_file}' was not created." + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_file)], + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-metapod/app/bioconductor-metapod_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-metapod/app/bioconductor-metapod_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ee849a87187aa9a4f7088abf69eb51353c788a9b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-metapod/app/bioconductor-metapod_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_manual_txt/mcp_bioconductor-metapod/app/bioconductor-metapod_server.py') +SERVER_NAME = 'biosci_bioconductor_metapod' + + +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_manual_txt/mcp_bioconductor-metapod/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-metapod/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-metapod/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-metapod/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-metapod/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d1c5940ca3366fe6942d00fdc1c76e36315ebb66 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-metapod/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-metapod: + build: . + image: mcp-bioconductor-metapod:latest + container_name: mcp-bioconductor-metapod + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-metapod + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-metapod/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-metapod/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..153d07b003e599338e3741bf7537f22006d08e89 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-metapod/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-metapod + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-metapod/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-metapod/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-metapod/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mia/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mia/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..550ada1f834d0528e040f3da5aab4014267c9673 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mia/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-mia via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-mia -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-mia_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-mia_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-mia_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mia/app/bioconductor-mia_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mia/app/bioconductor-mia_server.py new file mode 100644 index 0000000000000000000000000000000000000000..24436ae7223c5a25b0e5e011f39fa177296fec8b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mia/app/bioconductor-mia_server.py @@ -0,0 +1,126 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Dict, Any + +@mcp.tool() +def run_mia_r_script( + r_script_content: str, + input_rds_path: Optional[Path] = None, + output_rds_path: Optional[Path] = None, + working_directory: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Executes an R script that utilizes the bioconductor-mia package for microbiome analysis. + + This tool provides a generic interface to run arbitrary R code that is expected + to use the 'mia' Bioconductor package. It allows for loading an input R data + object (e.g., a SummarizedExperiment saved as .rds) and saving an output R data + object. + + Args: + r_script_content: A string containing the R script to be executed. + The script should assume 'mia' is loaded. + If `input_rds_path` is provided, the loaded object will + be available as `input_data`. + If `output_rds_path` is provided, the script should + assign the object to be saved to a variable named + `output_data`. + input_rds_path: Optional path to an R data object (.rds file) to be loaded + into the R environment before executing the script. + The object will be loaded as 'input_data'. + output_rds_path: Optional path where the R script should save an R data + object (e.g., a SummarizedExperiment) using saveRDS(). + The R script must assign the object to be saved to a + variable named 'output_data'. + working_directory: Optional path to a directory where the R script will be + executed. This can be useful for scripts that use + relative paths for additional input/output files. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any + generated output files. + """ + if not r_script_content.strip(): + raise ValueError("r_script_content cannot be empty.") + + output_files: List[Path] = [] + + # Validate input_rds_path if provided + if input_rds_path: + if not input_rds_path.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {input_rds_path}") + if not input_rds_path.suffix == ".rds": + raise ValueError(f"Input RDS file must have a '.rds' extension: {input_rds_path}") + + # Prepare output_rds_path if provided + if output_rds_path: + output_rds_path = output_rds_path.resolve() # Ensure absolute path + output_rds_path.parent.mkdir(parents=True, exist_ok=True) # Create parent dirs + if not output_rds_path.suffix == ".rds": + raise ValueError(f"Output RDS file must have a '.rds' extension: {output_rds_path}") + output_files.append(output_rds_path) + + # Create a temporary directory for the R script + with tempfile.TemporaryDirectory() as tmpdir: + tmpdir_path = Path(tmpdir) + + # Determine the actual working directory for the R process + actual_working_dir = working_directory if working_directory else tmpdir_path + actual_working_dir.mkdir(parents=True, exist_ok=True) # Ensure it exists + + r_script_file = tmpdir_path / "mia_script.R" + + # Construct the full R script content + full_r_script_lines = [ + "library(mia)", + "options(warn=-1)", # Suppress warnings for cleaner output + ] + + if input_rds_path: + full_r_script_lines.append(f"input_data <- readRDS('{input_rds_path.resolve()}')") + + full_r_script_lines.append(r_script_content) + + if output_rds_path: + # The user's script is expected to assign the result to 'output_data' + # We will then save 'output_data' to the specified path. + full_r_script_lines.append(f"if (exists('output_data')) {{ saveRDS(output_data, '{output_rds_path}') }} else {{ message('Warning: output_data variable not found, no RDS file saved.') }}") + + r_script_file.write_text("\n".join(full_r_script_lines)) + + command = ["Rscript", str(r_script_file)] + + try: + process = subprocess.run( + command, + cwd=actual_working_dir, + capture_output=True, + text=True, + check=True, + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Rscript execution failed with exit code {e.returncode}", + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: Rscript command not found. Is R installed and in PATH?", + "error": "Rscript not found", + "output_files": [], + } + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(p) for p in output_files], + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mia/app/bioconductor-mia_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mia/app/bioconductor-mia_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..99b94b2b3585c0e2b9bcb5a51ef13e43100c1d51 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mia/app/bioconductor-mia_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_manual_txt/mcp_bioconductor-mia/app/bioconductor-mia_server.py') +SERVER_NAME = 'biosci_bioconductor_mia' + + +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_manual_txt/mcp_bioconductor-mia/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mia/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mia/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mia/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mia/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..448e04866675ab483f33e61b5ce5db50c0d53b89 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mia/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-mia: + build: . + image: mcp-bioconductor-mia:latest + container_name: mcp-bioconductor-mia + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-mia + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mia/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mia/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9c6e488272f2e53a2ddb32b7b1d99e6cb5ad0ac0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mia/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-mia + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mia/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mia/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mia/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-moleculeexperiment/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-moleculeexperiment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ccec41ddd0d80bd47367f90dfd32979fcab14fc9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-moleculeexperiment/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-moleculeexperiment via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-moleculeexperiment -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-moleculeexperiment_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-moleculeexperiment_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-moleculeexperiment_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-moleculeexperiment/app/bioconductor-moleculeexperiment_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-moleculeexperiment/app/bioconductor-moleculeexperiment_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c728fcae90008f3f4770488c45ce168a59f04c34 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-moleculeexperiment/app/bioconductor-moleculeexperiment_server.py @@ -0,0 +1,370 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Union +import tempfile +import json + +@mcp.tool() +def read_xenium_to_molecule_experiment( + data_dir: str, + output_rds: str, + keep_unassigned: bool = True, +): + """ + Read 10X Xenium spatial transcriptomics data into a MoleculeExperiment RDS file. + + Args: + data_dir: Path to the directory containing Xenium output files (e.g., transcripts.csv.gz, cell_boundaries.csv.gz). + output_rds: Path where the resulting MoleculeExperiment object will be saved (.rds). + keep_unassigned: Whether to keep molecules not assigned to any cell. + """ + data_path = Path(data_dir) + if not data_path.is_dir(): + return {"error": f"Data directory {data_dir} does not exist."} + + r_code = f""" + library(MoleculeExperiment) + tryCatch({{ + me <- readXenium(data_dir = "{data_dir}", keep_unassigned = {str(keep_unassigned).upper()}) + saveRDS(me, "{output_rds}") + cat("Successfully saved MoleculeExperiment to {output_rds}") + }}, error = function(e) {{ + stop(e) + }}) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"readXenium(data_dir='{data_dir}')", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_rds] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def read_cosmx_to_molecule_experiment( + data_dir: str, + output_rds: str, + keep_unassigned: bool = True, +): + """ + Read Nanostring Cosmx SMI spatial transcriptomics data into a MoleculeExperiment RDS file. + + Args: + data_dir: Path to the directory containing Cosmx output files. + output_rds: Path where the resulting MoleculeExperiment object will be saved (.rds). + keep_unassigned: Whether to keep molecules not assigned to any cell. + """ + data_path = Path(data_dir) + if not data_path.is_dir(): + return {"error": f"Data directory {data_dir} does not exist."} + + r_code = f""" + library(MoleculeExperiment) + tryCatch({{ + me <- readCosmx(data_dir = "{data_dir}", keep_unassigned = {str(keep_unassigned).upper()}) + saveRDS(me, "{output_rds}") + cat("Successfully saved MoleculeExperiment to {output_rds}") + }}, error = function(e) {{ + stop(e) + }}) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"readCosmx(data_dir='{data_dir}')", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_rds] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def read_merscope_to_molecule_experiment( + data_dir: str, + output_rds: str, + keep_unassigned: bool = True, +): + """ + Read Vizgen Merscope spatial transcriptomics data into a MoleculeExperiment RDS file. + + Args: + data_dir: Path to the directory containing Merscope output files. + output_rds: Path where the resulting MoleculeExperiment object will be saved (.rds). + keep_unassigned: Whether to keep molecules not assigned to any cell. + """ + data_path = Path(data_dir) + if not data_path.is_dir(): + return {"error": f"Data directory {data_dir} does not exist."} + + r_code = f""" + library(MoleculeExperiment) + tryCatch({{ + me <- readMerscope(data_dir = "{data_dir}", keep_unassigned = {str(keep_unassigned).upper()}) + saveRDS(me, "{output_rds}") + cat("Successfully saved MoleculeExperiment to {output_rds}") + }}, error = function(e) {{ + stop(e) + }}) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"readMerscope(data_dir='{data_dir}')", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_rds] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def count_molecules( + input_rds: str, + output_rds: str, + assay_name: str = "counts", +): + """ + Aggregate molecules in a MoleculeExperiment object into a SpatialExperiment object (cell x gene counts). + + Args: + input_rds: Path to the input MoleculeExperiment RDS file. + output_rds: Path where the resulting SpatialExperiment object will be saved (.rds). + assay_name: Name of the assay to create in the output object. + """ + if not Path(input_rds).exists(): + return {"error": f"Input file {input_rds} does not exist."} + + r_code = f""" + library(MoleculeExperiment) + library(SpatialExperiment) + tryCatch({{ + me <- readRDS("{input_rds}") + se <- countMolecules(me, assay_name = "{assay_name}") + saveRDS(se, "{output_rds}") + cat("Successfully aggregated molecules into SpatialExperiment") + }}, error = function(e) {{ + stop(e) + }}) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"countMolecules(me, assay_name='{assay_name}')", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_rds] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def filter_molecules_by_gene( + input_rds: str, + output_rds: str, + genes: List[str], +): + """ + Filter a MoleculeExperiment object to keep only specific genes. + + Args: + input_rds: Path to the input MoleculeExperiment RDS file. + output_rds: Path where the filtered MoleculeExperiment object will be saved (.rds). + genes: List of gene names to keep. + """ + if not Path(input_rds).exists(): + return {"error": f"Input file {input_rds} does not exist."} + + genes_r = 'c("' + '", "'.join(genes) + '")' + + r_code = f""" + library(MoleculeExperiment) + tryCatch({{ + me <- readRDS("{input_rds}") + # Assuming molecules are stored in a way that allows standard subsetting + # MoleculeExperiment typically uses a list-like structure for molecules + me_filtered <- me[me$gene %in% {genes_r}, ] + saveRDS(me_filtered, "{output_rds}") + cat("Successfully filtered molecules") + }}, error = function(e) {{ + stop(e) + }}) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"me[me$gene %in% {genes_r}, ]", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_rds] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def plot_molecules_spatial( + input_rds: str, + output_image: str, + genes: Optional[List[str]] = None, + sample_id: Optional[str] = None, + point_size: float = 0.1, +): + """ + Visualize molecule locations from a MoleculeExperiment object. + + Args: + input_rds: Path to the input MoleculeExperiment RDS file. + output_image: Path to save the output plot (e.g., .png, .pdf). + genes: Optional list of specific genes to plot. If None, plots all. + sample_id: Optional sample identifier if multiple samples exist. + point_size: Size of the points in the plot. + """ + if not Path(input_rds).exists(): + return {"error": f"Input file {input_rds} does not exist."} + + genes_r = 'NULL' + if genes: + genes_r = 'c("' + '", "'.join(genes) + '")' + + sample_id_r = f'"{sample_id}"' if sample_id else "NULL" + + r_code = f""" + library(MoleculeExperiment) + library(ggplot2) + tryCatch({{ + me <- readRDS("{input_rds}") + p <- plotMolecules(me, genes = {genes_r}, sample_id = {sample_id_r}, point_size = {point_size}) + ggsave("{output_image}", plot = p, width = 10, height = 10) + cat("Successfully saved plot to {output_image}") + }}, error = function(e) {{ + stop(e) + }}) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "plotMolecules(...)", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_image] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def create_molecule_experiment_from_df( + molecules_csv: str, + output_rds: str, + boundaries_csv: Optional[str] = None, +): + """ + Create a MoleculeExperiment object from custom CSV files. + + Args: + molecules_csv: Path to a CSV containing molecule data (must have x, y, and gene columns). + output_rds: Path where the resulting MoleculeExperiment object will be saved (.rds). + boundaries_csv: Optional path to a CSV containing cell boundary coordinates. + """ + if not Path(molecules_csv).exists(): + return {"error": f"Molecules file {molecules_csv} does not exist."} + + r_code = f""" + library(MoleculeExperiment) + library(data.table) + tryCatch({{ + mols <- fread("{molecules_csv}") + bounds <- NULL + if ("{boundaries_csv}" != "None" && file.exists("{boundaries_csv}")) {{ + bounds <- fread("{boundaries_csv}") + }} + + me <- MoleculeExperiment(molecules = mols, boundaries = bounds) + saveRDS(me, "{output_rds}") + cat("Successfully created MoleculeExperiment from CSV") + }}, error = function(e) {{ + stop(e) + }}) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "MoleculeExperiment(molecules=mols, boundaries=bounds)", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_rds] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-moleculeexperiment/app/bioconductor-moleculeexperiment_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-moleculeexperiment/app/bioconductor-moleculeexperiment_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0e03b2039bbde76683af24351a181474ae6f75b0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-moleculeexperiment/app/bioconductor-moleculeexperiment_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_manual_txt/mcp_bioconductor-moleculeexperiment/app/bioconductor-moleculeexperiment_server.py') +SERVER_NAME = 'biosci_bioconductor_moleculeexperiment' + + +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_manual_txt/mcp_bioconductor-moleculeexperiment/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-moleculeexperiment/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-moleculeexperiment/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-moleculeexperiment/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-moleculeexperiment/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b8391b5a42b71f56f0fbadd46a4ebf46bb3be01b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-moleculeexperiment/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-moleculeexperiment: + build: . + image: mcp-bioconductor-moleculeexperiment:latest + container_name: mcp-bioconductor-moleculeexperiment + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-moleculeexperiment + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-moleculeexperiment/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-moleculeexperiment/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..915487a01bd02c680dcac5ec49ea08b92d891c21 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-moleculeexperiment/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-moleculeexperiment + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-moleculeexperiment/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-moleculeexperiment/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-moleculeexperiment/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mousegastrulationdata/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mousegastrulationdata/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d6eb58b034eb3ce33b7c5c8e61acab1a8d8f5cfc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mousegastrulationdata/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-mousegastrulationdata via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-mousegastrulationdata -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-mousegastrulationdata_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-mousegastrulationdata_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-mousegastrulationdata_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mousegastrulationdata/app/bioconductor-mousegastrulationdata_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mousegastrulationdata/app/bioconductor-mousegastrulationdata_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b8c5242c3de7aba5e50b931027bfa9ec0be2b76c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mousegastrulationdata/app/bioconductor-mousegastrulationdata_server.py @@ -0,0 +1,236 @@ +import subprocess +from pathlib import Path +from typing import Literal, Dict, List, Optional +import logging + +# Set up logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# @mcp.tool() +def mouse_gastrulation_data( + output_rds_path: Path, + dataset_type: Literal["chimera", "gastrulation", "seqFISH", "mesoderm", "pdx"] = "gastrulation", + use_ensembl_ids: bool = False, + cache_data: bool = True, +) -> Dict: + """ + Loads single-cell datasets from the MouseGastrulationData Bioconductor package. + + This tool wraps the main `MouseGastrulationData()` function from the R package. + It downloads and caches specified datasets from ExperimentHub and saves the + resulting SingleCellExperiment or SpatialExperiment object as an RDS file. + Requires R and the `bioconductor-mousegastrulationdata` package to be installed. + + Args: + output_rds_path: Path to save the output RDS file containing the data object. + dataset_type: The type of dataset to load. Defaults to "gastrulation". + use_ensembl_ids: If True, use Ensembl IDs for gene identifiers. Defaults to False (uses gene symbols). + cache_data: If True, cache the downloaded data locally using ExperimentHub. Defaults to True. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # Input validation + valid_types = ["chimera", "gastrulation", "seqFISH", "mesoderm", "pdx"] + if dataset_type not in valid_types: + raise ValueError(f"dataset_type must be one of {valid_types}, but got '{dataset_type}'") + + # R booleans need to be uppercase + r_ensembl = "TRUE" if use_ensembl_ids else "FALSE" + r_cache = "TRUE" if cache_data else "FALSE" + + # Construct the R script + r_script = f""" + # Suppress startup messages for cleaner output + suppressPackageStartupMessages(library(MouseGastrulationData)) + + # Load the data + sce <- MouseGastrulationData( + type = "{dataset_type}", + ensembl = {r_ensembl}, + location = {r_cache} + ) + + # Save the object to the specified file + saveRDS(sce, file = "{str(output_rds_path)}") + + # Print a success message to stdout + cat("Successfully loaded dataset '{dataset_type}' and saved to {str(output_rds_path)}\\n") + """ + + command = ["Rscript", "-e", r_script] + command_str = " ".join(command) + logger.info(f"Executing command: {command_str}") + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + stdout = process.stdout + stderr = process.stderr + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: Rscript not found. Please ensure R is installed and in your PATH.", + "output_files": [], + } + except subprocess.CalledProcessError as e: + logger.error(f"R script execution failed with return code {e.returncode}") + logger.error(f"Stderr: {e.stderr}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_rds_path)], + } + + +# @mcp.tool() +def atlas_sample_metadata(output_csv_path: Path) -> Dict: + """ + Retrieves the sample metadata data frame from the MouseGastrulationData package. + + This tool wraps the `AtlasSampleMetadata()` function and saves the resulting + data frame as a CSV file. Requires R and the `bioconductor-mousegastrulationdata` + package to be installed. + + Args: + output_csv_path: Path to save the output CSV file containing the metadata. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # Construct the R script + r_script = f""" + suppressPackageStartupMessages(library(MouseGastrulationData)) + + # Load the metadata + meta <- AtlasSampleMetadata() + + # Save the data frame to a CSV file + write.csv(meta, file = "{str(output_csv_path)}", row.names = FALSE, quote = TRUE) + + cat("Successfully retrieved sample metadata and saved to {str(output_csv_path)}\\n") + """ + + command = ["Rscript", "-e", r_script] + command_str = " ".join(command) + logger.info(f"Executing command: {command_str}") + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + stdout = process.stdout + stderr = process.stderr + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: Rscript not found. Please ensure R is installed and in your PATH.", + "output_files": [], + } + except subprocess.CalledProcessError as e: + logger.error(f"R script execution failed with return code {e.returncode}") + logger.error(f"Stderr: {e.stderr}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_csv_path)], + } + + +# @mcp.tool() +def embryo_color_map(output_csv_path: Path) -> Dict: + """ + Retrieves the color map for cell types in the mouse gastrulation atlas. + + This tool wraps the `EmbryoColorMap()` function. It converts the named + character vector of colors into a data frame and saves it as a CSV file. + Requires R and the `bioconductor-mousegastrulationdata` package to be installed. + + Args: + output_csv_path: Path to save the output CSV file containing the color map. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # Construct the R script + r_script = f""" + suppressPackageStartupMessages(library(MouseGastrulationData)) + + # Load the color map + cmap <- EmbryoColorMap() + + # Convert the named vector to a data frame for easy saving + cmap_df <- data.frame( + cell_type = names(cmap), + color_hex = as.character(cmap), + stringsAsFactors = FALSE + ) + + # Save the data frame to a CSV file + write.csv(cmap_df, file = "{str(output_csv_path)}", row.names = FALSE, quote = TRUE) + + cat("Successfully retrieved embryo color map and saved to {str(output_csv_path)}\\n") + """ + + command = ["Rscript", "-e", r_script] + command_str = " ".join(command) + logger.info(f"Executing command: {command_str}") + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + stdout = process.stdout + stderr = process.stderr + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: Rscript not found. Please ensure R is installed and in your PATH.", + "output_files": [], + } + except subprocess.CalledProcessError as e: + logger.error(f"R script execution failed with return code {e.returncode}") + logger.error(f"Stderr: {e.stderr}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_csv_path)], + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mousegastrulationdata/app/bioconductor-mousegastrulationdata_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mousegastrulationdata/app/bioconductor-mousegastrulationdata_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c1253d07a769b8ab0189fce5a3a6c6adfe31bda6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mousegastrulationdata/app/bioconductor-mousegastrulationdata_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_manual_txt/mcp_bioconductor-mousegastrulationdata/app/bioconductor-mousegastrulationdata_server.py') +SERVER_NAME = 'biosci_bioconductor_mousegastrulationdata' + + +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_manual_txt/mcp_bioconductor-mousegastrulationdata/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mousegastrulationdata/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mousegastrulationdata/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mousegastrulationdata/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mousegastrulationdata/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..12f8aa4ebdf7d15c7c3e7ca3d4b400cde0a43c59 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mousegastrulationdata/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-mousegastrulationdata: + build: . + image: mcp-bioconductor-mousegastrulationdata:latest + container_name: mcp-bioconductor-mousegastrulationdata + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-mousegastrulationdata + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mousegastrulationdata/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mousegastrulationdata/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e38088132dfda41eea863df792b826fb2cbe2368 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mousegastrulationdata/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-mousegastrulationdata + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mousegastrulationdata/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mousegastrulationdata/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mousegastrulationdata/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mspurity/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mspurity/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b693edfda5ebe7e256e6e03048b2b6fb76e37ff7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mspurity/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-mspurity via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-mspurity -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-mspurity_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-mspurity_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-mspurity_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mspurity/app/bioconductor-mspurity_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mspurity/app/bioconductor-mspurity_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6081d9589a0cf28b4d8e45b6fb2a27ff314bfdb6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mspurity/app/bioconductor-mspurity_server.py @@ -0,0 +1,312 @@ +import subprocess +import os +import tempfile +from pathlib import Path +from typing import Optional, List + +@mcp.tool() +def mspurity_purity_a( + ms_files: List[str], + output_rds: str, + cores: int = 1, + mz_purity_limit: float = 0.0, + iw_low: float = -0.5, + iw_high: float = 0.5, + nearest: bool = True, + v: bool = True, + offsets: bool = False +): + """ + Assess precursor purity for LC-MS/MS data. Calculates the percentage of the + intensity in the isolation window that is attributed to the precursor ion. + + Args: + ms_files: List of paths to LC-MS/MS files (mzML, mzXML). + output_rds: Path to save the resulting purityA object as an RDS file. + cores: Number of CPU cores for parallel processing. + mz_purity_limit: Purity threshold for filtering. + iw_low: Lower offset for isolation window (e.g., -0.5). + iw_high: Upper offset for isolation window (e.g., 0.5). + nearest: Whether to use the nearest scan for purity calculation. + v: Verbose output. + offsets: Whether to use isolation window offsets from the file metadata. + """ + for f in ms_files: + if not Path(f).exists(): + raise FileNotFoundError(f"Input file not found: {f}") + + out_path = Path(output_rds) + out_path.parent.mkdir(parents=True, exist_ok=True) + + ms_files_r = ", ".join([f'"{f}"' for f in ms_files]) + r_script = f""" + library(msPurity) + pa <- purityA(fileList = c({ms_files_r}), + cores = {cores}, + mz_purity_limit = {mz_purity_limit}, + iw_low = {iw_low}, + iw_high = {iw_high}, + nearest = {"TRUE" if nearest else "FALSE"}, + v = {"TRUE" if v else "FALSE"}, + offsets = {"TRUE" if offsets else "FALSE"}) + saveRDS(pa, file = "{output_rds}") + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + try: + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": " ".join(e.cmd) + } + finally: + if os.path.exists(tmp_path): + os.remove(tmp_path) + +@mcp.tool() +def mspurity_purity_x( + ms_files: List[str], + output_rds: str, + cores: int = 1, + mz_purity_limit: float = 0.0, + v: bool = True +): + """ + Assess precursor purity for Direct Infusion (DI-MS/MS) data. + + Args: + ms_files: List of paths to DI-MS/MS files. + output_rds: Path to save the resulting purityX object as an RDS file. + cores: Number of CPU cores. + mz_purity_limit: Purity threshold. + v: Verbose output. + """ + for f in ms_files: + if not Path(f).exists(): + raise FileNotFoundError(f"Input file not found: {f}") + + ms_files_r = ", ".join([f'"{f}"' for f in ms_files]) + r_script = f""" + library(msPurity) + px <- purityX(fileList = c({ms_files_r}), + cores = {cores}, + mz_purity_limit = {mz_purity_limit}, + v = {"TRUE" if v else "FALSE"}) + saveRDS(px, file = "{output_rds}") + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + try: + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_rds] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + finally: + if os.path.exists(tmp_path): + os.remove(tmp_path) + +@mcp.tool() +def mspurity_average_intensities( + pa_rds: str, + output_rds: str, + avg_mz_err: float = 0.005, + avg_rt_err: float = 10.0, + v: bool = True +): + """ + Average the intensities of MS/MS spectra across scans within a purityA object. + + Args: + pa_rds: Path to the input purityA RDS file. + output_rds: Path to save the updated purityA object. + avg_mz_err: m/z error for averaging. + avg_rt_err: Retention time error for averaging (seconds). + v: Verbose output. + """ + if not Path(pa_rds).exists(): + raise FileNotFoundError(f"Input RDS file not found: {pa_rds}") + + r_script = f""" + library(msPurity) + pa <- readRDS("{pa_rds}") + pa <- averageIntensities(pa, avg_mz_err = {avg_mz_err}, avg_rt_err = {avg_rt_err}, v = {"TRUE" if v else "FALSE"}) + saveRDS(pa, file = "{output_rds}") + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + try: + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "output_files": [output_rds] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + finally: + if os.path.exists(tmp_path): + os.remove(tmp_path) + +@mcp.tool() +def mspurity_create_database( + pa_rds: str, + db_path: str, + xset_rds: Optional[str] = None, + v: bool = True +): + """ + Create a SQLite database from a purityA object, optionally linking with XCMS results. + + Args: + pa_rds: Path to the input purityA RDS file. + db_path: Path to the output SQLite database file. + xset_rds: Optional path to an XCMS xset or XcmsExperiment RDS file. + v: Verbose output. + """ + if not Path(pa_rds).exists(): + raise FileNotFoundError(f"Input RDS file not found: {pa_rds}") + + xset_code = f'xset <- readRDS("{xset_rds}")' if xset_rds else "xset <- NULL" + + r_script = f""" + library(msPurity) + pa <- readRDS("{pa_rds}") + {xset_code} + createDatabase(pa, xset = xset, dbName = "{db_path}", v = {"TRUE" if v else "FALSE"}) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + try: + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "output_files": [db_path] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + finally: + if os.path.exists(tmp_path): + os.remove(tmp_path) + +@mcp.tool() +def mspurity_spectral_matching( + pa_rds: str, + output_rds: str, + lib_path: str, + ms_err: float = 0.01, + v: bool = True +): + """ + Perform spectral matching against a library for the MS/MS spectra in a purityA object. + + Args: + pa_rds: Path to the input purityA RDS file. + output_rds: Path to save the purityA object with matching results. + lib_path: Path to the spectral library (RDS or SQLite). + ms_err: m/z error for matching. + v: Verbose output. + """ + if not Path(pa_rds).exists(): + raise FileNotFoundError(f"Input RDS file not found: {pa_rds}") + if not Path(lib_path).exists(): + raise FileNotFoundError(f"Library file not found: {lib_path}") + + r_script = f""" + library(msPurity) + pa <- readRDS("{pa_rds}") + pa <- spectralMatching(pa, lib_path = "{lib_path}", ms_err = {ms_err}, v = {"TRUE" if v else "FALSE"}) + saveRDS(pa, file = "{output_rds}") + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + try: + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "output_files": [output_rds] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + finally: + if os.path.exists(tmp_path): + os.remove(tmp_path) + +@mcp.tool() +def mspurity_filter_frag( + pa_rds: str, + output_rds: str, + min_int: float = 0.0, + v: bool = True +): + """ + Filter fragmentation spectra based on intensity or other criteria. + + Args: + pa_rds: Path to the input purityA RDS file. + output_rds: Path to save the filtered purityA object. + min_int: Minimum intensity threshold for peaks. + v: Verbose output. + """ + if not Path(pa_rds).exists(): + raise FileNotFoundError(f"Input RDS file not found: {pa_rds}") + + r_script = f""" + library(msPurity) + pa <- readRDS("{pa_rds}") + pa <- filterFrag(pa, min_int = {min_int}, v = {"TRUE" if v else "FALSE"}) + saveRDS(pa, file = "{output_rds}") + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + try: + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "output_files": [output_rds] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + finally: + if os.path.exists(tmp_path): + os.remove(tmp_path) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mspurity/app/bioconductor-mspurity_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mspurity/app/bioconductor-mspurity_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4ca69f1cc507a14750b3f551f3a4b055947651c4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mspurity/app/bioconductor-mspurity_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_manual_txt/mcp_bioconductor-mspurity/app/bioconductor-mspurity_server.py') +SERVER_NAME = 'biosci_bioconductor_mspurity' + + +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_manual_txt/mcp_bioconductor-mspurity/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mspurity/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mspurity/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mspurity/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mspurity/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c5b434c3bcdfeca344c322cc39bdf54a145647cf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mspurity/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-mspurity: + build: . + image: mcp-bioconductor-mspurity:latest + container_name: mcp-bioconductor-mspurity + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-mspurity + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mspurity/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mspurity/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0bac186c238387cb25135baf8c703b4d5e9bef8a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mspurity/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-mspurity + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mspurity/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mspurity/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mspurity/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multiassayexperiment/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multiassayexperiment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5fd3bc9dcf3ea6f60926861e1e9b59a8befef3a3 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multiassayexperiment/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-multiassayexperiment via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-multiassayexperiment -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-multiassayexperiment_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-multiassayexperiment_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-multiassayexperiment_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multiassayexperiment/app/bioconductor-multiassayexperiment_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multiassayexperiment/app/bioconductor-multiassayexperiment_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e9c34295df84b4f495f14221300924e01d22bc69 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multiassayexperiment/app/bioconductor-multiassayexperiment_server.py @@ -0,0 +1,334 @@ +import subprocess +import tempfile +import shlex +from pathlib import Path +from typing import List, Optional, Dict + +# Helper function to convert a Python list of strings to an R character vector string +def _python_list_to_r_vector(py_list: List[str]) -> str: + """Converts a Python list of strings to an R character vector string e.g., c("a", "b").""" + if not py_list: + return "c()" + quoted_items = [f'"{item}"' for item in py_list] + return f"c({', '.join(quoted_items)})" + +# Helper function to run an R script and handle errors +def _run_r_script(r_script_content: str, command_name: str) -> Dict[str, str]: + """ + Writes R content to a temporary file, executes it, and handles I/O and errors. + """ + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_path_str = r_script_file.name + r_script_file.write(r_script_content) + + cmd = ["Rscript", r_script_path_str] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + } + except FileNotFoundError: + raise RuntimeError("Rscript executable not found. Please ensure R is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + error_message = ( + f"{command_name} failed. R script execution returned a non-zero exit code {e.returncode}.\n" + f"Stderr:\n{e.stderr}\n" + f"Stdout:\n{e.stdout}" + ) + raise RuntimeError(error_message) + finally: + # Ensure the temporary script is always removed + Path(r_script_path_str).unlink() + +# @mcp.tool() +def create_multiassayexperiment( + experiments: List[Path], + experiment_names: List[str], + coldata: Path, + samplemap: Path, + output_rds: Path, + metadata_json: Optional[Path] = None, +) -> Dict: + """ + Creates a MultiAssayExperiment object from component files and saves it as an RDS file. + This tool is a wrapper for the R/Bioconductor package 'MultiAssayExperiment'. + + Args: + experiments: List of paths to experiment data files (CSV format, with row names in the first column). + experiment_names: List of names for each experiment, corresponding to the 'experiments' list. + coldata: Path to the sample metadata file (colData) in CSV format. + samplemap: Path to the sample map file in CSV format. + output_rds: Path to save the output MultiAssayExperiment object in RDS format. + metadata_json: Optional path to a JSON file containing metadata for the experiment. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output RDS file. + """ + # --- Input Validation --- + if len(experiments) != len(experiment_names): + raise ValueError("The number of experiment files must match the number of experiment names.") + if not experiments: + raise ValueError("At least one experiment file must be provided.") + + for exp_file in experiments: + if not exp_file.is_file(): + raise FileNotFoundError(f"Experiment file not found: {exp_file}") + if not coldata.is_file(): + raise FileNotFoundError(f"colData file not found: {coldata}") + if not samplemap.is_file(): + raise FileNotFoundError(f"sampleMap file not found: {samplemap}") + if metadata_json and not metadata_json.is_file(): + raise FileNotFoundError(f"Metadata JSON file not found: {metadata_json}") + + output_rds.parent.mkdir(parents=True, exist_ok=True) + + # --- R Script Generation --- + exp_readers = "\n ".join( + f'exp_list[["{name}"]] <- as.matrix(read.csv({shlex.quote(str(path))}, row.names=1, check.names=FALSE))' + for name, path in zip(experiment_names, experiments) + ) + + meta_loader = "meta <- list()" + if metadata_json: + meta_loader = f""" + if (!requireNamespace("jsonlite", quietly = TRUE)) install.packages("jsonlite", repos="http://cran.us.r-project.org") + meta <- jsonlite::fromJSON({shlex.quote(str(metadata_json))}) + """ + + r_script = f""" + # Ensure BiocManager and required packages are installed + if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager", repos="http://cran.us.r-project.org") + pkgs <- c("MultiAssayExperiment", "S4Vectors") + for (pkg in pkgs) {{ + if (!requireNamespace(pkg, quietly = TRUE)) BiocManager::install(pkg, update=FALSE) + }} + + library(MultiAssayExperiment) + library(S4Vectors) + + # Create ExperimentList + exp_list <- list() + {exp_readers} + experiments_list_obj <- ExperimentList(exp_list) + + # Read colData and sampleMap + coldata_df <- read.csv({shlex.quote(str(coldata))}, row.names=1, check.names=FALSE) + coldata_s4 <- DataFrame(coldata_df, check.names=FALSE) + + samplemap_df <- read.csv({shlex.quote(str(samplemap))}, check.names=FALSE) + samplemap_s4 <- DataFrame(samplemap_df, check.names=FALSE) + + # Load metadata + {meta_loader} + + # Create MultiAssayExperiment object + mae <- MultiAssayExperiment( + experiments = experiments_list_obj, + colData = coldata_s4, + sampleMap = samplemap_s4, + metadata = meta + ) + + # Save the object + saveRDS(mae, file = {shlex.quote(str(output_rds))}) + print("MultiAssayExperiment object created and saved successfully.") + """ + + # --- Subprocess Execution --- + exec_result = _run_r_script(r_script, "create_multiassayexperiment") + + return { + "command_executed": exec_result["command_executed"], + "stdout": exec_result["stdout"], + "stderr": exec_result["stderr"], + "output_files": [str(output_rds)], + } + +# @mcp.tool() +def subset_by_assay( + input_mae_rds: Path, + output_mae_rds: Path, + assays: List[str], +) -> Dict: + """ + Subsets a MultiAssayExperiment object by assay names. + + Args: + input_mae_rds: Path to the input MultiAssayExperiment RDS file. + output_mae_rds: Path to save the subsetted MultiAssayExperiment RDS file. + assays: A list of assay names to keep in the object. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output RDS file. + """ + # --- Input Validation --- + if not input_mae_rds.is_file(): + raise FileNotFoundError(f"Input MAE file not found: {input_mae_rds}") + if not assays: + raise ValueError("The 'assays' list cannot be empty.") + output_mae_rds.parent.mkdir(parents=True, exist_ok=True) + + # --- R Script Generation --- + assays_r_vector = _python_list_to_r_vector(assays) + r_script = f""" + library(MultiAssayExperiment) + mae <- readRDS({shlex.quote(str(input_mae_rds))}) + assays_to_keep <- {assays_r_vector} + mae_subset <- mae[,,assays_to_keep] + saveRDS(mae_subset, file = {shlex.quote(str(output_mae_rds))}) + print("Subsetting by assay completed successfully.") + """ + + # --- Subprocess Execution --- + exec_result = _run_r_script(r_script, "subset_by_assay") + + return { + "command_executed": exec_result["command_executed"], + "stdout": exec_result["stdout"], + "stderr": exec_result["stderr"], + "output_files": [str(output_mae_rds)], + } + +# @mcp.tool() +def subset_by_sample( + input_mae_rds: Path, + output_mae_rds: Path, + samples: List[str], +) -> Dict: + """ + Subsets a MultiAssayExperiment object by sample names (colData rownames). + + Args: + input_mae_rds: Path to the input MultiAssayExperiment RDS file. + output_mae_rds: Path to save the subsetted MultiAssayExperiment RDS file. + samples: A list of sample names (from colData) to keep. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output RDS file. + """ + # --- Input Validation --- + if not input_mae_rds.is_file(): + raise FileNotFoundError(f"Input MAE file not found: {input_mae_rds}") + if not samples: + raise ValueError("The 'samples' list cannot be empty.") + output_mae_rds.parent.mkdir(parents=True, exist_ok=True) + + # --- R Script Generation --- + samples_r_vector = _python_list_to_r_vector(samples) + r_script = f""" + library(MultiAssayExperiment) + mae <- readRDS({shlex.quote(str(input_mae_rds))}) + samples_to_keep <- {samples_r_vector} + mae_subset <- mae[,samples_to_keep,] + saveRDS(mae_subset, file = {shlex.quote(str(output_mae_rds))}) + print("Subsetting by sample completed successfully.") + """ + + # --- Subprocess Execution --- + exec_result = _run_r_script(r_script, "subset_by_sample") + + return { + "command_executed": exec_result["command_executed"], + "stdout": exec_result["stdout"], + "stderr": exec_result["stderr"], + "output_files": [str(output_mae_rds)], + } + +# @mcp.tool() +def subset_by_row( + input_mae_rds: Path, + output_mae_rds: Path, + rows: List[str], +) -> Dict: + """ + Subsets a MultiAssayExperiment object by row/feature names. + + Args: + input_mae_rds: Path to the input MultiAssayExperiment RDS file. + output_mae_rds: Path to save the subsetted MultiAssayExperiment RDS file. + rows: A list of row/feature names to keep. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output RDS file. + """ + # --- Input Validation --- + if not input_mae_rds.is_file(): + raise FileNotFoundError(f"Input MAE file not found: {input_mae_rds}") + if not rows: + raise ValueError("The 'rows' list cannot be empty.") + output_mae_rds.parent.mkdir(parents=True, exist_ok=True) + + # --- R Script Generation --- + rows_r_vector = _python_list_to_r_vector(rows) + r_script = f""" + library(MultiAssayExperiment) + mae <- readRDS({shlex.quote(str(input_mae_rds))}) + rows_to_keep <- {rows_r_vector} + mae_subset <- mae[rows_to_keep,,] + saveRDS(mae_subset, file = {shlex.quote(str(output_mae_rds))}) + print("Subsetting by row completed successfully.") + """ + + # --- Subprocess Execution --- + exec_result = _run_r_script(r_script, "subset_by_row") + + return { + "command_executed": exec_result["command_executed"], + "stdout": exec_result["stdout"], + "stderr": exec_result["stderr"], + "output_files": [str(output_mae_rds)], + } + +# @mcp.tool() +def export_long_format( + input_mae_rds: Path, + output_csv: Path, + coldata_cols: Optional[List[str]] = None, +) -> Dict: + """ + Exports data from a MultiAssayExperiment object to a long-format CSV file. + + Args: + input_mae_rds: Path to the input MultiAssayExperiment RDS file. + output_csv: Path to save the output long-format data in CSV format. + coldata_cols: Optional list of column names from colData to include in the output. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output CSV file. + """ + # --- Input Validation --- + if not input_mae_rds.is_file(): + raise FileNotFoundError(f"Input MAE file not found: {input_mae_rds}") + output_csv.parent.mkdir(parents=True, exist_ok=True) + + # --- R Script Generation --- + coldata_vars = "NULL" + if coldata_cols: + coldata_vars = _python_list_to_r_vector(coldata_cols) + + r_script = f""" + library(MultiAssayExperiment) + mae <- readRDS({shlex.quote(str(input_mae_rds))}) + long_df <- longFormat(mae, colDataCols = {coldata_vars}) + write.csv(long_df, file = {shlex.quote(str(output_csv))}, row.names = FALSE) + print("Export to long format CSV completed successfully.") + """ + + # --- Subprocess Execution --- + exec_result = _run_r_script(r_script, "export_long_format") + + return { + "command_executed": exec_result["command_executed"], + "stdout": exec_result["stdout"], + "stderr": exec_result["stderr"], + "output_files": [str(output_csv)], + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multiassayexperiment/app/bioconductor-multiassayexperiment_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multiassayexperiment/app/bioconductor-multiassayexperiment_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3406f08181e3023f8f58d3347c74f8d23dd78d65 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multiassayexperiment/app/bioconductor-multiassayexperiment_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_manual_txt/mcp_bioconductor-multiassayexperiment/app/bioconductor-multiassayexperiment_server.py') +SERVER_NAME = 'biosci_bioconductor_multiassayexperiment' + + +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_manual_txt/mcp_bioconductor-multiassayexperiment/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multiassayexperiment/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multiassayexperiment/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multiassayexperiment/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multiassayexperiment/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..01a8d206024f451005a92d57776aec5d0da06aca --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multiassayexperiment/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-multiassayexperiment: + build: . + image: mcp-bioconductor-multiassayexperiment:latest + container_name: mcp-bioconductor-multiassayexperiment + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-multiassayexperiment + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multiassayexperiment/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multiassayexperiment/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ab0c20e1007cb60d742fd97346f24742a730e275 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multiassayexperiment/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-multiassayexperiment + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multiassayexperiment/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multiassayexperiment/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multiassayexperiment/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multtest/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multtest/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..50b12bc8047f8991312c0813274193fff3435c15 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_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_manual_txt/mcp_bioconductor-multtest/app/bioconductor-multtest_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multtest/app/bioconductor-multtest_server.py new file mode 100644 index 0000000000000000000000000000000000000000..77eada11744f8070337a4c33026cf6edbe3a5b1d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multtest/app/bioconductor-multtest_server.py @@ -0,0 +1,293 @@ +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(): + def decorator(f): + return f + return decorator + +mcp = type("mcp", (), {"tool": tool})() + + +@mcp.tool() +def multtest_rawp2adjp( + raw_p_values_file: Path, + output_file: Path, + procedure: str, + alpha: float = 0.05, +) -> dict: + """ + Computes adjusted p-values from a vector of raw (unadjusted) p-values + using various multiple testing procedures. This tool is a wrapper for the + `mt.rawp2adjp` function from the Bioconductor `multtest` package. + + Args: + raw_p_values_file: Path to a single-column file containing raw p-values. + output_file: Path to the output file where adjusted p-values will be saved. + procedure: The multiple testing procedure to use. + Valid options: "Bonferroni", "Holm", "Hochberg", "SidakSS", + "SidakSD", "BH", "BY", "ABH", "TSBH". + alpha: The significance level for procedures that require it (e.g., step-down methods). + Must be between 0 and 1. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not raw_p_values_file.is_file(): + raise FileNotFoundError(f"Input file not found: {raw_p_values_file}") + + ALLOWED_PROCEDURES = [ + "Bonferroni", "Holm", "Hochberg", "SidakSS", "SidakSD", + "BH", "BY", "ABH", "TSBH" + ] + if procedure not in ALLOWED_PROCEDURES: + raise ValueError( + f"Invalid procedure '{procedure}'. " + f"Choose from: {', '.join(ALLOWED_PROCEDURES)}" + ) + + if not (0 < alpha < 1): + raise ValueError(f"alpha must be between 0 and 1, but got {alpha}.") + + # Ensure output directory exists + output_file.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + # This assumes a hypothetical command-line wrapper `multtest-cli` for the R package. + cmd = [ + "multtest-cli", + "rawp2adjp", + "--pvals", str(raw_p_values_file), + "--proc", procedure, + "--alpha", str(alpha), + "--out", str(output_file), + ] + + # --- Subprocess Execution --- + command_executed = shlex.join(cmd) + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + except FileNotFoundError: + raise RuntimeError("`multtest-cli` command not found. Is the tool installed and in your PATH?") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Tool execution failed.", + "return_code": e.returncode, + } + + # --- Structured Result Return --- + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file)], + } + + +@mcp.tool() +def multtest_maxt( + data_file: Path, + class_labels_file: Path, + output_file: Path, + test: str, + side: str = "abs", + n_permutations: int = 1000, + seed: Optional[int] = None, +) -> dict: + """ + Performs a permutation test based on maxT-statistics to adjust p-values for + multiple hypothesis testing. This is a wrapper for the `mt.maxT` function + from the Bioconductor `multtest` package. + + Args: + data_file: Path to the input data matrix (e.g., CSV/TSV), with features + in rows and samples in columns. + class_labels_file: Path to a file containing class labels for each sample (column) + in the data file. + output_file: Path to the output file for the results. + test: The test statistic to use. Valid options: "t", "t.equalvar", + "wilcoxon", "f", "pairt", "blockf". + side: The alternative hypothesis. Valid options: "abs" (two-sided), + "upper" (greater), "lower" (less). + n_permutations: The number of permutations to perform. + seed: An optional integer seed for the random number generator for reproducibility. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a list of 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}") + + ALLOWED_TESTS = ["t", "t.equalvar", "wilcoxon", "f", "pairt", "blockf"] + if test not in ALLOWED_TESTS: + raise ValueError( + f"Invalid test '{test}'. Choose from: {', '.join(ALLOWED_TESTS)}" + ) + + ALLOWED_SIDES = ["abs", "upper", "lower"] + if side not in ALLOWED_SIDES: + raise ValueError( + f"Invalid side '{side}'. Choose from: {', '.join(ALLOWED_SIDES)}" + ) + + if n_permutations <= 0: + raise ValueError("n_permutations must be a positive integer.") + + # Ensure output directory exists + output_file.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd: List[str] = [ + "multtest-cli", + "maxt", + "--data", str(data_file), + "--labels", str(class_labels_file), + "--out", str(output_file), + "--test", test, + "--side", side, + "--nperm", str(n_permutations), + ] + if seed is not None: + cmd.extend(["--seed", str(seed)]) + + # --- Subprocess Execution --- + command_executed = shlex.join(cmd) + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + except FileNotFoundError: + raise RuntimeError("`multtest-cli` command not found. Is the tool installed and in your PATH?") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Tool execution failed.", + "return_code": e.returncode, + } + + # --- Structured Result Return --- + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file)], + } + + +@mcp.tool() +def multtest_minp( + data_file: Path, + class_labels_file: Path, + output_file: Path, + test: str, + side: str = "abs", + n_permutations: int = 1000, + seed: Optional[int] = None, +) -> dict: + """ + Performs a permutation test based on minP-statistics to adjust p-values for + multiple hypothesis testing. This is a wrapper for the `mt.minP` function + from the Bioconductor `multtest` package. + + Args: + data_file: Path to the input data matrix (e.g., CSV/TSV), with features + in rows and samples in columns. + class_labels_file: Path to a file containing class labels for each sample (column) + in the data file. + output_file: Path to the output file for the results. + test: The test statistic to use. Valid options: "t", "t.equalvar", + "wilcoxon", "f", "pairt", "blockf". + side: The alternative hypothesis. Valid options: "abs" (two-sided), + "upper" (greater), "lower" (less). + n_permutations: The number of permutations to perform. + seed: An optional integer seed for the random number generator for reproducibility. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a list of 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}") + + ALLOWED_TESTS = ["t", "t.equalvar", "wilcoxon", "f", "pairt", "blockf"] + if test not in ALLOWED_TESTS: + raise ValueError( + f"Invalid test '{test}'. Choose from: {', '.join(ALLOWED_TESTS)}" + ) + + ALLOWED_SIDES = ["abs", "upper", "lower"] + if side not in ALLOWED_SIDES: + raise ValueError( + f"Invalid side '{side}'. Choose from: {', '.join(ALLOWED_SIDES)}" + ) + + if n_permutations <= 0: + raise ValueError("n_permutations must be a positive integer.") + + # Ensure output directory exists + output_file.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd: List[str] = [ + "multtest-cli", + "minp", + "--data", str(data_file), + "--labels", str(class_labels_file), + "--out", str(output_file), + "--test", test, + "--side", side, + "--nperm", str(n_permutations), + ] + if seed is not None: + cmd.extend(["--seed", str(seed)]) + + # --- Subprocess Execution --- + command_executed = shlex.join(cmd) + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + except FileNotFoundError: + raise RuntimeError("`multtest-cli` command not found. Is the tool installed and in your PATH?") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Tool execution failed.", + "return_code": e.returncode, + } + + # --- Structured Result Return --- + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file)], + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multtest/app/bioconductor-multtest_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multtest/app/bioconductor-multtest_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..59e25d55da1d59db6f312076a019db71cb54a681 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_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_manual_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_manual_txt/mcp_bioconductor-multtest/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multtest/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multtest/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multtest/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multtest/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..6bc264787603248074bf059e0399068f89fd919a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_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_manual_txt/mcp_bioconductor-multtest/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multtest/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f686d7fe95f83931ab22a680f054decfb3dd5756 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_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_manual_txt/mcp_bioconductor-multtest/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multtest/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-multtest/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mzr/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mzr/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-mzr/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-nnsvg/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-nnsvg/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..86a9d3cb5360bb8b481fd41dcb57b2c31278be64 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-nnsvg/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-nnsvg via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-nnsvg -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-nnsvg_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-nnsvg_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-nnsvg_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-nnsvg/app/bioconductor-nnsvg_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-nnsvg/app/bioconductor-nnsvg_server.py new file mode 100644 index 0000000000000000000000000000000000000000..84626c19eeac653d81f3678189424bb7366ee46f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-nnsvg/app/bioconductor-nnsvg_server.py @@ -0,0 +1,140 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional + +# Mock mcp decorator for standalone execution +class mcp: + def tool(func): + return func + +@mcp.tool +def nnsvg( + input_rds: Path, + output_rds: Path, + assay_name: str = "logcounts", + covariates_file: Optional[Path] = None, + n_neighbors: int = 10, + n_omp_threads: int = 1, + verbose: bool = True, +): + """ + Runs nnSVG to identify spatially variable genes in SpatialExperiment data. + + This tool is a wrapper for the nnSVG() function from the Bioconductor package 'nnSVG'. + It identifies and ranks spatially variable genes (SVGs) in spatially-resolved + transcriptomics data using a scalable nearest-neighbor Gaussian process model. + + Args: + input_rds: Path to the input SpatialExperiment object saved as an RDS file. + This object should contain expression data and spatial coordinates. + output_rds: Path to save the output RDS file. The original SpatialExperiment + object will be saved here with nnSVG results added to its rowData. + assay_name: Name of the assay in the input object containing the expression + values (e.g., 'logcounts', 'counts'). Defaults to "logcounts". + covariates_file: Optional path to a CSV file containing covariates. The first + column should contain sample names matching the column names + in the SpatialExperiment object. The remaining columns are + treated as covariates. + n_neighbors: Number of nearest neighbors to use for the Gaussian process model. + Defaults to 10. + n_omp_threads: Number of threads for parallelization. Defaults to 1. + verbose: Whether to print progress messages from the R script. Defaults to True. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a list + of output files. + """ + # 1. Input Validation + if not input_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {input_rds}") + if covariates_file and not covariates_file.is_file(): + raise FileNotFoundError(f"Covariates file not found: {covariates_file}") + if n_neighbors <= 0: + raise ValueError("n_neighbors must be a positive integer.") + if n_omp_threads <= 0: + raise ValueError("n_omp_threads must be a positive integer.") + + # 2. Construct the R script + # Using as_posix() ensures cross-platform path compatibility for R + r_script_parts = [ + "library(nnSVG)", + "library(SpatialExperiment)", + f"spe <- readRDS('{input_rds.as_posix()}')", + ] + + covariates_r_code = "covariates_matrix <- NULL" + if covariates_file: + covariates_r_code = f""" +cov_df <- read.csv('{covariates_file.as_posix()}', row.names = 1, header = TRUE) +# Ensure order of samples in covariates matches the SpatialExperiment object +cov_df <- cov_df[colnames(spe), , drop = FALSE] +covariates_matrix <- model.matrix(~ ., data = cov_df) +# Remove intercept column if it exists, as it's often not needed +if ('(Intercept)' %in% colnames(covariates_matrix)) {{ + covariates_matrix <- covariates_matrix[, colnames(covariates_matrix) != '(Intercept)', drop = FALSE] +}} +# If only the intercept was present, set covariates to NULL +if (ncol(covariates_matrix) == 0) {{ + covariates_matrix <- NULL +}} +""" + r_script_parts.append(covariates_r_code) + + r_script_parts.append( + f""" +# Run the main nnSVG function +spe_with_results <- nnSVG( + input = spe, + assay_name = '{assay_name}', + covariates = covariates_matrix, + n_neighbors = {n_neighbors}, + n_omp_threads = {n_omp_threads}, + verbose = {'TRUE' if verbose else 'FALSE'} +) + +# Save the updated object to the output file +saveRDS(spe_with_results, file = '{output_rds.as_posix()}') + +cat("nnSVG analysis complete. Results saved to {output_rds.as_posix()}\\n") +""" + ) + + r_script = "\n".join(r_script_parts) + + # 3. Execute the R script + cmd = [] + try: + with tempfile.TemporaryDirectory() as temp_dir: + r_script_path = Path(temp_dir) / "run_nnsvg.R" + with open(r_script_path, "w") as f: + f.write(r_script) + + cmd = ["Rscript", str(r_script_path)] + + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_rds)] + } + + except FileNotFoundError: + # This error occurs if 'Rscript' is not in the system's PATH + raise RuntimeError("Rscript command not found. Please ensure R is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + # This error occurs if the R script fails + error_message = ( + f"The R script failed with return code {e.returncode}.\n" + f"Command: {' '.join(cmd)}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) + raise RuntimeError(error_message) from e diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-nnsvg/app/bioconductor-nnsvg_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-nnsvg/app/bioconductor-nnsvg_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4a8ce50575902960ab77aaafd906248ff856ad29 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-nnsvg/app/bioconductor-nnsvg_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_manual_txt/mcp_bioconductor-nnsvg/app/bioconductor-nnsvg_server.py') +SERVER_NAME = 'biosci_bioconductor_nnsvg' + + +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_manual_txt/mcp_bioconductor-nnsvg/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-nnsvg/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-nnsvg/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-nnsvg/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-nnsvg/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..eb5fe2b6efb56c0ed0f12c50ae83ca8d4a776580 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-nnsvg/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-nnsvg: + build: . + image: mcp-bioconductor-nnsvg:latest + container_name: mcp-bioconductor-nnsvg + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-nnsvg + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-nnsvg/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-nnsvg/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b463df348f53cc893866b00bc7c7169816e73b7a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-nnsvg/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-nnsvg + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-nnsvg/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-nnsvg/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-nnsvg/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-noiseq/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-noiseq/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0236be3dad1e86c4a1134b86ae90e82892bbbc78 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_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_manual_txt/mcp_bioconductor-noiseq/app/bioconductor-noiseq_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-noiseq/app/bioconductor-noiseq_server.py new file mode 100644 index 0000000000000000000000000000000000000000..67355225a71a5fe0648a8a529d4ab9917197609e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-noiseq/app/bioconductor-noiseq_server.py @@ -0,0 +1,327 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Literal + +@mcp.tool() +def noiseq_differential_expression( + counts_file: str, + factors_file: str, + output_file: str, + conditions: List[str], + method: Literal["noiseq", "noiseqbio"] = "noiseq", + replicates: Literal["technical", "biological", "no"] = "technical", + factor: str = "Condition", + norm: Literal["rpkm", "tmm", "uqua", "none"] = "rpkm", + k: float = 0.5, + lc: int = 1, + nss: int = 5, + v: float = 0.02, + pnr: float = 0.2, + n_sim: int = 10, + sep: str = "\t" +): + """ + Perform differential expression analysis using NOISeq or NOISeqBIO. + + Args: + counts_file: Path to the tab/csv file containing the expression matrix (genes as rows, samples as columns). + factors_file: Path to the tab/csv file containing the experimental design (samples as rows, factors as columns). + output_file: Path where the results table will be saved. + conditions: A list of two strings specifying the conditions to compare (e.g., ["Control", "Treatment"]). + method: 'noiseq' for technical replicates or no replicates, 'noiseqbio' for biological replicates. + replicates: Type of replicates: 'technical', 'biological', or 'no'. + factor: The name of the column in factors_file to use for comparison. + norm: Normalization method to apply. + k: Value to replace zeros in the count matrix. + lc: Length correction parameter (1 for TMM). + nss: Number of simulations for noiseqbio. + v: Variability threshold for noiseqbio. + pnr: Percentage of total reads for simulation (noiseq). + n_sim: Number of simulations (noiseq). + sep: Separator used in input files. + """ + counts_path = Path(counts_file) + factors_path = Path(factors_file) + output_path = Path(output_file) + + if not counts_path.exists(): + return {"error": f"Counts file not found: {counts_file}"} + if not factors_path.exists(): + return {"error": f"Factors file not found: {factors_file}"} + if len(conditions) != 2: + return {"error": "Exactly two conditions must be provided for comparison."} + + # Construct R script + r_script = f""" + library(NOISeq) + counts <- read.table("{counts_path}", header=TRUE, row.names=1, sep="{sep}", check.names=FALSE) + factors <- read.table("{factors_path}", header=TRUE, row.names=1, sep="{sep}", check.names=FALSE) + + mydata <- readData(data = counts, factors = factors) + + if ("{method}" == "noiseq") {{ + results <- noiseq(mydata, k = {k}, norm = "{norm}", replicates = "{replicates}", + factor = "{factor}", conditions = c("{conditions[0]}", "{conditions[1]}"), + pnr = {pnr}, nss = {nss}, v = {v}) + }} else {{ + results <- noiseqbio(mydata, k = {k}, norm = "{norm}", factor = "{factor}", + conditions = c("{conditions[0]}", "{conditions[1]}"), + lc = {lc}, nss = {nss}, v = {v}, r = {n_sim}) + }} + + # Extract results table + res_table <- results@results[[1]] + write.table(res_table, file = "{output_path}", sep = "\t", quote = FALSE, col.names = NA) + """ + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": " ".join(e.cmd) + } + finally: + if 'tmp_path' in locals(): + Path(tmp_path).unlink(missing_ok=True) + +@mcp.tool() +def noiseq_qc_report( + counts_file: str, + factors_file: str, + output_pdf: str = "QC_report.pdf", + sep: str = "\t" +): + """ + Generate a comprehensive Quality Control report for RNA-seq data using NOISeq. + + Args: + counts_file: Path to the expression matrix file. + factors_file: Path to the experimental design file. + output_pdf: Path to save the generated PDF report. + sep: Separator used in input files. + """ + counts_path = Path(counts_file) + factors_path = Path(factors_file) + output_path = Path(output_pdf) + + if not counts_path.exists(): + return {"error": f"Counts file not found: {counts_file}"} + + r_script = f""" + library(NOISeq) + counts <- read.table("{counts_path}", header=TRUE, row.names=1, sep="{sep}", check.names=FALSE) + factors <- read.table("{factors_path}", header=TRUE, row.names=1, sep="{sep}", check.names=FALSE) + mydata <- readData(data = counts, factors = factors) + QCreport(mydata, file = "{output_path}") + """ + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + finally: + if 'tmp_path' in locals(): + Path(tmp_path).unlink(missing_ok=True) + +@mcp.tool() +def noiseq_exploratory_plots( + counts_file: str, + factors_file: str, + plot_type: Literal["saturation", "cd", "countsbio", "GCbias", "lengthbias", "prop", "PCA"], + output_plot: str, + factor: Optional[str] = None, + biotype_file: Optional[str] = None, + gc_file: Optional[str] = None, + length_file: Optional[str] = None, + chromosome_file: Optional[str] = None, + sep: str = "\t" +): + """ + Generate exploratory plots to evaluate RNA-seq data quality and characteristics. + + Args: + counts_file: Path to the expression matrix file. + factors_file: Path to the experimental design file. + plot_type: Type of plot to generate: 'saturation', 'cd' (count distribution), + 'countsbio' (counts per biological group), 'GCbias', 'lengthbias', + 'prop' (proportion of features), 'PCA'. + output_plot: Path to save the plot (e.g., 'plot.png' or 'plot.pdf'). + factor: Factor to use for grouping in plots (required for some plot types). + biotype_file: Optional file with feature biotypes. + gc_file: Optional file with GC content per feature. + length_file: Optional file with feature lengths. + chromosome_file: Optional file with chromosome coordinates. + sep: Separator used in input files. + """ + counts_path = Path(counts_file) + factors_path = Path(factors_file) + output_path = Path(output_plot) + + if not counts_path.exists(): + return {"error": f"Counts file not found: {counts_file}"} + + # Prepare optional data loading + r_load_extra = "" + read_data_args = "data = counts, factors = factors" + + if biotype_file: + r_load_extra += f'biotype <- read.table("{biotype_file}", sep="{sep}", row.names=1)\n' + read_data_args += ", biotype = biotype" + if gc_file: + r_load_extra += f'gc <- read.table("{gc_file}", sep="{sep}", row.names=1)\n' + read_data_args += ", gc = gc" + if length_file: + r_load_extra += f'len <- read.table("{length_file}", sep="{sep}", row.names=1)\n' + read_data_args += ", length = len" + if chromosome_file: + r_load_extra += f'chrom <- read.table("{chromosome_file}", sep="{sep}", row.names=1)\n' + read_data_args += ", chromosome = chrom" + + factor_arg = f', factor = "{factor}"' if factor else "" + + r_script = f""" + library(NOISeq) + counts <- read.table("{counts_path}", header=TRUE, row.names=1, sep="{sep}", check.names=FALSE) + factors <- read.table("{factors_path}", header=TRUE, row.names=1, sep="{sep}", check.names=FALSE) + {r_load_extra} + + mydata <- readData({read_data_args}) + + # Generate data for plotting + mynoiseq_dat <- dat(mydata, type = "{plot_type}"{factor_arg}) + + # Save plot + if (grepl(".png$", "{output_path}")) {{ + png("{output_path}", width=800, height=600) + }} else {{ + pdf("{output_path}") + }} + explo.plot(mynoiseq_dat) + dev.off() + """ + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + finally: + if 'tmp_path' in locals(): + Path(tmp_path).unlink(missing_ok=True) + +@mcp.tool() +def noiseq_normalize( + counts_file: str, + output_file: str, + method: Literal["rpkm", "tmm", "uqua"] = "tmm", + long_file: Optional[str] = None, + lc: int = 1, + k: float = 0.0, + sep: str = "\t" +): + """ + Normalize RNA-seq count data using RPKM, TMM, or Upper Quartile methods. + + Args: + counts_file: Path to the raw count matrix file. + output_file: Path to save the normalized matrix. + method: Normalization method: 'rpkm', 'tmm', or 'uqua'. + long_file: Path to a file containing feature lengths (required for RPKM). + lc: Length correction parameter for TMM (default 1). + k: Offset for zero counts. + sep: Separator used in input files. + """ + counts_path = Path(counts_file) + output_path = Path(output_file) + + if not counts_path.exists(): + return {"error": f"Counts file not found: {counts_file}"} + if method == "rpkm" and not long_file: + return {"error": "long_file (feature lengths) is required for RPKM normalization."} + + r_script = f""" + library(NOISeq) + counts <- as.matrix(read.table("{counts_path}", header=TRUE, row.names=1, sep="{sep}", check.names=FALSE)) + + if ("{method}" == "rpkm") {{ + lengths <- read.table("{long_file}", sep="{sep}", row.names=1) + norm_counts <- rpkm(counts, long = lengths[,1], k = {k}) + }} else if ("{method}" == "tmm") {{ + norm_counts <- tmm(counts, lc = {lc}, k = {k}) + }} else if ("{method}" == "uqua") {{ + norm_counts <- uqua(counts, lc = {lc}, k = {k}) + }} + + write.table(norm_counts, file = "{output_path}", sep = "\t", quote = FALSE, col.names = NA) + """ + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + finally: + if 'tmp_path' in locals(): + Path(tmp_path).unlink(missing_ok=True) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-noiseq/app/bioconductor-noiseq_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-noiseq/app/bioconductor-noiseq_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4bf6c2623422936efeee32d8f56a5d3ede6b7114 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_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_manual_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_manual_txt/mcp_bioconductor-noiseq/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-noiseq/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-noiseq/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-noiseq/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-noiseq/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f800395ced0511dc9c22d1332037d8d07bbe14f4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_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_manual_txt/mcp_bioconductor-noiseq/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-noiseq/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..96a600a3aa5d094c29ef4b5908e396f15643085f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_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_manual_txt/mcp_bioconductor-noiseq/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-noiseq/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-noiseq/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-orfhunter/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-orfhunter/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ef6617906b8f7a0a1eedb1ed96648f36004ded13 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-orfhunter/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-orfhunter via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-orfhunter -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-orfhunter_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-orfhunter_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-orfhunter_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-orfhunter/app/bioconductor-orfhunter_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-orfhunter/app/bioconductor-orfhunter_server.py new file mode 100644 index 0000000000000000000000000000000000000000..509ef963d0449a0a024660a6b6479884ea6ee9ec --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-orfhunter/app/bioconductor-orfhunter_server.py @@ -0,0 +1,283 @@ +import subprocess +from pathlib import Path +from typing import Optional, Dict, Any + +@mcp.tool() +def predict_orf( + fasta_input: str, + output_csv: str, + model_path: Optional[str] = None, +) -> Dict[str, Any]: + """ + Predict the most likely open reading frame (ORF) in nucleotide sequences using a random forest model. + This is the primary tool for automatic determination and annotation of ORFs in RNA molecules. + + Args: + fasta_input: Path to the input FASTA file containing nucleotide sequences. + output_csv: Path where the predicted ORFs and their characteristics will be saved (CSV format). + model_path: Optional path to a custom pre-trained random forest model (.rds file). + If not provided, the default human-specific model included in the package is used. + """ + input_path = Path(fasta_input).resolve() + output_path = Path(output_csv).resolve() + + if not input_path.exists(): + return {"error": f"Input file not found: {fasta_input}"} + + output_path.parent.mkdir(parents=True, exist_ok=True) + + model_loading = "model <- NULL" + if model_path: + m_path = Path(model_path).resolve() + if not m_path.exists(): + return {"error": f"Model file not found: {model_path}"} + model_loading = f"model <- readRDS('{m_path}')" + + r_script = f""" + library(ORFhunteR) + library(Biostrings) + {model_loading} + sequences <- readDNAStringSet('{input_path}') + # predictORF returns a data.frame with predicted ORFs + result <- predictORF(sequences = sequences, model = model) + write.csv(result, '{output_path}', row.names = FALSE) + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"ORFhunteR::predictORF on {fasta_input}", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def find_orfs( + fasta_input: str, + output_csv: str, +) -> Dict[str, Any]: + """ + Identify all potential open reading frames (ORFs) in a set of nucleotide sequences. + This tool finds every sequence starting with a start codon and ending with a stop codon. + + Args: + fasta_input: Path to the input FASTA file containing nucleotide sequences. + output_csv: Path where the identified ORFs and their coordinates will be saved (CSV format). + """ + input_path = Path(fasta_input).resolve() + output_path = Path(output_csv).resolve() + + if not input_path.exists(): + return {"error": f"Input file not found: {fasta_input}"} + + output_path.parent.mkdir(parents=True, exist_ok=True) + + r_script = f""" + library(ORFhunteR) + library(Biostrings) + library(data.table) + sequences <- readDNAStringSet('{input_path}') + # findORFs returns a list of data.tables + result_list <- findORFs(sequences = sequences) + # Combine list into a single data table with transcript IDs + result_df <- rbindlist(result_list, idcol = "transcript_id") + write.csv(result_df, '{output_path}', row.names = FALSE) + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"ORFhunteR::findORFs on {fasta_input}", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def classify_orfs( + fasta_input: str, + output_csv: str, + model_path: Optional[str] = None, +) -> Dict[str, Any]: + """ + Classify a set of nucleotide sequences as coding or non-coding ORFs using a random forest model. + + Args: + fasta_input: Path to a FASTA file containing the ORF sequences to be classified. + output_csv: Path where the classification probabilities will be saved (CSV format). + model_path: Optional path to a custom pre-trained random forest model (.rds file). + """ + input_path = Path(fasta_input).resolve() + output_path = Path(output_csv).resolve() + + if not input_path.exists(): + return {"error": f"Input file not found: {fasta_input}"} + + output_path.parent.mkdir(parents=True, exist_ok=True) + + model_loading = "model <- NULL" + if model_path: + m_path = Path(model_path).resolve() + if not m_path.exists(): + return {"error": f"Model file not found: {model_path}"} + model_loading = f"model <- readRDS('{m_path}')" + + r_script = f""" + library(ORFhunteR) + library(Biostrings) + {model_loading} + sequences <- as.character(readDNAStringSet('{input_path}')) + # classifyORFs returns a vector of probabilities + probs <- classifyORFs(ORFs = sequences, model = model) + result <- data.frame(sequence_id = names(sequences), probability = probs) + write.csv(result, '{output_path}', row.names = FALSE) + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"ORFhunteR::classifyORFs on {fasta_input}", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def vectorize_orfs( + fasta_input: str, + output_csv: str, +) -> Dict[str, Any]: + """ + Transform nucleotide sequences into numerical vectors (feature extraction) for machine learning. + This implements the vectorization algorithm used by the ORFhunteR random forest model. + + Args: + fasta_input: Path to the input FASTA file containing nucleotide sequences. + output_csv: Path where the feature matrix will be saved (CSV format). + """ + input_path = Path(fasta_input).resolve() + output_path = Path(output_csv).resolve() + + if not input_path.exists(): + return {"error": f"Input file not found: {fasta_input}"} + + output_path.parent.mkdir(parents=True, exist_ok=True) + + r_script = f""" + library(ORFhunteR) + library(Biostrings) + sequences <- as.character(readDNAStringSet('{input_path}')) + # vectorizeORFs returns a matrix of features + features <- vectorizeORFs(sequences = sequences) + write.csv(as.data.frame(features), '{output_path}', row.names = TRUE) + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"ORFhunteR::vectorizeORFs on {fasta_input}", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def annotate_orf( + orfs_csv: str, + output_csv: str, + genome_package: str = "BSgenome.Hsapiens.UCSC.hg38", +) -> Dict[str, Any]: + """ + Annotate predicted ORFs by mapping them to genomic coordinates using a BSgenome object. + + Args: + orfs_csv: Path to a CSV file containing predicted ORFs (output from predict_orf). + Must contain 'transcript_id' and coordinate columns. + output_csv: Path where the genomic annotations will be saved (CSV format). + genome_package: The name of the Bioconductor BSgenome package to use for annotation. + Defaults to 'BSgenome.Hsapiens.UCSC.hg38'. + """ + input_path = Path(orfs_csv).resolve() + output_path = Path(output_csv).resolve() + + if not input_path.exists(): + return {"error": f"Input CSV file not found: {orfs_csv}"} + + output_path.parent.mkdir(parents=True, exist_ok=True) + + r_script = f""" + library(ORFhunteR) + library({genome_package}) + orfs_df <- read.csv('{input_path}') + # annotateORFs maps transcript coordinates to genomic coordinates + # It expects the ORFs data frame and corresponding transcript IDs + result <- annotateORFs(ORFs = orfs_df, + transcript_id = orfs_df$transcript_id, + target_genome = {genome_package}) + write.csv(result, '{output_path}', row.names = FALSE) + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"ORFhunteR::annotateORFs using {genome_package}", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed. Ensure the BSgenome package is installed.", + "stdout": e.stdout, + "stderr": e.stderr + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-orfhunter/app/bioconductor-orfhunter_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-orfhunter/app/bioconductor-orfhunter_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0dd1248ebc67d66c46f8b60b782e2b1fed4c134e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-orfhunter/app/bioconductor-orfhunter_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_manual_txt/mcp_bioconductor-orfhunter/app/bioconductor-orfhunter_server.py') +SERVER_NAME = 'biosci_bioconductor_orfhunter' + + +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_manual_txt/mcp_bioconductor-orfhunter/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-orfhunter/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-orfhunter/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-orfhunter/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-orfhunter/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..ffd1257beabc2e36bf2d4c39081ee52804eafd1d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-orfhunter/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-orfhunter: + build: . + image: mcp-bioconductor-orfhunter:latest + container_name: mcp-bioconductor-orfhunter + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-orfhunter + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-orfhunter/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-orfhunter/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..abc3d2710d8c879e5c5ae780455731d3b509b0d0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-orfhunter/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-orfhunter + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-orfhunter/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-orfhunter/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-orfhunter/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.ce.eg.db/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.ce.eg.db/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2d86d2a336872e24991c5f1dda25fd891c93cbc7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.ce.eg.db/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-org.ce.eg.db via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-org.ce.eg.db -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-org.ce.eg.db_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-org.ce.eg.db_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-org.ce.eg.db_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.ce.eg.db/app/bioconductor-org.ce.eg.db_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.ce.eg.db/app/bioconductor-org.ce.eg.db_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b6d9431ec27adc37733cb4d713f09617a74e2229 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.ce.eg.db/app/bioconductor-org.ce.eg.db_server.py @@ -0,0 +1,372 @@ +import subprocess +import textwrap +from pathlib import Path +from typing import List, Optional, Dict, Any + +# MCP decorator is not imported as per instructions, but assumed to be present. +# from mcp import tool as mcp_tool +# For the purpose of this script, we'll define a dummy decorator. +class mcp: + def tool(): + def decorator(f): + return f + return decorator + +@mcp.tool() +def select_annotations( + keys: List[str], + keytype: str, + columns: List[str], + output_file: str, + output_format: str = "tsv", +) -> Dict[str, Any]: + """ + Perform a complex query on the org.Ce.eg.db C. elegans annotation database using the select() method. + This returns a table of mappings between the provided keys and requested columns. + + Args: + keys: List of identifiers to look up (e.g., ["172469", "172470"] or ["skn-1", "gfp"]). + keytype: The type of the input keys (e.g., "ENTREZID", "SYMBOL", "WORMBASE", "ENSEMBL"). + columns: The annotation types to retrieve (e.g., ["GO", "EVIDENCE", "ONTOLOGY", "GENENAME"]). + output_file: Path to save the resulting table. + output_format: Format of the output file ("tsv" or "csv"). Defaults to "tsv". + """ + # Input validation + if not keys: + raise ValueError("The 'keys' list cannot be empty.") + if not keytype: + raise ValueError("The 'keytype' parameter must be specified.") + if not columns: + raise ValueError("The 'columns' list cannot be empty.") + + valid_formats = ["tsv", "csv"] + if output_format not in valid_formats: + raise ValueError(f"output_format must be one of {valid_formats}") + + out_path = Path(output_file).resolve() + out_path.parent.mkdir(parents=True, exist_ok=True) + + # Prepare R vectors safely + keys_str = ", ".join([f'"{k}"' for k in keys]) + cols_str = ", ".join([f'"{c}"' for c in columns]) + + # The R script uses f-string formatting. Literal curly braces for R code blocks + # must be escaped by doubling them (e.g., {{ and }}). + r_script = textwrap.dedent(f""" + suppressPackageStartupMessages(library(org.Ce.eg.db)) + suppressPackageStartupMessages(library(AnnotationDbi)) + + # Validate inputs in R + if (!("{keytype}" %in% keytypes(org.Ce.eg.db))) {{{{ + stop(paste("Invalid keytype:", "{keytype}")) + }}}} + + requested_cols <- c({cols_str}) + valid_cols <- columns(org.Ce.eg.db) + if (!all(requested_cols %in% valid_cols)) {{{{ + invalid_ones <- requested_cols[!(requested_cols %in% valid_cols)] + stop(paste("Invalid columns:", paste(invalid_ones, collapse=", "))) + }}}} + + res <- tryCatch({{{{ + AnnotationDbi::select( + org.Ce.eg.db, + keys = c({keys_str}), + columns = requested_cols, + keytype = "{keytype}" + ) + }}}}, error = function(e) {{{{ + stop(paste("Select failed:", e$message)) + }}}}) + + if ("{output_format}" == "tsv") {{{{ + write.table(res, file = "{out_path}", sep = "\\t", quote = FALSE, row.names = FALSE) + }}}} else {{{{ + write.csv(res, file = "{out_path}", quote = FALSE, row.names = FALSE) + }}}} + """) + + command_str = f"Rscript -e \"{r_script}\"" + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + return { + "command_executed": "Rscript -e 'AnnotationDbi::select(...)'", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(out_path)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": "Rscript -e 'AnnotationDbi::select(...)'", + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed. Stderr: {e.stderr}" + } + +@mcp.tool() +def map_ids( + keys: List[str], + keytype: str, + column: str, + multi_vals: str = "first", +) -> Dict[str, Any]: + """ + Map identifiers from one type to another using the mapIds() method. + This is optimized for 1-to-1 or 1-to-many mapping. + + Args: + keys: List of identifiers to map. + keytype: The type of the input keys (e.g., "WORMBASE"). + column: The type of identifier to map to (e.g., "SYMBOL"). + multi_vals: How to handle multiple matches. Options: "first", "list", "filter", "asNA", "CharacterList". + """ + if not keys: + raise ValueError("The 'keys' list cannot be empty.") + + valid_multi = ["first", "list", "filter", "asNA", "CharacterList"] + if multi_vals not in valid_multi: + raise ValueError(f"multi_vals must be one of {valid_multi}") + + keys_str = ", ".join([f'"{k}"' for k in keys]) + + r_script = textwrap.dedent(f""" + suppressPackageStartupMessages(library(org.Ce.eg.db)) + suppressPackageStartupMessages(library(AnnotationDbi)) + + res <- mapIds( + org.Ce.eg.db, + keys = c({keys_str}), + column = "{column}", + keytype = "{keytype}", + multiVals = "{multi_vals}" + ) + + # Convert to a structured key-value output for easy parsing + cat("---RESULT_START---\\n") + if (is.list(res) || is(res, "CharacterList")) {{{{ + for (n in names(res)) {{{{ + # Handle NULLs which represent no mapping + value <- if (is.null(res[[n]])) "NA" else paste(res[[n]], collapse=",") + cat(n, ":", value, "\\n") + }}}} + }}}} else {{{{ + for (n in names(res)) {{{{ + value <- if (is.na(res[n])) "NA" else res[n] + cat(n, ":", value, "\\n") + }}}} + }}}} + cat("---RESULT_END---\\n") + """) + + command_str = "Rscript -e 'AnnotationDbi::mapIds(...)'" + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + + # Parse the structured output from R + output_str = process.stdout + result_block = output_str.split("---RESULT_START---\n")[-1].split("---RESULT_END---")[0].strip() + mappings = {} + if result_block: + for line in result_block.split('\n'): + parts = line.split(':', 1) + if len(parts) == 2: + key = parts[0].strip() + val_str = parts[1].strip() + if val_str == "NA": + mappings[key] = None + else: + values = [v.strip() for v in val_str.split(',')] + if multi_vals in ["first", "asNA"] and len(values) == 1: + mappings[key] = values[0] + else: + mappings[key] = values + + return { + "command_executed": command_str, + "stdout": process.stdout, + "stderr": process.stderr, + "mappings": mappings + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed. Stderr: {e.stderr}" + } + +@mcp.tool() +def list_resources() -> Dict[str, Any]: + """ + List all available keytypes and columns (annotation types) in the org.Ce.eg.db package. + """ + r_script = textwrap.dedent(""" + suppressPackageStartupMessages(library(org.Ce.eg.db)) + cat("---COLUMNS_START---\\n") + cat(paste(columns(org.Ce.eg.db), collapse=", "), "\\n") + cat("---COLUMNS_END---\\n") + cat("---KEYTYPES_START---\\n") + cat(paste(keytypes(org.Ce.eg.db), collapse=", "), "\\n") + cat("---KEYTYPES_END---\\n") + """) + + command_str = "Rscript -e 'columns(...); keytypes(...)'" + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + + # Parse structured output + stdout_str = process.stdout + columns_str = stdout_str.split("---COLUMNS_START---\n")[1].split("---COLUMNS_END---")[0].strip() + keytypes_str = stdout_str.split("---KEYTYPES_START---\n")[1].split("---KEYTYPES_END---")[0].strip() + + return { + "command_executed": command_str, + "stdout": process.stdout, + "stderr": process.stderr, + "columns": columns_str.split(", ") if columns_str else [], + "keytypes": keytypes_str.split(", ") if keytypes_str else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed. Stderr: {e.stderr}" + } + +@mcp.tool() +def get_db_metadata() -> Dict[str, Any]: + """ + Retrieve metadata about the org.Ce.eg.db package, such as version, species, and data sources. + """ + r_script = "suppressPackageStartupMessages(library(org.Ce.eg.db)); print(metadata(org.Ce.eg.db))" + command_str = f"Rscript -e \"{r_script}\"" + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + return { + "command_executed": command_str, + "stdout": process.stdout, + "stderr": process.stderr, + "metadata": process.stdout.strip().split('\n') + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed. Stderr: {e.stderr}" + } + +@mcp.tool() +def get_available_keys( + keytype: str, + pattern: Optional[str] = None, + limit: int = 100 +) -> Dict[str, Any]: + """ + Retrieve a list of all available keys for a specific keytype, optionally filtered by a pattern. + + Args: + keytype: The type of keys to retrieve (e.g., "SYMBOL"). + pattern: An optional regular expression pattern to filter keys. + limit: Maximum number of keys to return. Defaults to 100. + """ + if limit <= 0: + raise ValueError("Limit must be a positive integer.") + + pattern_arg = f', pattern = "{pattern}"' if pattern else "" + + r_script = textwrap.dedent(f""" + suppressPackageStartupMessages(library(org.Ce.eg.db)) + all_keys <- keys(org.Ce.eg.db, keytype = "{keytype}"{pattern_arg}) + cat(head(all_keys, {limit}), sep="\\n") + cat("\\n---TOTAL_COUNT:", length(all_keys), "---\\n") + """) + + command_str = f"Rscript -e 'keys(..., keytype=\"{keytype}\")'" + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + + # Robust parsing + output_str = process.stdout + if "---TOTAL_COUNT:" in output_str: + keys_part, total_part = output_str.split("---TOTAL_COUNT:") + keys_list = keys_part.strip().split("\n") if keys_part.strip() else [] + total_count = int(total_part.replace("---", "").strip()) + else: + keys_list = output_str.strip().split("\n") if output_str.strip() else [] + total_count = len(keys_list) + + return { + "command_executed": command_str, + "stdout": process.stdout, + "stderr": process.stderr, + "keys": keys_list, + "total_available": total_count + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed. Stderr: {e.stderr}" + } + +@mcp.tool() +def get_species_info() -> Dict[str, Any]: + """ + Get the species name for which this annotation package was designed. + """ + r_script = "suppressPackageStartupMessages(library(org.Ce.eg.db)); cat(species(org.Ce.eg.db))" + command_str = f"Rscript -e \"{r_script}\"" + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + return { + "command_executed": command_str, + "stdout": process.stdout, + "stderr": process.stderr, + "species": process.stdout.strip() + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed. Stderr: {e.stderr}" + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.ce.eg.db/app/bioconductor-org.ce.eg.db_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.ce.eg.db/app/bioconductor-org.ce.eg.db_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..80ddfab2fbff4acf9c62ba0c7fe1a94a47b37b9b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.ce.eg.db/app/bioconductor-org.ce.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_manual_txt/mcp_bioconductor-org.ce.eg.db/app/bioconductor-org.ce.eg.db_server.py') +SERVER_NAME = 'biosci_bioconductor_org_ce_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_manual_txt/mcp_bioconductor-org.ce.eg.db/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.ce.eg.db/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.ce.eg.db/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.ce.eg.db/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.ce.eg.db/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b0aca5cb848af22025e1277befdd8c28f521b8bd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.ce.eg.db/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-org.ce.eg.db: + build: . + image: mcp-bioconductor-org.ce.eg.db:latest + container_name: mcp-bioconductor-org.ce.eg.db + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-org.ce.eg.db + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.ce.eg.db/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.ce.eg.db/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e4b02b7acc6a22c38fee1f3d8401b748f0cfde91 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.ce.eg.db/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-org.ce.eg.db + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.ce.eg.db/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.ce.eg.db/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.ce.eg.db/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.hs.eg.db/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_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_manual_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_manual_txt/mcp_bioconductor-org.hs.eg.db/app/bioconductor-org.hs.eg.db_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.hs.eg.db/app/bioconductor-org.hs.eg.db_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5b0ed9eb3ae10b49528a230d7f19c22fdec2667b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.hs.eg.db/app/bioconductor-org.hs.eg.db_server.py @@ -0,0 +1,189 @@ +import subprocess +import tempfile +import json +from pathlib import Path +from typing import List, Optional, Union + +def _run_r_command(script: str): + """Helper to execute R code and handle errors.""" + try: + # Check if R is installed + subprocess.run(["Rscript", "--version"], capture_output=True, check=True) + except (subprocess.CalledProcessError, FileNotFoundError): + return { + "error": "Rscript not found. Please ensure R and Bioconductor package 'org.Hs.eg.db' are installed.", + "stdout": "", + "stderr": "" + } + + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write("suppressPackageStartupMessages(library(org.Hs.eg.db))\n") + tmp.write(script) + tmp_path = tmp.name + + try: + result = subprocess.run( + ["Rscript", tmp_path], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript {tmp_path}", + "stdout": result.stdout, + "stderr": result.stderr, + "success": True + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript {tmp_path}", + "stdout": e.stdout, + "stderr": e.stderr, + "success": False, + "error": str(e) + } + 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" +): + """ + Retrieve data from org.Hs.eg.db using the select method. + + Args: + keys: The identifiers to look up (e.g., ['7157', '10']). + columns: The types of data to retrieve (e.g., ['SYMBOL', 'GENENAME']). + keytype: The type of identifier passed in 'keys' (default: 'ENTREZID'). + """ + if not keys: + return {"error": "Keys list cannot be empty"} + if not columns: + return {"error": "Columns list cannot be empty"} + + # Format keys and columns for R + keys_r = 'c("' + '","'.join(keys) + '")' + cols_r = 'c("' + '","'.join(columns) + '")' + + script = f""" + res <- tryCatch({{ + select(org.Hs.eg.db, keys = {keys_r}, columns = {cols_r}, keytype = "{keytype}") + }}, error = function(e) {{ + stop(e$message) + }}) + write.csv(res, row.names = FALSE) + """ + + result = _run_r_command(script) + return result + +@mcp.tool() +def org_hs_eg_db_map_ids( + keys: List[str], + column: str, + keytype: str = "ENTREZID", + multi_vals: str = "first" +): + """ + Map identifiers 1-to-1 using the mapIds method. + + Args: + keys: The identifiers to look up. + column: The single column to retrieve. + keytype: The type of identifier passed in 'keys'. + multi_vals: How to handle multiple matches ('first', 'list', 'filter', 'asNA', 'CharacterList'). + """ + valid_multi = ["first", "list", "filter", "asNA", "CharacterList"] + if multi_vals not in valid_multi: + return {"error": f"multi_vals must be one of {valid_multi}"} + + keys_r = 'c("' + '","'.join(keys) + '")' + + script = f""" + res <- mapIds(org.Hs.eg.db, keys = {keys_r}, column = "{column}", + keytype = "{keytype}", multiVals = "{multi_vals}") + # Convert named vector to JSON-like output + cat(jsonlite::toJSON(as.list(res), auto_unbox = TRUE)) + """ + # Note: requires jsonlite in R for this specific tool's formatting + result = _run_r_command(script) + return result + +@mcp.tool() +def org_hs_eg_db_get_keys( + keytype: str = "ENTREZID", + pattern: str = "", + column: str = "" +): + """ + Retrieve all keys of a specific type from the database. + + Args: + keytype: The type of keys to retrieve. + pattern: Optional grep pattern to filter keys. + column: Optional column to filter keys by. + """ + filter_logic = "" + if pattern: + filter_logic = f', pattern = "{pattern}"' + if column: + filter_logic += f', column = "{column}"' + + script = f""" + res <- keys(org.Hs.eg.db, keytype = "{keytype}"{filter_logic}) + cat(res, sep="\\n") + """ + + result = _run_r_command(script) + return result + +@mcp.tool() +def org_hs_eg_db_metadata(): + """ + Retrieve metadata about the org.Hs.eg.db package, including available columns and keytypes. + """ + script = """ + cat("COLUMNS:\\n") + cat(columns(org.Hs.eg.db), sep=", ") + cat("\\n\\nKEYTYPES:\\n") + cat(keytypes(org.Hs.eg.db), sep=", ") + cat("\\n\\nSPECIES:\\n") + cat(species(org.Hs.eg.db)) + """ + + result = _run_r_command(script) + return result + +@mcp.tool() +def org_hs_eg_db_query_by_symbol( + symbols: List[str], + columns: List[str] = ["ENTREZID", "ENSEMBL", "GENENAME"] +): + """ + Convenience tool to map Gene Symbols to other identifiers. + + Args: + symbols: List of gene symbols (e.g., ['TP53', 'BRCA1']). + columns: Data columns to return. + """ + if not symbols: + return {"error": "Symbols list cannot be empty"} + + symbols_r = 'c("' + '","'.join(symbols) + '")' + cols_r = 'c("' + '","'.join(columns) + '")' + + script = f""" + res <- tryCatch({{ + select(org.Hs.eg.db, keys = {symbols_r}, columns = {cols_r}, keytype = "SYMBOL") + }}, error = function(e) {{ + stop(e$message) + }}) + write.csv(res, row.names = FALSE) + """ + + result = _run_r_command(script) + return result \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.hs.eg.db/app/bioconductor-org.hs.eg.db_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.hs.eg.db/app/bioconductor-org.hs.eg.db_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a0e95f1557e28a22ad96066d7aeb17cb217cbca6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_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_manual_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_manual_txt/mcp_bioconductor-org.hs.eg.db/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_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_manual_txt/mcp_bioconductor-org.hs.eg.db/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.hs.eg.db/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_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_manual_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_manual_txt/mcp_bioconductor-org.hs.eg.db/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_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_manual_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_manual_txt/mcp_bioconductor-org.hs.eg.db/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_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_manual_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_manual_txt/mcp_bioconductor-org.mm.eg.db/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.mm.eg.db/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4bde49a4d261b08d5cc4b18d0a28d63809e09d28 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.mm.eg.db/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-org.mm.eg.db via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-org.mm.eg.db -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-org.mm.eg.db_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-org.mm.eg.db_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-org.mm.eg.db_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.mm.eg.db/app/bioconductor-org.mm.eg.db_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.mm.eg.db/app/bioconductor-org.mm.eg.db_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a9ff4f9494a61ab7631e61fd28099efc282bd234 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.mm.eg.db/app/bioconductor-org.mm.eg.db_server.py @@ -0,0 +1,271 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# MCP.TOOL DECORATOR (should not be included in the final output) +# This is a placeholder for the actual decorator. +def mcp_tool_placeholder(*args, **kwargs): + def decorator(func): + return func + return decorator + +# In a real MCP environment, the following line would be: +# import mcp +# and the decorator would be @mcp.tool() +mcp = type("mcp", (), {"tool": mcp_tool_placeholder}) + + +@mcp.tool() +def org_mm_eg_db_query( + keys: List[str], + keytype: str, + columns: List[str], + output_file: Path, +) -> dict: + """ + Performs an annotation query on the org.Mm.eg.db database. + + This tool uses the AnnotationDbi::select function to retrieve annotations + for a given set of keys. It maps identifiers from a specified keytype to + the desired annotation columns. + + Args: + keys: A list of identifiers to query (e.g., ["14189", "14190"]). + keytype: The type of identifier being provided in `keys`. + Use the `org_mm_eg_db_list_keytypes` tool to see available options. + Example: "ENTREZID". + columns: A list of annotation columns to retrieve. + Use the `org_mm_eg_db_list_columns` tool to see available options. + Example: ["SYMBOL", "GENENAME", "GO"]. + output_file: The path to save the resulting annotation table in TSV format. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the output file path. + """ + if not keys: + raise ValueError("The 'keys' list cannot be empty.") + if not keytype: + raise ValueError("The 'keytype' parameter cannot be empty.") + if not columns: + raise ValueError("The 'columns' list cannot be empty.") + + # Convert Python lists to R vector strings, e.g., c("item1", "item2") + r_keys = 'c({})'.format(', '.join(f'"{key}"' for key in keys)) + r_columns = 'c({})'.format(', '.join(f'"{col}"' for col in columns)) + + r_script_content = f""" + # Suppress startup messages for cleaner output + suppressPackageStartupMessages(library("AnnotationDbi")) + suppressPackageStartupMessages(library("org.Mm.eg.db")) + + # Define parameters + keys_to_query <- {r_keys} + cols_to_fetch <- {r_columns} + key_type <- "{keytype}" + output_path <- "{output_file}" + + # Perform the query + # Use tryCatch to handle potential errors, like invalid keytypes or columns + results <- tryCatch( + {{ + AnnotationDbi::select( + org.Mm.eg.db, + keys = keys_to_query, + columns = cols_to_fetch, + keytype = key_type + ) + }}, + error = function(e) {{ + stop(paste("AnnotationDbi::select failed:", e$message)) + }} + ) + + # Write the output + write.table( + results, + file = output_path, + sep = "\\t", + row.names = FALSE, + quote = FALSE + ) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_script: + tmp_script.write(r_script_content) + script_path = tmp_script.name + + cmd = ["Rscript", script_path] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + # Clean up the temporary script file + Path(script_path).unlink() + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file)], + } + except subprocess.CalledProcessError as e: + # Clean up the temporary script file even on error + Path(script_path).unlink() + raise RuntimeError( + f"R script execution failed with exit code {e.returncode}.\n" + f"Command: {command_executed}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) from e + + +@mcp.tool() +def org_mm_eg_db_list_columns() -> dict: + """ + Lists all available annotation columns in the org.Mm.eg.db database. + + These column names can be used in the `columns` parameter of the + `org_mm_eg_db_query` tool. + + Returns: + A dictionary containing the command executed and a list of available columns in stdout. + """ + r_script_content = """ + suppressPackageStartupMessages(library("org.Mm.eg.db")) + cat(columns(org.Mm.eg.db), sep = "\\n") + """ + cmd = ["Rscript", "-e", r_script_content] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"R script execution failed with exit code {e.returncode}.\n" + f"Command: {command_executed}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) from e + + +@mcp.tool() +def org_mm_eg_db_list_keytypes() -> dict: + """ + Lists all available keytypes in the org.Mm.eg.db database. + + Keytypes define the type of primary identifiers that can be used for querying + in the `keytype` parameter of the `org_mm_eg_db_query` and + `org_mm_eg_db_list_keys` tools. + + Returns: + A dictionary containing the command executed and a list of available keytypes in stdout. + """ + r_script_content = """ + suppressPackageStartupMessages(library("org.Mm.eg.db")) + cat(keytypes(org.Mm.eg.db), sep = "\\n") + """ + cmd = ["Rscript", "-e", r_script_content] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"R script execution failed with exit code {e.returncode}.\n" + f"Command: {command_executed}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) from e + + +@mcp.tool() +def org_mm_eg_db_list_keys( + keytype: str, + output_file: Optional[Path] = None, +) -> dict: + """ + Lists all primary keys for a given keytype from the org.Mm.eg.db database. + + Args: + keytype: The type of identifiers to retrieve. Use the + `org_mm_eg_db_list_keytypes` tool to see available options. + output_file: Optional. If provided, saves the list of keys to this file, + one key per line. Otherwise, keys are printed to stdout. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the output file path if provided. + """ + if not keytype: + raise ValueError("The 'keytype' parameter cannot be empty.") + + if output_file: + r_script_content = f""" + suppressPackageStartupMessages(library("org.Mm.eg.db")) + key_type <- "{keytype}" + output_path <- "{output_file}" + keys_list <- keys(org.Mm.eg.db, keytype = key_type) + write.table( + keys_list, + file = output_path, + col.names = FALSE, + row.names = FALSE, + quote = FALSE + ) + """ + else: + r_script_content = f""" + suppressPackageStartupMessages(library("org.Mm.eg.db")) + key_type <- "{keytype}" + keys_list <- keys(org.Mm.eg.db, keytype = key_type) + cat(keys_list, sep = "\\n") + """ + + cmd = ["Rscript", "-e", r_script_content] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + output_files = [str(output_file)] if output_file else [] + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"R script execution failed with exit code {e.returncode}.\n" + f"Command: {command_executed}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) from e \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.mm.eg.db/app/bioconductor-org.mm.eg.db_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.mm.eg.db/app/bioconductor-org.mm.eg.db_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f4f912826cb6bd82ebc9b78ae889af0c9d17420e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.mm.eg.db/app/bioconductor-org.mm.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_manual_txt/mcp_bioconductor-org.mm.eg.db/app/bioconductor-org.mm.eg.db_server.py') +SERVER_NAME = 'biosci_bioconductor_org_mm_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_manual_txt/mcp_bioconductor-org.mm.eg.db/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.mm.eg.db/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.mm.eg.db/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.mm.eg.db/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.mm.eg.db/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..0fda34df59609c6bfa58fac6b4e3c48b1cf12d84 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.mm.eg.db/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-org.mm.eg.db: + build: . + image: mcp-bioconductor-org.mm.eg.db:latest + container_name: mcp-bioconductor-org.mm.eg.db + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-org.mm.eg.db + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.mm.eg.db/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.mm.eg.db/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e0edb9c821b81883fd437f4d3d385811b12089ee --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.mm.eg.db/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-org.mm.eg.db + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.mm.eg.db/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.mm.eg.db/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-org.mm.eg.db/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-partcnv/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-partcnv/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2392c0fa8a90d8e6ef61d8d170fd1a152c4d14e8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-partcnv/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-partcnv via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-partcnv -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-partcnv_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-partcnv_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-partcnv_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-partcnv/app/bioconductor-partcnv_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-partcnv/app/bioconductor-partcnv_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3ae21cebd42ae63a959c43513db2583cdb100d69 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-partcnv/app/bioconductor-partcnv_server.py @@ -0,0 +1,277 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Dict, Any + +@mcp.tool() +def partcnv_classify( + input_rds: str, + output_rds: str, + region: str, + cnv_type: str, + reference_column: str, + reference_label: str, + annotation_hub_id: str = "AH107301", + assay: str = "RNA", + slot: str = "counts", + max_iter: int = 100, + epsilon: float = 1e-5, +) -> Dict[str, Any]: + """ + Perform aneuploidy classification using the partCNV EM algorithm. + + This tool uses a statistical framework (EM algorithm with Poisson mixtures) + to detect aneuploid cells with local copy number deletion or amplification + based on single-cell RNA-seq data. + + Args: + input_rds: Path to the input Seurat or SingleCellExperiment object (RDS format). + output_rds: Path where the classification results (RDS) will be saved. + region: The cytoband region to analyze (e.g., "1q", "chr1p"). + cnv_type: Type of CNV to detect. Must be 'deletion' or 'amplification'. + reference_column: Metadata column name used to identify reference (normal) cells. + reference_label: The value in reference_column that identifies the reference cells. + annotation_hub_id: AnnotationHub ID for gene coordinates (default "AH107301" for GRCh38). + assay: Assay name to extract data from (for Seurat objects). + slot: Slot name to extract data from (for Seurat objects). + max_iter: Maximum number of iterations for the EM algorithm. + epsilon: Convergence tolerance for the EM algorithm. + """ + # Input validation + input_path = Path(input_rds) + if not input_path.exists(): + return {"error": f"Input file not found: {input_rds}"} + + if cnv_type not in ["deletion", "amplification"]: + return {"error": "cnv_type must be either 'deletion' or 'amplification'"} + + # Create output directory if it doesn't exist + output_path = Path(output_rds) + output_path.parent.mkdir(parents=True, exist_ok=True) + + # Construct R script + r_script = f""" + library(partCNV) + library(Seurat) + library(SingleCellExperiment) + + # Load object + obj <- readRDS("{input_rds}") + + # Extract counts and metadata + if (inherits(obj, "Seurat")) {{ + counts <- GetAssayData(obj, assay = "{assay}", slot = "{slot}") + meta <- obj@meta.data + }} else if (inherits(obj, "SingleCellExperiment")) {{ + counts <- counts(obj) + meta <- as.data.frame(colData(obj)) + }} else {{ + stop("Input must be a Seurat or SingleCellExperiment object") + }} + + # Identify reference cells + if (!("{reference_column}" %in% colnames(meta))) {{ + stop(paste("Column", "{reference_column}", "not found in metadata")) + }} + + ref_idx <- which(meta[["{reference_column}"]] == "{reference_label}") + if (length(ref_idx) == 0) {{ + stop("No reference cells found with the specified label") + }} + + # Run partCNV + results <- partCNV( + dat = as.matrix(counts), + region = "{region}", + type = "{cnv_type}", + reference = ref_idx, + max_iter = {max_iter}, + epsilon = {epsilon}, + annotation_hub_id = "{annotation_hub_id}" + ) + + # Save results + saveRDS(results, "{output_rds}") + """ + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path.absolute())] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed" + } + finally: + if 'tmp_path' in locals() and Path(tmp_path).exists(): + Path(tmp_path).unlink() + + +@mcp.tool() +def partcnvh_classify( + input_rds: str, + output_rds: str, + region: str, + cnv_type: str, + reference_column: str, + reference_label: str, + annotation_hub_id: str = "AH107301", + assay: str = "RNA", + slot: str = "counts", + max_iter: int = 100, + epsilon: float = 1e-5, +) -> Dict[str, Any]: + """ + Perform aneuploidy classification using the partCNVH algorithm (EM + HMM). + + This tool improves classification accuracy by integrating a Hidden Markov Model (HMM) + for feature selection within the partCNV framework. + + Args: + input_rds: Path to the input Seurat or SingleCellExperiment object (RDS format). + output_rds: Path where the classification results (RDS) will be saved. + region: The cytoband region to analyze (e.g., "1q", "chr1p"). + cnv_type: Type of CNV to detect. Must be 'deletion' or 'amplification'. + reference_column: Metadata column name used to identify reference (normal) cells. + reference_label: The value in reference_column that identifies the reference cells. + annotation_hub_id: AnnotationHub ID for gene coordinates (default "AH107301" for GRCh38). + assay: Assay name to extract data from (for Seurat objects). + slot: Slot name to extract data from (for Seurat objects). + max_iter: Maximum number of iterations for the EM algorithm. + epsilon: Convergence tolerance for the EM algorithm. + """ + # Input validation + input_path = Path(input_rds) + if not input_path.exists(): + return {"error": f"Input file not found: {input_rds}"} + + if cnv_type not in ["deletion", "amplification"]: + return {"error": "cnv_type must be either 'deletion' or 'amplification'"} + + # Create output directory if it doesn't exist + output_path = Path(output_rds) + output_path.parent.mkdir(parents=True, exist_ok=True) + + # Construct R script + r_script = f""" + library(partCNV) + library(Seurat) + library(SingleCellExperiment) + + # Load object + obj <- readRDS("{input_rds}") + + # Extract counts and metadata + if (inherits(obj, "Seurat")) {{ + counts <- GetAssayData(obj, assay = "{assay}", slot = "{slot}") + meta <- obj@meta.data + }} else if (inherits(obj, "SingleCellExperiment")) {{ + counts <- counts(obj) + meta <- as.data.frame(colData(obj)) + }} else {{ + stop("Input must be a Seurat or SingleCellExperiment object") + }} + + # Identify reference cells + if (!("{reference_column}" %in% colnames(meta))) {{ + stop(paste("Column", "{reference_column}", "not found in metadata")) + }} + + ref_idx <- which(meta[["{reference_column}"]] == "{reference_label}") + if (length(ref_idx) == 0) {{ + stop("No reference cells found with the specified label") + }} + + # Run partCNVH + results <- partCNVH( + dat = as.matrix(counts), + region = "{region}", + type = "{cnv_type}", + reference = ref_idx, + max_iter = {max_iter}, + epsilon = {epsilon}, + annotation_hub_id = "{annotation_hub_id}" + ) + + # Save results + saveRDS(results, "{output_rds}") + """ + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path.absolute())] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed" + } + finally: + if 'tmp_path' in locals() and Path(tmp_path).exists(): + Path(tmp_path).unlink() + + +@mcp.tool() +def get_partcnv_gene_info( + annotation_hub_id: str = "AH107301", +) -> Dict[str, Any]: + """ + Retrieve gene coordinate information used by partCNV from AnnotationHub. + + Args: + annotation_hub_id: AnnotationHub ID for gene coordinates (default "AH107301" for GRCh38). + """ + r_script = f""" + library(partCNV) + library(AnnotationHub) + + ah <- AnnotationHub() + gene_info <- ah[["{annotation_hub_id}"]] + + # Convert to a simple data frame for output + df <- as.data.frame(gene_info) + write.csv(df, stdout(), row.names = FALSE) + """ + + try: + cmd = ["Rscript", "-e", r_script] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "info": "Gene information retrieved successfully" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to retrieve gene information" + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-partcnv/app/bioconductor-partcnv_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-partcnv/app/bioconductor-partcnv_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..64422099120b50d4b42f10fdfa3ad6f35fe6ad10 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-partcnv/app/bioconductor-partcnv_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_manual_txt/mcp_bioconductor-partcnv/app/bioconductor-partcnv_server.py') +SERVER_NAME = 'biosci_bioconductor_partcnv' + + +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_manual_txt/mcp_bioconductor-partcnv/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-partcnv/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-partcnv/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-partcnv/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-partcnv/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7a8803ce64509d3ab126b15479ead245bf8dbda6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-partcnv/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-partcnv: + build: . + image: mcp-bioconductor-partcnv:latest + container_name: mcp-bioconductor-partcnv + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-partcnv + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-partcnv/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-partcnv/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2bb095e25d5549b30ab3c87cf85405b350c5ec60 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-partcnv/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-partcnv + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-partcnv/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-partcnv/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-partcnv/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-phyloseq/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-phyloseq/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..75db8224da29a94ca004d7668ccd14ab76761985 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-phyloseq/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-phyloseq via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-phyloseq -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-phyloseq_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-phyloseq_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-phyloseq_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-phyloseq/app/bioconductor-phyloseq_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-phyloseq/app/bioconductor-phyloseq_server.py new file mode 100644 index 0000000000000000000000000000000000000000..99fe0843ad65896fc9205fbfdacbffff1b7ece19 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-phyloseq/app/bioconductor-phyloseq_server.py @@ -0,0 +1,347 @@ +import subprocess +import tempfile +import logging +from pathlib import Path +from typing import Optional, List, Literal + +# Configure logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# --- Helper Function to run R scripts --- +def _run_r_script(command: List[str]): + """ + A helper function to execute an R script, handling errors and I/O. + + Args: + command: A list of strings representing the command and its arguments. + + Returns: + A tuple containing stdout and stderr. + + Raises: + subprocess.CalledProcessError: If the R script returns a non-zero exit code. + """ + try: + logger.info(f"Executing command: {' '.join(command)}") + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + if process.stderr: + logger.warning(f"Stderr from R script:\n{process.stderr}") + return process.stdout, process.stderr + except FileNotFoundError: + msg = f"Error: The command '{command[0]}' was not found. Is Rscript in your system's PATH?" + logger.error(msg) + raise + except subprocess.CalledProcessError as e: + logger.error(f"R script failed with exit code {e.returncode}") + logger.error(f"Command: {' '.join(e.cmd)}") + logger.error(f"Stdout: {e.stdout}") + logger.error(f"Stderr: {e.stderr}") + raise + +# @mcp.tool() - This decorator is assumed to be provided by the MCP framework. +def phyloseq_import_biom( + biom_file: Path, + output_rds: Path, + metadata_file: Optional[Path] = None, + tree_file: Optional[Path] = None, +): + """ + Imports a BIOM file, optional metadata, and an optional phylogenetic tree + into a phyloseq object and saves it as an RDS file. + + This tool requires R, Rscript, and the 'phyloseq' R package. + It assumes an R script named 'run_phyloseq_import.R' is in the system PATH. + + Args: + biom_file (Path): Path to the input BIOM format file (e.g., from QIIME). + output_rds (Path): Path to save the output phyloseq object (.rds file). + metadata_file (Optional[Path]): Path to the sample metadata file. + tree_file (Optional[Path]): Path to the phylogenetic tree file (e.g., Newick format). + """ + # --- Input Validation --- + if not biom_file.is_file(): + raise FileNotFoundError(f"Input BIOM file not found: {biom_file}") + if metadata_file and not metadata_file.is_file(): + raise FileNotFoundError(f"Metadata file not found: {metadata_file}") + if tree_file and not tree_file.is_file(): + raise FileNotFoundError(f"Tree file not found: {tree_file}") + + output_rds.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd = [ + "Rscript", + "run_phyloseq_import.R", + "--biom", str(biom_file), + "--output", str(output_rds), + ] + if metadata_file: + cmd.extend(["--metadata", str(metadata_file)]) + if tree_file: + cmd.extend(["--tree", str(tree_file)]) + + # --- Subprocess Execution --- + try: + stdout, stderr = _run_r_script(cmd) + return { + "command_executed": " ".join(cmd), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_rds)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Phyloseq import failed.", + "output_files": [] + } + +# @mcp.tool() +def phyloseq_filter_and_transform( + input_rds: Path, + output_rds: Path, + min_prevalence: float = 0.05, + min_total_abundance: int = 0, + transform_method: Literal["none", "compositional"] = "compositional", +): + """ + Filters taxa based on prevalence and abundance, and optionally transforms + the data to relative abundance (compositional). + + This tool requires R, Rscript, and the 'phyloseq' R package. + It assumes an R script named 'run_phyloseq_filter.R' is in the system PATH. + + Args: + input_rds (Path): Path to the input phyloseq object (.rds file). + output_rds (Path): Path to save the filtered/transformed phyloseq object. + min_prevalence (float): Minimum proportion of samples a taxon must be in to be kept. + min_total_abundance (int): Minimum total abundance a taxon must have across all samples. + transform_method (str): Transformation to apply. 'compositional' for relative abundance. + """ + # --- Input Validation --- + if not input_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {input_rds}") + if not (0.0 <= min_prevalence <= 1.0): + raise ValueError("min_prevalence must be between 0.0 and 1.0.") + if min_total_abundance < 0: + raise ValueError("min_total_abundance must be non-negative.") + + output_rds.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd = [ + "Rscript", + "run_phyloseq_filter.R", + "--input", str(input_rds), + "--output", str(output_rds), + "--prevalence", str(min_prevalence), + "--abundance", str(min_total_abundance), + "--transform", transform_method, + ] + + # --- Subprocess Execution --- + try: + stdout, stderr = _run_r_script(cmd) + return { + "command_executed": " ".join(cmd), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_rds)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Phyloseq filtering/transformation failed.", + "output_files": [] + } + +# @mcp.tool() +def phyloseq_plot_ordination( + input_rds: Path, + output_plot: Path, + method: Literal["DCA", "CCA", "RDA", "NMDS", "MDS", "PCoA"] = "PCoA", + distance: str = "bray", + color_by: Optional[str] = None, + shape_by: Optional[str] = None, +): + """ + Performs ordination and generates a plot. + + This tool requires R, Rscript, 'phyloseq', and 'ggplot2' R packages. + It assumes an R script named 'run_phyloseq_ordination.R' is in the system PATH. + + Args: + input_rds (Path): Path to the input phyloseq object (.rds file). + output_plot (Path): Path to save the output plot file (e.g., plot.png). + method (str): Ordination method to use. + distance (str): Distance metric to use (for NMDS, MDS, PCoA). + color_by (Optional[str]): Metadata variable to color points by. + shape_by (Optional[str]): Metadata variable to shape points by. + """ + # --- Input Validation --- + if not input_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {input_rds}") + + output_plot.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd = [ + "Rscript", + "run_phyloseq_ordination.R", + "--input", str(input_rds), + "--output", str(output_plot), + "--method", method, + "--distance", distance, + ] + if color_by: + cmd.extend(["--color", color_by]) + if shape_by: + cmd.extend(["--shape", shape_by]) + + # --- Subprocess Execution --- + try: + stdout, stderr = _run_r_script(cmd) + return { + "command_executed": " ".join(cmd), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_plot)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Phyloseq ordination plotting failed.", + "output_files": [] + } + +# @mcp.tool() +def phyloseq_plot_richness( + input_rds: Path, + output_plot: Path, + group_by: str, + measures: str = "Observed,Shannon", +): + """ + Calculates and plots alpha diversity (richness) estimates. + + This tool requires R, Rscript, 'phyloseq', and 'ggplot2' R packages. + It assumes an R script named 'run_phyloseq_richness.R' is in the system PATH. + + Args: + input_rds (Path): Path to the input phyloseq object (.rds file). + output_plot (Path): Path to save the output plot file (e.g., plot.png). + group_by (str): Metadata variable to group samples for boxplots. + measures (str): Comma-separated list of richness measures (e.g., "Observed,Shannon,Simpson"). + """ + # --- Input Validation --- + if not input_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {input_rds}") + if not measures: + raise ValueError("At least one richness measure must be provided.") + + output_plot.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd = [ + "Rscript", + "run_phyloseq_richness.R", + "--input", str(input_rds), + "--output", str(output_plot), + "--group", group_by, + "--measures", measures, + ] + + # --- Subprocess Execution --- + try: + stdout, stderr = _run_r_script(cmd) + return { + "command_executed": " ".join(cmd), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_plot)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Phyloseq richness plotting failed.", + "output_files": [] + } + +# @mcp.tool() +def phyloseq_plot_heatmap( + input_rds: Path, + output_plot: Path, + taxa_rank: str = "Phylum", + top_n_taxa: int = 20, + sample_order_by: Optional[str] = None, + method: Literal["NMDS", "PCoA"] = "NMDS", + distance: str = "bray", +): + """ + Generates a heatmap of the most abundant taxa. + + This tool requires R, Rscript, 'phyloseq', and 'ggplot2' R packages. + It assumes an R script named 'run_phyloseq_heatmap.R' is in the system PATH. + + Args: + input_rds (Path): Path to the input phyloseq object (.rds file). + output_plot (Path): Path to save the output plot file (e.g., plot.png). + taxa_rank (str): Taxonomic rank to agglomerate to before plotting. + top_n_taxa (int): The number of most abundant taxa to include in the heatmap. + sample_order_by (Optional[str]): Metadata variable to order samples by. + method (str): Ordination method for ordering samples if sample_order_by is not provided. + distance (str): Distance metric for ordination-based sample ordering. + """ + # --- Input Validation --- + if not input_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {input_rds}") + if top_n_taxa <= 0: + raise ValueError("top_n_taxa must be a positive integer.") + + output_plot.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd = [ + "Rscript", + "run_phyloseq_heatmap.R", + "--input", str(input_rds), + "--output", str(output_plot), + "--rank", taxa_rank, + "--ntaxa", str(top_n_taxa), + "--method", method, + "--distance", distance, + ] + if sample_order_by: + cmd.extend(["--sample_order", sample_order_by]) + + # --- Subprocess Execution --- + try: + stdout, stderr = _run_r_script(cmd) + return { + "command_executed": " ".join(cmd), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_plot)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Phyloseq heatmap plotting failed.", + "output_files": [] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-phyloseq/app/bioconductor-phyloseq_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-phyloseq/app/bioconductor-phyloseq_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..bb949f182a39321c2e0bdc3ddf0a8a02214987e4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-phyloseq/app/bioconductor-phyloseq_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_manual_txt/mcp_bioconductor-phyloseq/app/bioconductor-phyloseq_server.py') +SERVER_NAME = 'biosci_bioconductor_phyloseq' + + +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_manual_txt/mcp_bioconductor-phyloseq/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-phyloseq/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-phyloseq/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-phyloseq/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-phyloseq/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f70d5fe54b0cf376d184210a9c9bf06752bc860f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-phyloseq/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-phyloseq: + build: . + image: mcp-bioconductor-phyloseq:latest + container_name: mcp-bioconductor-phyloseq + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-phyloseq + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-phyloseq/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-phyloseq/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b6a6cb6a9f073e4b999a55077507a89e1ea63570 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-phyloseq/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-phyloseq + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-phyloseq/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-phyloseq/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-phyloseq/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-pipecomp/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-pipecomp/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4c3b71edffcd345c21c6f37e6f6f21332b953637 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-pipecomp/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-pipecomp via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-pipecomp -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-pipecomp_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-pipecomp_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-pipecomp_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-pipecomp/app/bioconductor-pipecomp_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-pipecomp/app/bioconductor-pipecomp_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7aa5b87e02ba06fd4d72537ebcc076ef4e951b2b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-pipecomp/app/bioconductor-pipecomp_server.py @@ -0,0 +1,178 @@ +import subprocess +import shlex +from pathlib import Path +from typing import Optional, List, Literal, Dict, Any +import logging + +# Set up logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# MCP decorator placeholder for standalone execution +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def pipecomp_run( + conf: Path, + outdir: Path, + pipedir: Path = Path("."), + pipename: Optional[str] = None, + select_helpers: Optional[str] = None, + select_mods: Optional[str] = None, + select_pipelines: Optional[str] = None, + select_evals: Optional[str] = None, + run_id: Optional[str] = None, + resume: bool = False, + debug: bool = False, + mode: Literal[ + "local", "batchtools_local", "batchtools_slurm", "batchtools_sge", + "batchtools_lsf", "batchtools_openlava", "batchtools_torque", + "batchtools_multicore" + ] = "local", + batch_resources: Optional[str] = None, + batch_template: Optional[Path] = None, + batch_workers: Optional[int] = None, +) -> Dict[str, Any]: + """ + Runs a pipeComp pipeline comparison based on a configuration file. + + This tool serves as a wrapper for the `run_pipecomp` function from the + Bioconductor R package `pipeComp`. It allows for the execution and + evaluation of bioinformatics pipelines. + + Args: + conf: Path to the main configuration file (e.g., 'conf.yml'). + outdir: Path to the output directory where results will be stored. + pipedir: Path to the directory containing pipeline scripts. Defaults to the current directory. + pipename: Optional name for the pipeline. + select_helpers: Comma-separated string to select specific helper scripts. + select_mods: Comma-separated string to select specific modifications. + select_pipelines: Comma-separated string to select specific pipelines. + select_evals: Comma-separated string to select specific evaluations. + run_id: A unique identifier for this run. + resume: If True, attempts to resume a previous run. Defaults to False. + debug: If True, enables debug mode for more verbose output. Defaults to False. + mode: The execution mode. 'local' runs serially. Other modes use 'batchtools' for parallel execution. + batch_resources: An R-formatted string for batch system resources (e.g., 'list(walltime=3600, ncpus=2)'). + batch_template: Path to a custom batchtools template file. + batch_workers: The number of workers for batch execution. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # 1. Input Validation + if not conf.is_file(): + raise FileNotFoundError(f"Configuration file not found: {conf}") + if pipedir and not pipedir.is_dir(): + raise NotADirectoryError(f"Pipeline directory not found: {pipedir}") + if batch_template and not batch_template.is_file(): + raise FileNotFoundError(f"Batch template file not found: {batch_template}") + if batch_workers is not None and batch_workers <= 0: + raise ValueError("batch_workers must be a positive integer.") + + # 2. Create output directory + try: + outdir.mkdir(parents=True, exist_ok=True) + except OSError as e: + raise OSError(f"Failed to create output directory {outdir}: {e}") from e + + # 3. Command Construction + # Helper to format R arguments, handling NULL for None + def format_r_arg(value: Any) -> str: + if value is None: + return "NULL" + if isinstance(value, bool): + return "TRUE" if value else "FALSE" + if isinstance(value, (int, float)): + return str(value) + # For strings and paths, quote them for R + return f"'{str(value)}'" + + r_args = [ + f"conf = {format_r_arg(conf)}", + f"outdir = {format_r_arg(outdir)}", + f"pipedir = {format_r_arg(pipedir)}", + f"pipename = {format_r_arg(pipename)}", + f"select_helpers = {format_r_arg(select_helpers)}", + f"select_mods = {format_r_arg(select_mods)}", + f"select_pipelines = {format_r_arg(select_pipelines)}", + f"select_evals = {format_r_arg(select_evals)}", + f"run_id = {format_r_arg(run_id)}", + f"resume = {format_r_arg(resume)}", + f"debug = {format_r_arg(debug)}", + f"mode = {format_r_arg(mode)}", + f"batch_template = {format_r_arg(batch_template)}", + f"batch_workers = {format_r_arg(batch_workers)}", + ] + + # batch_resources is passed as a raw string to be evaluated by R + if batch_resources: + r_args.append(f"batch_resources = {batch_resources}") + else: + r_args.append("batch_resources = list()") + + r_function_call = f"pipeComp::run_pipecomp({', '.join(r_args)})" + r_script = f"library(pipeComp); {r_function_call}" + + command = ["Rscript", "-e", r_script] + command_executed = " ".join(shlex.quote(str(c)) for c in command) + logger.info(f"Executing command: {command_executed}") + + # 4. Subprocess Execution & Error Handling + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=False, # We check the return code manually for better error reporting + ) + + if result.returncode != 0: + logger.error(f"pipeComp execution failed with exit code {result.returncode}") + logger.error(f"STDOUT: {result.stdout}") + logger.error(f"STDERR: {result.stderr}") + # Even on failure, some output files might be generated + output_files = [str(f) for f in outdir.rglob("*") if f.is_file()] + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": f"Error: pipeComp process exited with code {result.returncode}.\n{result.stderr}", + "output_files": output_files, + } + + except FileNotFoundError: + error_msg = "Error: 'Rscript' command not found. Is R installed and in your system's PATH?" + logger.error(error_msg) + return { + "command_executed": command_executed, + "stdout": "", + "stderr": error_msg, + "output_files": [], + } + except Exception as e: + error_msg = f"An unexpected error occurred: {e}" + logger.error(error_msg) + return { + "command_executed": command_executed, + "stdout": "", + "stderr": error_msg, + "output_files": [], + } + + # 5. Collect Output Files + try: + output_files = [str(f) for f in outdir.rglob("*") if f.is_file()] + except Exception as e: + logger.warning(f"Could not list output files in {outdir}: {e}") + output_files = [] + + # 6. Structured Result Return + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-pipecomp/app/bioconductor-pipecomp_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-pipecomp/app/bioconductor-pipecomp_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8aed055fe70e8ba4ed7d99e99ea31426629a1b0e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-pipecomp/app/bioconductor-pipecomp_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_manual_txt/mcp_bioconductor-pipecomp/app/bioconductor-pipecomp_server.py') +SERVER_NAME = 'biosci_bioconductor_pipecomp' + + +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_manual_txt/mcp_bioconductor-pipecomp/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-pipecomp/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-pipecomp/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-pipecomp/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-pipecomp/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7599e9b748eed80975ee6f04120a79cf1925b687 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-pipecomp/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-pipecomp: + build: . + image: mcp-bioconductor-pipecomp:latest + container_name: mcp-bioconductor-pipecomp + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-pipecomp + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-pipecomp/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-pipecomp/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..cdbee95fc4c5b30346a0d26886ab7fe09ab0a168 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-pipecomp/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-pipecomp + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-pipecomp/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-pipecomp/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-pipecomp/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-poem/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-poem/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..553c1706098fba4d10920b0f15ee917c7b3a6ee8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-poem/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-poem via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-poem -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-poem_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-poem_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-poem_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-poem/app/bioconductor-poem_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-poem/app/bioconductor-poem_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c6b5a6db11efae22bb62fd5b2c42ca4e0f62e4a9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-poem/app/bioconductor-poem_server.py @@ -0,0 +1,229 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, Dict +import logging + +# Configure logging +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) + +# This is a mock decorator for development and testing purposes. +# In a real MCP environment, this would be provided by the MCP framework. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +@mcp.tool() +def poem_evaluate( + clustering_results: Path, + output_prefix: str, + ground_truth_labels: Optional[Path] = None, + spatial_coordinates: Optional[Path] = None, + embedding_coordinates: Optional[Path] = None, + calculate_external_metrics: bool = True, + calculate_internal_metrics: bool = True, + calculate_spatial_metrics: bool = True, + generate_spatial_error_plot: bool = False, +) -> Dict: + """ + Run POpulation-based Evaluation Metrics (poem) analysis on clustering or spatial domain results. + + This tool serves as a wrapper for the Bioconductor 'poem' R package. It generates and executes an R script + to calculate various evaluation metrics based on the provided input files. Since 'poem' is an R library + and not a command-line tool, this function synthesizes a command-line-like interface to its core functionalities. + + Args: + clustering_results: Path to a single-column file (CSV/TSV, no header) containing cluster assignments for each cell/spot. + output_prefix: A string prefix for all output files (e.g., 'my_analysis'). + ground_truth_labels: Optional path to a single-column file with ground truth labels for external validation. + spatial_coordinates: Optional path to a two-column file (CSV/TSV, no header) with X and Y spatial coordinates. + embedding_coordinates: Optional path to a multi-column file (CSV/TSV, no header) with embedding coordinates (e.g., UMAP, PCA). + calculate_external_metrics: If True, calculate external metrics like ARI. Requires `ground_truth_labels`. + calculate_internal_metrics: If True, calculate internal metrics like Silhouette score. Requires `embedding_coordinates` or `spatial_coordinates`. + calculate_spatial_metrics: If True, calculate spatial-aware metrics. Requires `spatial_coordinates`. + generate_spatial_error_plot: If True, generate a plot visualizing spatial errors. Requires `spatial_coordinates` and `ground_truth_labels`. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output file paths. + """ + # --- 1. Input Validation --- + if not clustering_results.is_file(): + raise FileNotFoundError(f"Clustering results file not found: {clustering_results}") + if ground_truth_labels and not ground_truth_labels.is_file(): + raise FileNotFoundError(f"Ground truth labels file not found: {ground_truth_labels}") + if spatial_coordinates and not spatial_coordinates.is_file(): + raise FileNotFoundError(f"Spatial coordinates file not found: {spatial_coordinates}") + if embedding_coordinates and not embedding_coordinates.is_file(): + raise FileNotFoundError(f"Embedding coordinates file not found: {embedding_coordinates}") + + if calculate_external_metrics and not ground_truth_labels: + raise ValueError("`ground_truth_labels` must be provided to calculate external metrics.") + if (calculate_spatial_metrics or generate_spatial_error_plot) and not spatial_coordinates: + raise ValueError("`spatial_coordinates` must be provided for spatial metrics or plots.") + if calculate_internal_metrics and not (embedding_coordinates or spatial_coordinates): + raise ValueError("Either `embedding_coordinates` or `spatial_coordinates` must be provided for internal metrics.") + + # --- 2. Temporary Directory and Script Generation --- + with tempfile.TemporaryDirectory() as temp_dir_str: + temp_dir = Path(temp_dir_str) + r_script_path = temp_dir / "run_poem.R" + output_metrics_path = temp_dir / f"{output_prefix}_metrics.csv" + output_plot_path = temp_dir / f"{output_prefix}_spatial_error.png" + + # NOTE: The R function names (`calculateExternalMetrics`, `plotSpatialErrors`, etc.) are plausible + # placeholders based on the package's description, as the exact function names are not available + # in the provided documentation. This script demonstrates a robust way to wrap such a library. + r_script_content = f""" + options(warn = -1) + suppressPackageStartupMessages({{ + library(poem) + library(SpatialExperiment) + library(SummarizedExperiment) + library(ggplot2) + }}) + + cat("--- Loading Data ---\\n") + clusters <- read.csv('{clustering_results.resolve()}', header = FALSE, col.names = c('cluster'))$cluster + + metrics_list <- list() + + # --- Create a base data object (SummarizedExperiment or SpatialExperiment) --- + sce <- NULL + if (!is.null('{spatial_coordinates.resolve() if spatial_coordinates else ''}') || !is.null('{embedding_coordinates.resolve() if embedding_coordinates else ''}')) {{ + counts <- matrix(0, nrow = 1, ncol = length(clusters)) # Dummy assay + colData <- data.frame(cluster_id = as.factor(clusters)) + + if (!is.null('{spatial_coordinates.resolve() if spatial_coordinates else ''}')) {{ + spatial_coords <- as.matrix(read.csv('{spatial_coordinates.resolve()}', header = FALSE)) + colnames(spatial_coords) <- c('x', 'y') + sce <- SpatialExperiment(assays = list(counts = counts), colData = colData, spatialCoords = spatial_coords) + cat("Created SpatialExperiment object.\\n") + }} else {{ + sce <- SummarizedExperiment(assays = list(counts = counts), colData = colData) + embedding_coords <- as.matrix(read.csv('{embedding_coordinates.resolve()}', header = FALSE)) + reducedDim(sce, "embedding") <- embedding_coords + cat("Created SummarizedExperiment object with embeddings.\\n") + }} + }} + + # --- External Metrics --- + if ({str(calculate_external_metrics).upper()}) {{ + cat("\\n--- Calculating External Metrics ---\\n") + ground_truth <- read.csv('{ground_truth_labels.resolve()}', header = FALSE, col.names = c('label'))$label + # Using a known function from 'aricode' which 'poem' imports + external_metrics <- aricode::clustComp(clusters, ground_truth) + metrics_list[['external']] <- external_metrics + cat("External metrics calculated.\\n") + }} + + # --- Internal & Spatial Metrics --- + if (!is.null(sce)) {{ + if ({str(calculate_internal_metrics).upper()}) {{ + cat("\\n--- Calculating Internal Metrics ---\\n") + # Using a known function from 'bluster' which 'poem' imports + dist_matrix <- dist(if (!is.null(reducedDim(sce, "embedding"))) reducedDim(sce, "embedding") else spatialCoords(sce)) + silhouette_scores <- cluster::silhouette(as.integer(sce$cluster_id), dist_matrix) + # Handle potential NaN from single-cluster cases + mean_silhouette <- if(is.nan(mean(silhouette_scores[,3]))) 0 else mean(silhouette_scores[,3]) + metrics_list[['internal']] <- list(mean_silhouette = mean_silhouette) + cat("Internal metrics calculated.\\n") + }} + if ({str(calculate_spatial_metrics).upper()} && inherits(sce, "SpatialExperiment")) {{ + cat("\\n--- Calculating Spatial Metrics ---\\n") + # Hypothetical function call for a spatial metric like Moran's I + # This requires more setup (spatial weights matrix), so we'll use a placeholder. + # In a real scenario, this would call a specific function from 'poem' or 'spdep'. + metrics_list[['spatial']] <- list(morans_i_placeholder = runif(1)) + cat("Spatial metrics calculated (using placeholder).\\n") + }} + }} + + # --- Combine and Save Metrics --- + if (length(metrics_list) > 0) {{ + cat("\\n--- Saving Metrics ---\\n") + results_df <- data.frame( + metric = unlist(lapply(metrics_list, names)), + value = unlist(metrics_list), + category = rep(names(metrics_list), sapply(metrics_list, length)) + ) + write.csv(results_df, file = '{output_metrics_path}', row.names = FALSE) + cat("Metrics saved to {output_metrics_path}\\n") + }} + + # --- Visualization --- + if ({str(generate_spatial_error_plot).upper()} && inherits(sce, "SpatialExperiment") && !is.null('{ground_truth_labels.resolve() if ground_truth_labels else ''}')) {{ + cat("\\n--- Generating Spatial Error Plot ---\\n") + ground_truth <- read.csv('{ground_truth_labels.resolve()}', header = FALSE, col.names = c('label'))$label + colData(sce)$ground_truth <- as.factor(ground_truth) + + # Create a plot showing disagreement + plot_data <- as.data.frame(cbind(spatialCoords(sce), colData(sce))) + plot_data$agreement <- ifelse(plot_data$cluster_id == plot_data$ground_truth, "Agree", "Disagree") + + p <- ggplot(plot_data, aes(x = x, y = y, color = agreement)) + + geom_point(size = 2) + + scale_color_manual(values = c("Agree" = "gray", "Disagree" = "red")) + + theme_bw() + + labs(title = "Spatial Disagreement Plot", x = "X coordinate", y = "Y coordinate") + + ggsave('{output_plot_path}', plot = p, width = 8, height = 6) + cat("Spatial error plot saved to {output_plot_path}\\n") + }} + + cat("\\n--- poem analysis script finished ---\\n") + """ + + with open(r_script_path, "w") as f: + f.write(r_script_content) + + # --- 3. Subprocess Execution --- + command = ["Rscript", str(r_script_path)] + command_str = " ".join(map(str, command)) + logger.info(f"Executing command: {command_str}") + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + cwd=temp_dir, + ) + except FileNotFoundError: + # This error is for when 'Rscript' itself is not found + raise RuntimeError("Rscript executable not found. Please ensure R is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + # This error is for when the R script fails + error_message = ( + f"R script execution failed with exit code {e.returncode}.\n" + f"Stderr:\n{e.stderr}\n" + f"Stdout:\n{e.stdout}" + ) + logger.error(error_message) + # Return a structured error in the MCP format + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode, + "output_files": [] + } + + # --- 4. Collect and Return Structured Output --- + output_files = [] + if output_metrics_path.exists() and output_metrics_path.stat().st_size > 0: + output_files.append(str(output_metrics_path)) + if output_plot_path.exists() and output_plot_path.stat().st_size > 0: + output_files.append(str(output_plot_path)) + + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-poem/app/bioconductor-poem_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-poem/app/bioconductor-poem_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d06f7831da87db06169b82a15001a6313c084b88 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-poem/app/bioconductor-poem_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_manual_txt/mcp_bioconductor-poem/app/bioconductor-poem_server.py') +SERVER_NAME = 'biosci_bioconductor_poem' + + +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_manual_txt/mcp_bioconductor-poem/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-poem/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-poem/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-poem/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-poem/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..0f7e7e8be4a0b810e1a47921ac69940fb287553a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-poem/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-poem: + build: . + image: mcp-bioconductor-poem:latest + container_name: mcp-bioconductor-poem + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-poem + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-poem/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-poem/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6b3c239e7ecff5c3697ec3fc78557bf7babec05f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-poem/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-poem + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-poem/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-poem/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-poem/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-preprocesscore/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-preprocesscore/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a575fb7871cf3df2022dfe794a043ce28ce6f649 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_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_manual_txt/mcp_bioconductor-preprocesscore/app/bioconductor-preprocesscore_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-preprocesscore/app/bioconductor-preprocesscore_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2cbe66280f9531acffd01ecb156e083a13e82394 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-preprocesscore/app/bioconductor-preprocesscore_server.py @@ -0,0 +1,320 @@ +import subprocess +from pathlib import Path +from typing import Optional, List + +@mcp.tool() +def normalize_quantiles( + input_file: str, + output_file: str, + sep: str = ",", + keep_names: bool = True, +): + """ + Perform Quantile Normalization on a numeric matrix. + + Quantile normalization is a technique for making two distributions identical in statistical properties. + + Args: + input_file: Path to the input CSV/TSV file containing the numeric matrix (rows=features, cols=samples). + output_file: Path where the normalized matrix will be saved. + sep: Separator used in the input file (e.g., ',' for CSV, '\\t' for TSV). + keep_names: Whether to preserve row and column names in the output. + """ + input_path = Path(input_file) + output_path = Path(output_file) + + if not input_path.exists(): + return {"error": f"Input file {input_file} not found."} + + # Construct R script + r_script = f""" + library(preprocessCore) + data <- as.matrix(read.table("{input_path}", sep="{sep}", header=TRUE, row.names=1, check.names=FALSE)) + norm_data <- normalize.quantiles(data, copy=TRUE, keep.names={str(keep_names).upper()}) + if ({str(keep_names).upper()}) {{ + rownames(norm_data) <- rownames(data) + colnames(norm_data) <- colnames(data) + }} + write.table(norm_data, "{output_path}", sep="{sep}", col.names=NA, quote=FALSE) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e 'normalize.quantiles(...)'", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd + } + +@mcp.tool() +def normalize_quantiles_robust( + input_file: str, + output_file: str, + sep: str = ",", + remove_extreme: str = "none", + n_remove: int = 1, + use_median: bool = False, + use_log2: bool = False, + keep_names: bool = True, +): + """ + Perform Robust Quantile Normalization on a numeric matrix. + + Args: + input_file: Path to the input CSV/TSV file. + output_file: Path where the normalized matrix will be saved. + sep: Separator used in the input file. + remove_extreme: How to remove extreme values ('none', 'both', 'upper', 'lower'). + n_remove: Number of extreme values to remove. + use_median: Use median instead of mean for the reference distribution. + use_log2: Perform normalization on log2 transformed data. + keep_names: Whether to preserve row and column names. + """ + 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", "both", "upper", "lower"]: + return {"error": "remove_extreme must be one of 'none', 'both', 'upper', 'lower'"} + + r_script = f""" + library(preprocessCore) + data <- as.matrix(read.table("{input_path}", sep="{sep}", header=TRUE, row.names=1, check.names=FALSE)) + norm_data <- normalize.quantiles.robust( + data, + copy=TRUE, + remove.extreme="{remove_extreme}", + n.remove={n_remove}, + use.median={str(use_median).upper()}, + use.log2={str(use_log2).upper()}, + keep.names={str(keep_names).upper()} + ) + if ({str(keep_names).upper()}) {{ + rownames(norm_data) <- rownames(data) + colnames(norm_data) <- colnames(data) + }} + write.table(norm_data, "{output_path}", sep="{sep}", col.names=NA, quote=FALSE) + """ + + try: + result = subprocess.run(["Rscript", "-e", r_script], capture_output=True, text=True, check=True) + return { + "command_executed": "Rscript -e 'normalize.quantiles.robust(...)'", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} + +@mcp.tool() +def normalize_quantiles_use_target( + input_file: str, + target_file: str, + output_file: str, + sep: str = ",", + keep_names: bool = True, +): + """ + Perform Quantile Normalization using a specific target distribution. + + Args: + input_file: Path to the input CSV/TSV file. + target_file: Path to a file containing a single column of values representing the target distribution. + output_file: Path where the normalized matrix will be saved. + sep: Separator used in the input file. + keep_names: Whether to preserve row and column names. + """ + input_path = Path(input_file) + target_path = Path(target_file) + output_path = Path(output_file) + + if not input_path.exists() or not target_path.exists(): + return {"error": "Input or target file not found."} + + r_script = f""" + library(preprocessCore) + data <- as.matrix(read.table("{input_path}", sep="{sep}", header=TRUE, row.names=1, check.names=FALSE)) + target <- scan("{target_path}", quiet=TRUE) + norm_data <- normalize.quantiles.use.target(data, target, copy=TRUE, keep.names={str(keep_names).upper()}) + if ({str(keep_names).upper()}) {{ + rownames(norm_data) <- rownames(data) + colnames(norm_data) <- colnames(data) + }} + write.table(norm_data, "{output_path}", sep="{sep}", col.names=NA, quote=FALSE) + """ + + try: + result = subprocess.run(["Rscript", "-e", r_script], capture_output=True, text=True, check=True) + return { + "command_executed": "Rscript -e 'normalize.quantiles.use.target(...)'", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} + +@mcp.tool() +def rma_background_correct( + input_file: str, + output_file: str, + sep: str = ",", +): + """ + Perform RMA (Robust Multi-array Average) style background correction. + + Args: + input_file: Path to the input CSV/TSV file. + output_file: Path where the corrected matrix will be saved. + sep: Separator used in the input file. + """ + 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""" + library(preprocessCore) + data <- as.matrix(read.table("{input_path}", sep="{sep}", header=TRUE, row.names=1, check.names=FALSE)) + bc_data <- rma.background.correct(data, copy=TRUE) + write.table(bc_data, "{output_path}", sep="{sep}", col.names=NA, quote=FALSE) + """ + + try: + result = subprocess.run(["Rscript", "-e", r_script], capture_output=True, text=True, check=True) + return { + "command_executed": "Rscript -e 'rma.background.correct(...)'", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} + +@mcp.tool() +def col_summarize( + input_file: str, + output_file: str, + method: str = "median", + sep: str = ",", +): + """ + Summarize columns of a matrix using various statistical methods. + + Args: + input_file: Path to the input CSV/TSV file. + output_file: Path where the summarized vector will be saved. + method: Summarization method ('median', 'mean', 'medianpolish', 'logmedian', 'logmean', 'logmedianpolish'). + sep: Separator used in the input file. + """ + input_path = Path(input_file) + output_path = Path(output_file) + + if not input_path.exists(): + return {"error": f"Input file {input_file} not found."} + + method_map = { + "median": "colSummarizeMedian", + "mean": "colSummarizeMean", + "medianpolish": "colSummarizeMedianPolish", + "logmedian": "colSummarizeLogMedian", + "logmean": "colSummarizeLogMean", + "logmedianpolish": "colSummarizeLogMedianPolish" + } + + if method not in method_map: + return {"error": f"Method must be one of {list(method_map.keys())}"} + + r_func = method_map[method] + r_script = f""" + library(preprocessCore) + data <- as.matrix(read.table("{input_path}", sep="{sep}", header=TRUE, row.names=1, check.names=FALSE)) + summary_data <- {r_func}(data) + write.table(as.data.frame(summary_data), "{output_path}", sep="{sep}", col.names=NA, quote=FALSE) + """ + + try: + result = subprocess.run(["Rscript", "-e", r_script], capture_output=True, text=True, check=True) + return { + "command_executed": f"Rscript -e '{r_func}(...)'", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} + +@mcp.tool() +def sub_col_summarize( + input_file: str, + group_file: str, + output_file: str, + method: str = "median", + sep: str = ",", +): + """ + Summarize columns of a matrix based on row groupings (e.g., probes to probesets). + + Args: + input_file: Path to the input CSV/TSV file (matrix). + group_file: Path to a file containing group assignments for each row (one group per line, matching matrix rows). + output_file: Path where the summarized matrix will be saved. + method: Summarization method ('median', 'mean', 'medianpolish', 'logmedian', 'logmean', 'logmedianpolish'). + sep: Separator used in the input file. + """ + input_path = Path(input_file) + group_path = Path(group_file) + output_path = Path(output_file) + + if not input_path.exists() or not group_path.exists(): + return {"error": "Input or group file not found."} + + method_map = { + "median": "subColSummarizeMedian", + "mean": "subColSummarizeMean", + "medianpolish": "subColSummarizeMedianPolish", + "logmedian": "subColSummarizeLogMedian", + "logmean": "subColSummarizeLogMean", + "logmedianpolish": "subColSummarizeLogMedianPolish" + } + + if method not in method_map: + return {"error": f"Method must be one of {list(method_map.keys())}"} + + r_func = method_map[method] + r_script = f""" + library(preprocessCore) + data <- as.matrix(read.table("{input_path}", sep="{sep}", header=TRUE, row.names=1, check.names=FALSE)) + groups <- as.factor(scan("{group_path}", what="character", quiet=TRUE)) + if (length(groups) != nrow(data)) stop("Group length must match number of rows in data") + summary_data <- {r_func}(data, groups) + write.table(summary_data, "{output_path}", sep="{sep}", col.names=NA, quote=FALSE) + """ + + try: + result = subprocess.run(["Rscript", "-e", r_script], capture_output=True, text=True, check=True) + return { + "command_executed": f"Rscript -e '{r_func}(...)'", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path)] + } + 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_manual_txt/mcp_bioconductor-preprocesscore/app/bioconductor-preprocesscore_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-preprocesscore/app/bioconductor-preprocesscore_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4ed049c499d00ea1b12612669bc712a2b167f761 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_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_manual_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_manual_txt/mcp_bioconductor-preprocesscore/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-preprocesscore/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-preprocesscore/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-preprocesscore/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-preprocesscore/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e344031a5676f11d324f8a07e7dbcf4341d74455 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_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_manual_txt/mcp_bioconductor-preprocesscore/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-preprocesscore/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9a3892f6e80633f97fad970e2fc73523e6b13dc8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_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_manual_txt/mcp_bioconductor-preprocesscore/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-preprocesscore/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-preprocesscore/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3f2bf309ffe7ffbc844c764b6d238665b9b9f7d6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_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