diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/app/bioconductor-protgenerics_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/app/bioconductor-protgenerics_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0d43e09499edb8653009c563d9ff76dacfd257ec --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/app/bioconductor-protgenerics_server.py @@ -0,0 +1,281 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +@mcp.tool() +def protgenerics_check_installation() -> Dict[str, Any]: + """ + Verifies if R and the bioconductor-protgenerics package are correctly installed and accessible. + This is essential because ProtGenerics is an R-based infrastructure package. + """ + r_code = "if (!requireNamespace('ProtGenerics', quietly = TRUE)) { quit(status = 1) } else { cat(as.character(packageVersion('ProtGenerics'))) }" + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "status": "installed", + "version": result.stdout.strip(), + "command_executed": f"Rscript -e \"{r_code}\"", + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "status": "not_installed", + "error": "ProtGenerics package not found in R environment or Rscript not in PATH.", + "stdout": e.stdout, + "stderr": e.stderr + } + except FileNotFoundError: + return { + "status": "error", + "error": "Rscript command not found. Please ensure R is installed.", + "stdout": "", + "stderr": "" + } + +@mcp.tool() +def protgenerics_get_package_info() -> Dict[str, Any]: + """ + Returns detailed metadata about the ProtGenerics package, including its description, + maintainer, and dependencies. + """ + r_code = "print(packageDescription('ProtGenerics'))" + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e \"{r_code}\"", + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to retrieve package information.", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def protgenerics_list_generics() -> Dict[str, Any]: + """ + Lists all S4 generic functions exported by the ProtGenerics package. + These generics define the standard interface for proteomics data in Bioconductor. + Common generics include: mz, intensity, rtime, precursorMz, spectra, etc. + """ + r_code = "cat(paste(getNamespaceExports('ProtGenerics'), collapse='\n'))" + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + generics = result.stdout.strip().split('\n') + return { + "count": len(generics), + "generics": generics, + "command_executed": f"Rscript -e \"{r_code}\"", + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to list generics.", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def protgenerics_inspect_generic(generic_name: str) -> Dict[str, Any]: + """ + Inspects a specific S4 generic function to show its arguments and definition. + + Args: + generic_name: The name of the generic function to inspect (e.g., 'mz', 'rtime'). + """ + # Validate generic_name to prevent R injection + if not generic_name.replace(".", "").replace("_", "").isalnum(): + return {"error": "Invalid generic name format."} + + r_code = f"library(ProtGenerics); print(getGeneric('{generic_name}'))" + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "generic": generic_name, + "command_executed": f"Rscript -e \"{r_code}\"", + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": f"Failed to inspect generic '{generic_name}'. Ensure it is exported by ProtGenerics.", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def protgenerics_list_methods(generic_name: str) -> Dict[str, Any]: + """ + Lists all available methods (implementations) for a specific ProtGenerics generic. + This shows which classes (e.g., Spectra, MSnExp) implement the generic. + + Args: + generic_name: The name of the generic function (e.g., 'mz', 'intensity'). + """ + if not generic_name.replace(".", "").replace("_", "").isalnum(): + return {"error": "Invalid generic name format."} + + r_code = f"library(ProtGenerics); print(methods('{generic_name}'))" + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "generic": generic_name, + "command_executed": f"Rscript -e \"{r_code}\"", + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": f"Failed to list methods for '{generic_name}'.", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def protgenerics_execute_generic( + generic_name: str, + input_rds: str, + output_rds: Optional[str] = None, + additional_params: str = "" +) -> Dict[str, Any]: + """ + Executes a ProtGenerics S4 generic function on a proteomics object stored in an RDS file. + This is the primary way to use the generics defined in this package. + + Args: + generic_name: The name of the generic to call (e.g., 'mz', 'intensity', 'rtime', 'msLevel'). + input_rds: Path to an R RDS file containing a proteomics object (e.g., Spectra, MSnExp). + output_rds: Optional path to save the result as an RDS file if the output is a complex object. + additional_params: Optional string of additional R arguments (e.g., 'msLevel = 1'). + """ + input_path = Path(input_rds) + if not input_path.exists(): + return {"error": f"Input file {input_rds} does not exist."} + + if not generic_name.replace(".", "").replace("_", "").isalnum(): + return {"error": "Invalid generic name format."} + + # Construct R script + # We load ProtGenerics and the input object, then call the generic + r_script = [ + "library(ProtGenerics)", + f"obj <- readRDS('{input_rds}')", + f"res <- {generic_name}(obj, {additional_params})" if additional_params else f"res <- {generic_name}(obj)" + ] + + if output_rds: + r_script.append(f"saveRDS(res, '{output_rds}')") + r_script.append("cat('Result saved to RDS file.')") + else: + r_script.append("print(res)") + + full_r_code = "; ".join(r_script) + + try: + result = subprocess.run( + ["Rscript", "-e", full_r_code], + capture_output=True, + text=True, + check=True + ) + + output_files = [output_rds] if output_rds else [] + + return { + "command_executed": f"Rscript -e \"{full_r_code}\"", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + return { + "error": f"Execution of generic '{generic_name}' failed.", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def protgenerics_get_news() -> Dict[str, Any]: + """ + Retrieves the NEWS file for the ProtGenerics package to see recent changes and updates. + """ + r_code = "print(news(package='ProtGenerics'))" + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e \"{r_code}\"", + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to retrieve NEWS.", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def protgenerics_citation() -> Dict[str, Any]: + """ + Returns the citation information for the ProtGenerics package. + """ + r_code = "print(citation('ProtGenerics'))" + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e \"{r_code}\"", + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to retrieve citation.", + "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-protgenerics/app/bioconductor-protgenerics_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/app/bioconductor-protgenerics_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..50bd9824c44a6bcf1b069540edb394f2772736be --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/app/bioconductor-protgenerics_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/app/bioconductor-protgenerics_server.py') +SERVER_NAME = 'biosci_bioconductor_protgenerics' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..8e1d8d8096c32ba24e5823365e99b8573189e31a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-protgenerics: + build: . + image: mcp-bioconductor-protgenerics:latest + container_name: mcp-bioconductor-protgenerics + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-protgenerics + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d17c7b69d3b821e749569b909c88ec485482063c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-protgenerics + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..68578d8d110651dfd83095374a2f5205aead0fd1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-qvalue via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-qvalue -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-qvalue_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-qvalue_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-qvalue_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/app/bioconductor-qvalue_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/app/bioconductor-qvalue_server.py new file mode 100644 index 0000000000000000000000000000000000000000..915d583610bdd696805978617de5831048f33fb6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/app/bioconductor-qvalue_server.py @@ -0,0 +1,220 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, Dict, List, Any + +# This is a placeholder for the MCP decorator. +# It supports both `@mcp.tool` and `@mcp.tool()` styles so shim loading works. +def mcp_tool_decorator(func=None): + if func is None: + def _decorator(inner_func): + return inner_func + return _decorator + return func + +mcp = type("mcp", (), {"tool": staticmethod(mcp_tool_decorator)}) + +@mcp.tool() +def run_qvalue( + p_values_file: Path, + output_dir: Path, + output_prefix: str = "qvalue_results", + fdr_level: Optional[float] = None, + pfdr: bool = False, + lfdr_out: bool = True, + pi0_method: str = "smoother", + smooth_df: int = 3, + smooth_log_pi0: bool = False, + lambda_seq: Optional[str] = None, + plot_results: bool = True, +) -> Dict[str, Any]: + """ + Estimates q-values and local FDRs from a list of p-values using the bioconductor-qvalue R package. + + This tool takes a list of p-values and estimates their q-values and local FDR values. + The q-value of a test measures the proportion of false positives incurred (the false + discovery rate) when that particular test is called significant. The local FDR measures + the posterior probability the null hypothesis is true given the test's p-value. + + Args: + p_values_file: Path to a file containing a single column of p-values without a header. + output_dir: Path to the directory where output files will be saved. + output_prefix: Prefix for the output files. + fdr_level: The level at which to control the False Discovery Rate (FDR). Must be between 0 and 1. + pfdr: An indicator of whether the p-values are already sorted (p-value false discovery rate). + lfdr_out: If True, local FDR values will be calculated and included in the output. + pi0_method: Method for estimating pi0, the proportion of true null hypotheses. + Must be one of 'smoother' or 'bootstrap'. + smooth_df: Degrees of freedom to use in the smoother spline fit. Only used if pi0_method is 'smoother'. + smooth_log_pi0: If True and pi0_method is 'smoother', the spline is fit to log(pi0) instead of pi0. + lambda_seq: A comma-separated string of tuning parameter values for pi0 estimation (e.g., "0.1,0.2,0.3"). + If not provided, the default R sequence `seq(0, 0.95, 0.01)` is used. + plot_results: If True, generates a PDF with diagnostic plots. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output file paths. + """ + # 1. Input Validation + if not p_values_file.is_file(): + raise FileNotFoundError(f"Input file not found: {p_values_file}") + + if fdr_level is not None and not (0 <= fdr_level <= 1): + raise ValueError("fdr_level must be between 0 and 1.") + + if pi0_method not in ["smoother", "bootstrap"]: + raise ValueError("pi0_method must be either 'smoother' or 'bootstrap'.") + + if pi0_method == "smoother" and smooth_df < 3: + raise ValueError("smooth_df must be an integer >= 3 when using the 'smoother' method.") + + if lambda_seq: + try: + # Validate that all parts of the comma-separated string are numbers + [float(x) for x in lambda_seq.split(',')] + except ValueError: + raise ValueError("lambda_seq must be a comma-separated string of valid numbers.") + + # 2. File Path Handling + output_dir.mkdir(parents=True, exist_ok=True) + output_prefix_path = output_dir / output_prefix + + # 3. Prepare R script + # Convert Python types to R-compatible strings + r_fdr_level = "NULL" if fdr_level is None else str(fdr_level) + r_pfdr = "TRUE" if pfdr else "FALSE" + r_lfdr_out = "TRUE" if lfdr_out else "FALSE" + r_smooth_log_pi0 = "TRUE" if smooth_log_pi0 else "FALSE" + r_plot_results = "TRUE" if plot_results else "FALSE" + r_lambda_seq = "NULL" if lambda_seq is None else f"c({lambda_seq})" + + r_script_content = f""" + # Load required library + library(qvalue) + + # --- Parameters --- + p_values_file <- "{p_values_file.resolve()}" + output_prefix <- "{output_prefix_path.resolve()}" + + # --- Read Input Data --- + # Using tryCatch for robust error handling on file read + p_values <- tryCatch({{ + read.table(p_values_file, header = FALSE, col.names = c("pvalue"))$pvalue + }}, error = function(e) {{ + stop(paste("Error reading p-values file:", e$message)) + }}) + + # --- Build Argument List for qvalue() --- + qvalue_args <- list( + p = p_values, + fdr.level = {r_fdr_level}, + pfdr = {r_pfdr}, + lfdr.out = {r_lfdr_out}, + pi0.method = "{pi0_method}", + smooth.df = {smooth_df}, + smooth.log.pi0 = {r_smooth_log_pi0} + ) + + # Only add lambda if it was provided by the user to allow R default to be used + r_lambda_val <- {r_lambda_seq} + if (!is.null(r_lambda_val)) {{ + qvalue_args$lambda <- r_lambda_val + }} + + # --- Run qvalue Analysis --- + qobj <- tryCatch({{ + do.call(qvalue, qvalue_args) + }}, error = function(e) {{ + stop(paste("Error during qvalue execution:", e$message)) + }}) + + # --- Save Outputs --- + # 1. Main results table + results_df <- data.frame(p_values = qobj$pvalues, q_values = qobj$qvalues) + if ({r_lfdr_out} && "lfdr" %in% names(qobj) && !is.null(qobj$lfdr)) {{ + results_df$lfdr <- qobj$lfdr + }} + write.table( + results_df, + file = paste0(output_prefix, ".tsv"), + sep = "\\t", + row.names = FALSE, + quote = FALSE + ) + + # 2. Summary file + summary_file <- paste0(output_prefix, "_summary.txt") + sink(summary_file) + print(summary(qobj)) + sink() + + # 3. Plots if requested + if ({r_plot_results}) {{ + pdf(paste0(output_prefix, "_plots.pdf")) + plot(qobj) + dev.off() + }} + """ + + # 4. Subprocess Execution + command = [] + stdout_str, stderr_str = "", "" + output_files: List[str] = [] + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script: + r_script.write(r_script_content) + r_script_path = r_script.name + + command = ["Rscript", r_script_path] + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + stdout_str = process.stdout + stderr_str = process.stderr + + # 5. Collect output files + results_tsv = output_prefix_path.with_suffix(".tsv") + if results_tsv.exists(): + output_files.append(str(results_tsv)) + + summary_txt = output_dir / f"{output_prefix}_summary.txt" + if summary_txt.exists(): + output_files.append(str(summary_txt)) + + if plot_results: + plots_pdf = output_prefix_path.with_suffix("_plots.pdf") + if plots_pdf.exists(): + output_files.append(str(plots_pdf)) + + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + "output_files": [], + } + except Exception as e: + # Catch other potential errors like file I/O + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": str(e), + "return_code": 1, + "output_files": [], + } + finally: + # Clean up the temporary R script + if 'r_script_path' in locals() and Path(r_script_path).exists(): + Path(r_script_path).unlink() + + # 6. Return Structured Output + return { + "command_executed": " ".join(command), + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": output_files, + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/app/bioconductor-qvalue_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/app/bioconductor-qvalue_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..66fd1a0aa1bd9bffaf85adb687f5f1131911363e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/app/bioconductor-qvalue_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-qvalue/app/bioconductor-qvalue_server.py') +SERVER_NAME = 'biosci_bioconductor_qvalue' + + +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-qvalue/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..5fcace032ea1df85f3bedfe442d3c60483ba2189 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-qvalue: + build: . + image: mcp-bioconductor-qvalue:latest + container_name: mcp-bioconductor-qvalue + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-qvalue + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3e840a1e9a6841c8ba1b594eedc004de5ad52dc0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-qvalue + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..53e2341acd3b052248da950dc9a85edca62d94d0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-rbgl via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-rbgl -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-rbgl_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-rbgl_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-rbgl_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/app/bioconductor-rbgl_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/app/bioconductor-rbgl_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7dc3c445af0ddebd9e1ef3ade097bed635e50d5f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/app/bioconductor-rbgl_server.py @@ -0,0 +1,129 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Dict, Any + +# No mcp import needed as per instructions + +# The bioconductor-rbgl package is an R library and does not expose a direct +# command-line interface with subcommands or parameters that can be parsed +# from standard CLI help. The provided documentation confirms this by showing +# an Rscript error and directing users to R-specific documentation (vignettes, +# reference manual) for usage. +# +# To interact with RBGL, one typically writes an R script that loads the +# package and calls its functions. Since the specific R functions, their +# arguments, and return types are not detailed in the provided documentation, +# it is impossible to create individual MCP tools for "EVERY internal functions" +# of the RBGL package. +# +# This MCP tool provides a generic interface to execute R code, allowing users +# to leverage RBGL's functionality by supplying the necessary R script. + +@mcp.tool() +def execute_rbgl_r_code( + r_code: str, + output_file_patterns: Optional[List[str]] = None, + r_args: Optional[List[str]] = None, + working_directory: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Executes R code that can utilize the Bioconductor RBGL package. + + This tool provides a generic interface to run R scripts that leverage + the RBGL library for graph algorithms. Since RBGL is an R package and + does not expose a direct command-line interface, users are expected + to provide the R code directly. The R code should typically include + `library(RBGL)` to load the package. + + Args: + r_code: A string containing the R code to execute. This code should + include `library(RBGL)` and calls to RBGL functions as needed. + output_file_patterns: An optional list of glob patterns (e.g., "*.csv", "output_*.txt") + to identify and collect output files generated by the R script + within the working directory. + r_args: Optional list of additional arguments to pass to Rscript. + These can be accessed within the R script via `commandArgs(trailingOnly=TRUE)`. + working_directory: Optional path to a directory where the R script + should be executed. If not provided, a temporary + directory will be used. + + Returns: + A dictionary containing the command executed, stdout, stderr, and + a list of any output files generated. + """ + if not r_code: + raise ValueError("R code cannot be empty.") + + command = ["Rscript", "-e", r_code] + + if r_args: + command.extend(r_args) + + output_files: List[Path] = [] + temp_dir: Optional[tempfile.TemporaryDirectory] = None + actual_working_dir: Path + + try: + if working_directory: + if not working_directory.is_dir(): + raise ValueError(f"Working directory '{working_directory}' does not exist or is not a directory.") + actual_working_dir = working_directory + else: + temp_dir = tempfile.TemporaryDirectory() + actual_working_dir = Path(temp_dir.name) + + process = subprocess.run( + command, + cwd=actual_working_dir, + capture_output=True, + text=True, + check=True + ) + + # Collect output files based on provided patterns or list all if no patterns + if output_file_patterns: + for pattern in output_file_patterns: + for f in actual_working_dir.glob(pattern): + if f.is_file(): + output_files.append(f) + else: + # If no patterns, collect all non-hidden files in the working directory + for f in actual_working_dir.iterdir(): + if f.is_file() and not f.name.startswith("."): + output_files.append(f) + + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(f) for f in output_files] + } + + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Rscript execution failed with exit code {e.returncode}", + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: Rscript command not found. Is R installed and in PATH?", + "error": "Rscript command not found", + "output_files": [] + } + except ValueError as e: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": str(e), + "error": "Input validation error", + "output_files": [] + } + finally: + if temp_dir: + temp_dir.cleanup() diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/app/bioconductor-rbgl_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/app/bioconductor-rbgl_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..59269eb06c66f383f145a871c5189f7db0569239 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/app/bioconductor-rbgl_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-rbgl/app/bioconductor-rbgl_server.py') +SERVER_NAME = 'biosci_bioconductor_rbgl' + + +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-rbgl/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..08a18e7897455296f14df20991ebb996529e7791 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-rbgl: + build: . + image: mcp-bioconductor-rbgl:latest + container_name: mcp-bioconductor-rbgl + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-rbgl + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8476e0fe29a2433391cebe3367ae4506229d61e0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-rbgl + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-reactomegsa.data/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-reactomegsa.data/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a70a7575b3d2098adb631cc68af8591f602439f8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-reactomegsa.data/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-reactomegsa.data via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-reactomegsa.data -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-reactomegsa.data_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-reactomegsa.data_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-reactomegsa.data_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-reactomegsa.data/app/bioconductor-reactomegsa.data_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-reactomegsa.data/app/bioconductor-reactomegsa.data_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9e69706a8619f43b6bfcc2d9c4147165e996558a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-reactomegsa.data/app/bioconductor-reactomegsa.data_server.py @@ -0,0 +1,112 @@ +import subprocess +from pathlib import Path +from typing import Optional, List + +@mcp.tool() +def get_citation( + rscript_path: Path = Path("Rscript"), + output_file: Optional[Path] = None, +) -> dict: + """ + Retrieves the citation information for the bioconductor-reactomegsa.data R package. + + This package is a Bioconductor data package for the R environment and does not + expose direct command-line subcommands in the traditional sense. This function + wraps an Rscript call to ensure the package and its manager (BiocManager) are + installed, then loads the package, and finally extracts its citation information. + + Args: + rscript_path: Path to the Rscript executable. Defaults to 'Rscript', + assuming it's in the system's PATH. + output_file: Optional path to save the citation output to a file. + If not provided, the citation will be returned in stdout. + + Returns: + A dictionary containing the command executed, stdout, stderr, and + a list of any output files. + """ + # Validate rscript_path + rscript_executable: str + if not rscript_path.is_absolute(): + try: + # Check if 'Rscript' is in PATH + subprocess.run(["which", "Rscript"], check=True, capture_output=True) + rscript_executable = "Rscript" + except subprocess.CalledProcessError: + raise FileNotFoundError( + f"Rscript not found in system PATH. Please ensure R is installed " + "and Rscript is accessible, or provide an absolute path to Rscript." + ) + elif not rscript_path.is_file(): + raise FileNotFoundError(f"Rscript not found at the specified path: {rscript_path}") + else: + rscript_executable = str(rscript_path) + + # R command to: + # 1. Install BiocManager if not already installed. + # 2. Install ReactomeGSA.data if not already installed (using BiocManager). + # 3. Load the ReactomeGSA.data library. + # 4. Print the citation information. + r_code = ( + 'if (!require("BiocManager", quietly = TRUE)) install.packages("BiocManager"); ' + 'if (!require("ReactomeGSA.data", quietly = TRUE)) BiocManager::install("ReactomeGSA.data", update = FALSE, ask = FALSE); ' + 'library(ReactomeGSA.data); ' + 'print(citation("ReactomeGSA.data"))' + ) + + command = [ + rscript_executable, + "-e", + r_code + ] + + stdout_capture = "" + stderr_capture = "" + output_files_list: List[str] = [] + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True + ) + stdout_capture = process.stdout + stderr_capture = process.stderr + + if output_file: + output_file.parent.mkdir(parents=True, exist_ok=True) + output_file.write_text(stdout_capture) + output_files_list.append(str(output_file)) + + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": f"Rscript execution failed with exit code {e.returncode}. Stderr: {e.stderr}" + } + except FileNotFoundError as e: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": str(e), + "output_files": [], + "error": f"Executable not found: {e}" + } + except Exception as e: + return { + "command_executed": " ".join(command), + "stdout": stdout_capture, + "stderr": stderr_capture, + "output_files": [], + "error": f"An unexpected error occurred: {str(e)}" + } + + return { + "command_executed": " ".join(command), + "stdout": stdout_capture, + "stderr": stderr_capture, + "output_files": output_files_list + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-reactomegsa.data/app/bioconductor-reactomegsa.data_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-reactomegsa.data/app/bioconductor-reactomegsa.data_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b75a01e080f30d4c1e71f1d1aadf079f6ec920ba --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-reactomegsa.data/app/bioconductor-reactomegsa.data_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-reactomegsa.data/app/bioconductor-reactomegsa.data_server.py') +SERVER_NAME = 'biosci_bioconductor_reactomegsa_data' + + +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-reactomegsa.data/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-reactomegsa.data/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..60dee9c55100465544eb8f835941791188519aa1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-reactomegsa.data/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-reactomegsa.data: + build: . + image: mcp-bioconductor-reactomegsa.data:latest + container_name: mcp-bioconductor-reactomegsa.data + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-reactomegsa.data + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-reactomegsa.data/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-reactomegsa.data/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ac58425c4535a7f2f525163a6ee1f38aff304abc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-reactomegsa.data/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-reactomegsa.data + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-reactomegsa.data/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-reactomegsa.data/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-reactomegsa.data/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-regionalst/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-regionalst/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c15f24ba075f7a6d16db8ee68a73783ae7f0e06b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-regionalst/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-regionalst via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-regionalst -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-regionalst_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-regionalst_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-regionalst_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-regionalst/app/bioconductor-regionalst_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-regionalst/app/bioconductor-regionalst_server.py new file mode 100644 index 0000000000000000000000000000000000000000..459518d27082e704b1e533b33780784b50c40e16 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-regionalst/app/bioconductor-regionalst_server.py @@ -0,0 +1,459 @@ +import subprocess +import tempfile +import shutil +from pathlib import Path +from typing import Optional, List, Dict, Any + +# MCP decorators are omitted as per the instructions, but would be present in a real MCP file. +# from mcp import tool + +# --- R Script Templates --- +# These strings contain self-contained R scripts that will be executed. +# They use the 'optparse' library to accept command-line arguments. + +REGIONAL_LIMMA_RSCRIPT = """ +# R script to run regionalST::regional_limma +suppressPackageStartupMessages(library(optparse)) +suppressPackageStartupMessages(library(regionalST)) +suppressPackageStartupMessages(library(SpatialExperiment)) + +option_list <- list( + make_option(c("-i", "--input_rds"), type="character", help="Path to input SpatialExperiment RDS file."), + make_option(c("-o", "--output_csv"), type="character", help="Path for the output CSV file."), + make_option(c("--col_group"), type="character", help="Column name for grouping variable."), + make_option(c("--group1"), type="character", help="Name of the first group for comparison."), + make_option(c("--group2"), type="character", default=NULL, help="Name of the second group (optional)."), + make_option(c("--col_covariate"), type="character", default=NULL, help="Comma-separated column names for covariates (optional)."), + make_option(c("--n_neighbors"), type="integer", default=6, help="Number of neighbors."), + make_option(c("--log2fc_threshold"), type="double", default=0, help="Log2 fold change threshold."), + make_option(c("--pval_threshold"), type="double", default=1, help="P-value threshold."), + make_option(c("--assay_name"), type="character", default="logcounts", help="Name of the assay to use.") +) + +opt_parser <- OptionParser(option_list=option_list) +opt <- parse_args(opt_parser) + +if (is.null(opt$input_rds) || is.null(opt$output_csv) || is.null(opt$col_group) || is.null(opt$group1)) { + print_help(opt_parser) + stop("Missing required arguments: --input_rds, --output_csv, --col_group, --group1", call.=FALSE) +} + +spe <- readRDS(opt$input_rds) + +covariates <- NULL +if (!is.null(opt$col_covariate)) { + covariates <- strsplit(opt$col_covariate, ",")[[1]] +} + +results <- regional_limma( + spe = spe, + col_group = opt$col_group, + col_covariate = covariates, + group1 = opt$group1, + group2 = opt$group2, + n_neighbors = opt$n_neighbors, + log2fc_threshold = opt$log2fc_threshold, + pval_threshold = opt$pval_threshold, + assay_name = opt$assay_name +) + +write.csv(as.data.frame(results), file = opt$output_csv, row.names = FALSE) + +cat("regional_limma analysis complete. Results saved to", opt$output_csv, "\\n") +""" + +REGIONAL_VOOM_RSCRIPT = """ +# R script to run regionalST::regional_voom +suppressPackageStartupMessages(library(optparse)) +suppressPackageStartupMessages(library(regionalST)) +suppressPackageStartupMessages(library(SpatialExperiment)) + +option_list <- list( + make_option(c("-i", "--input_rds"), type="character", help="Path to input SpatialExperiment RDS file."), + make_option(c("-o", "--output_csv"), type="character", help="Path for the output CSV file."), + make_option(c("--col_group"), type="character", help="Column name for grouping variable."), + make_option(c("--group1"), type="character", help="Name of the first group for comparison."), + make_option(c("--group2"), type="character", default=NULL, help="Name of the second group (optional)."), + make_option(c("--col_covariate"), type="character", default=NULL, help="Comma-separated column names for covariates (optional)."), + make_option(c("--n_neighbors"), type="integer", default=6, help="Number of neighbors."), + make_option(c("--log2fc_threshold"), type="double", default=0, help="Log2 fold change threshold."), + make_option(c("--pval_threshold"), type="double", default=1, help="P-value threshold."), + make_option(c("--assay_name"), type="character", default="counts", help="Name of the assay to use.") +) + +opt_parser <- OptionParser(option_list=option_list) +opt <- parse_args(opt_parser) + +if (is.null(opt$input_rds) || is.null(opt$output_csv) || is.null(opt$col_group) || is.null(opt$group1)) { + print_help(opt_parser) + stop("Missing required arguments: --input_rds, --output_csv, --col_group, --group1", call.=FALSE) +} + +spe <- readRDS(opt$input_rds) + +covariates <- NULL +if (!is.null(opt$col_covariate)) { + covariates <- strsplit(opt$col_covariate, ",")[[1]] +} + +results <- regional_voom( + spe = spe, + col_group = opt$col_group, + col_covariate = covariates, + group1 = opt$group1, + group2 = opt$group2, + n_neighbors = opt$n_neighbors, + log2fc_threshold = opt$log2fc_threshold, + pval_threshold = opt$pval_threshold, + assay_name = opt$assay_name +) + +write.csv(as.data.frame(results), file = opt$output_csv, row.names = FALSE) + +cat("regional_voom analysis complete. Results saved to", opt$output_csv, "\\n") +""" + +REGIONAL_NONPARAMETRIC_RSCRIPT_TEMPLATE = """ +# R script to run regionalST non-parametric tests +suppressPackageStartupMessages(library(optparse)) +suppressPackageStartupMessages(library(regionalST)) +suppressPackageStartupMessages(library(SpatialExperiment)) + +option_list <- list( + make_option(c("-i", "--input_rds"), type="character", help="Path to input SpatialExperiment RDS file."), + make_option(c("-o", "--output_csv"), type="character", help="Path for the output CSV file."), + make_option(c("--col_group"), type="character", help="Column name for grouping variable."), + make_option(c("--group1"), type="character", help="Name of the first group for comparison."), + make_option(c("--group2"), type="character", default=NULL, help="Name of the second group (optional)."), + make_option(c("--n_neighbors"), type="integer", default=6, help="Number of neighbors."), + make_option(c("--log2fc_threshold"), type="double", default=0, help="Log2 fold change threshold."), + make_option(c("--pval_threshold"), type="double", default=1, help="P-value threshold."), + make_option(c("--assay_name"), type="character", default="logcounts", help="Name of the assay to use."), + make_option(c("--test_function"), type="character", help="The R function to call (e.g., 'regional_wilcox').") +) + +opt_parser <- OptionParser(option_list=option_list) +opt <- parse_args(opt_parser) + +if (is.null(opt$input_rds) || is.null(opt$output_csv) || is.null(opt$col_group) || is.null(opt$group1) || is.null(opt$test_function)) { + print_help(opt_parser) + stop("Missing required arguments: --input_rds, --output_csv, --col_group, --group1, --test_function", call.=FALSE) +} + +spe <- readRDS(opt$input_rds) + +# Dynamically get the function from the regionalST package +test_func <- get(opt$test_function, asNamespace("regionalST")) + +results <- test_func( + spe = spe, + col_group = opt$col_group, + group1 = opt$group1, + group2 = opt$group2, + n_neighbors = opt$n_neighbors, + log2fc_threshold = opt$log2fc_threshold, + pval_threshold = opt$pval_threshold, + assay_name = opt$assay_name +) + +write.csv(as.data.frame(results), file = opt$output_csv, row.names = FALSE) + +cat(paste(opt$test_function, "analysis complete. Results saved to", opt$output_csv, "\\n")) +""" + +def _run_regionalst_script( + script_content: str, + cmd_args: List[str], + output_filename: str +) -> Dict[str, Any]: + """ + Internal helper to execute a regionalST R script. + + This function sets up a temporary environment, writes the provided R script + to a file, executes it with Rscript, and captures the output. It is not + intended to be an MCP tool itself. + + Args: + script_content: A string containing the R script to execute. + cmd_args: A list of command-line arguments for the R script. + output_filename: The name of the output file to be generated. + + Returns: + A dictionary containing execution details and output file paths. + """ + if not shutil.which("Rscript"): + raise RuntimeError( + "Rscript executable not found in system PATH. " + "Please install R and ensure Rscript is accessible." + ) + + with tempfile.TemporaryDirectory() as temp_dir: + temp_path = Path(temp_dir) + r_script_path = temp_path / "run_script.R" + output_csv_path = temp_path / output_filename + + r_script_path.write_text(script_content) + + command = [ + "Rscript", str(r_script_path), + *cmd_args, + "--output_csv", str(output_csv_path) + ] + command_str = " ".join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + cwd=temp_path, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"results_csv": str(output_csv_path)} + } + except subprocess.CalledProcessError as e: + error_message = ( + f"R script execution failed with return code {e.returncode}.\n" + f"STDOUT:\n{e.stdout}\n" + f"STDERR:\n{e.stderr}" + ) + raise RuntimeError(error_message) from e + +# @mcp.tool() +def regional_limma( + input_rds: Path, + col_group: str, + group1: str, + group2: Optional[str] = None, + col_covariate: Optional[List[str]] = None, + n_neighbors: int = 6, + log2fc_threshold: float = 0.0, + pval_threshold: float = 1.0, + assay_name: str = "logcounts", +) -> Dict[str, Any]: + """ + Performs regional differential expression analysis using limma. + + This function wraps `regional_limma` from the R package `regionalST`, suitable + for analyzing microarray data or transformed RNA-seq data (e.g., log-CPM). + It requires R, Rscript, and the Bioconductor packages `regionalST`, + `SpatialExperiment`, and `optparse` to be installed. + + Args: + input_rds: Path to the input SpatialExperiment object saved as an RDS file. + col_group: The column name in `colData` that defines the groups to compare. + group1: The name of the first group for comparison. + group2: The name of the second group. If not provided, performs a one-vs-all comparison. + col_covariate: List of column names in `colData` to use as covariates. + n_neighbors: The number of nearest neighbors to consider for each spot. + log2fc_threshold: The log2 fold change threshold for determining significance. + pval_threshold: The p-value threshold for determining significance. + assay_name: The name of the assay in the SpatialExperiment object to use. + + Returns: + A dictionary with the command, stdout, stderr, and output CSV file path. + """ + if not input_rds.is_file(): + raise FileNotFoundError(f"Input file not found: {input_rds}") + if n_neighbors <= 0: + raise ValueError("n_neighbors must be a positive integer.") + if not (0.0 <= pval_threshold <= 1.0): + raise ValueError("pval_threshold must be between 0.0 and 1.0.") + + cmd_args = [ + "--input_rds", str(input_rds), + "--col_group", col_group, + "--group1", group1, + "--n_neighbors", str(n_neighbors), + "--log2fc_threshold", str(log2fc_threshold), + "--pval_threshold", str(pval_threshold), + "--assay_name", assay_name, + ] + if group2: + cmd_args.extend(["--group2", group2]) + if col_covariate: + cmd_args.extend(["--col_covariate", ",".join(col_covariate)]) + + return _run_regionalst_script( + script_content=REGIONAL_LIMMA_RSCRIPT, + cmd_args=cmd_args, + output_filename="regional_limma_results.csv" + ) + +# @mcp.tool() +def regional_voom( + input_rds: Path, + col_group: str, + group1: str, + group2: Optional[str] = None, + col_covariate: Optional[List[str]] = None, + n_neighbors: int = 6, + log2fc_threshold: float = 0.0, + pval_threshold: float = 1.0, + assay_name: str = "counts", +) -> Dict[str, Any]: + """ + Performs regional differential expression analysis using voom. + + This function wraps `regional_voom` from `regionalST`, suitable for RNA-seq + count data. It requires R, Rscript, and the Bioconductor packages `regionalST`, + `SpatialExperiment`, and `optparse` to be installed. + + Args: + input_rds: Path to the input SpatialExperiment object saved as an RDS file. + col_group: The column name in `colData` that defines the groups to compare. + group1: The name of the first group for comparison. + group2: The name of the second group. If not provided, performs a one-vs-all comparison. + col_covariate: List of column names in `colData` to use as covariates. + n_neighbors: The number of nearest neighbors to consider for each spot. + log2fc_threshold: The log2 fold change threshold for determining significance. + pval_threshold: The p-value threshold for determining significance. + assay_name: The name of the assay containing raw counts. + + Returns: + A dictionary with the command, stdout, stderr, and output CSV file path. + """ + if not input_rds.is_file(): + raise FileNotFoundError(f"Input file not found: {input_rds}") + if n_neighbors <= 0: + raise ValueError("n_neighbors must be a positive integer.") + if not (0.0 <= pval_threshold <= 1.0): + raise ValueError("pval_threshold must be between 0.0 and 1.0.") + + cmd_args = [ + "--input_rds", str(input_rds), + "--col_group", col_group, + "--group1", group1, + "--n_neighbors", str(n_neighbors), + "--log2fc_threshold", str(log2fc_threshold), + "--pval_threshold", str(pval_threshold), + "--assay_name", assay_name, + ] + if group2: + cmd_args.extend(["--group2", group2]) + if col_covariate: + cmd_args.extend(["--col_covariate", ",".join(col_covariate)]) + + return _run_regionalst_script( + script_content=REGIONAL_VOOM_RSCRIPT, + cmd_args=cmd_args, + output_filename="regional_voom_results.csv" + ) + +# @mcp.tool() +def regional_wilcox( + input_rds: Path, + col_group: str, + group1: str, + group2: Optional[str] = None, + n_neighbors: int = 6, + log2fc_threshold: float = 0.0, + pval_threshold: float = 1.0, + assay_name: str = "logcounts", +) -> Dict[str, Any]: + """ + Performs regional DE analysis using the Wilcoxon rank-sum test. + + This function wraps `regional_wilcox` from `regionalST`, a non-parametric test. + It requires R, Rscript, and the Bioconductor packages `regionalST`, + `SpatialExperiment`, and `optparse` to be installed. + + Args: + input_rds: Path to the input SpatialExperiment object saved as an RDS file. + col_group: The column name in `colData` that defines the groups to compare. + group1: The name of the first group for comparison. + group2: The name of the second group. If not provided, performs a one-vs-all comparison. + n_neighbors: The number of nearest neighbors to consider for each spot. + log2fc_threshold: The log2 fold change threshold for determining significance. + pval_threshold: The p-value threshold for determining significance. + assay_name: The name of the assay to use for analysis. + + Returns: + A dictionary with the command, stdout, stderr, and output CSV file path. + """ + if not input_rds.is_file(): + raise FileNotFoundError(f"Input file not found: {input_rds}") + if n_neighbors <= 0: + raise ValueError("n_neighbors must be a positive integer.") + if not (0.0 <= pval_threshold <= 1.0): + raise ValueError("pval_threshold must be between 0.0 and 1.0.") + + cmd_args = [ + "--input_rds", str(input_rds), + "--col_group", col_group, + "--group1", group1, + "--n_neighbors", str(n_neighbors), + "--log2fc_threshold", str(log2fc_threshold), + "--pval_threshold", str(pval_threshold), + "--assay_name", assay_name, + "--test_function", "regional_wilcox", + ] + if group2: + cmd_args.extend(["--group2", group2]) + + return _run_regionalst_script( + script_content=REGIONAL_NONPARAMETRIC_RSCRIPT_TEMPLATE, + cmd_args=cmd_args, + output_filename="regional_wilcox_results.csv" + ) + +# @mcp.tool() +def regional_ttest( + input_rds: Path, + col_group: str, + group1: str, + group2: Optional[str] = None, + n_neighbors: int = 6, + log2fc_threshold: float = 0.0, + pval_threshold: float = 1.0, + assay_name: str = "logcounts", +) -> Dict[str, Any]: + """ + Performs regional differential expression analysis using a t-test. + + This function wraps `regional_ttest` from `regionalST`, a parametric test. + It requires R, Rscript, and the Bioconductor packages `regionalST`, + `SpatialExperiment`, and `optparse` to be installed. + + Args: + input_rds: Path to the input SpatialExperiment object saved as an RDS file. + col_group: The column name in `colData` that defines the groups to compare. + group1: The name of the first group for comparison. + group2: The name of the second group. If not provided, performs a one-vs-all comparison. + n_neighbors: The number of nearest neighbors to consider for each spot. + log2fc_threshold: The log2 fold change threshold for determining significance. + pval_threshold: The p-value threshold for determining significance. + assay_name: The name of the assay to use for analysis. + + Returns: + A dictionary with the command, stdout, stderr, and output CSV file path. + """ + if not input_rds.is_file(): + raise FileNotFoundError(f"Input file not found: {input_rds}") + if n_neighbors <= 0: + raise ValueError("n_neighbors must be a positive integer.") + if not (0.0 <= pval_threshold <= 1.0): + raise ValueError("pval_threshold must be between 0.0 and 1.0.") + + cmd_args = [ + "--input_rds", str(input_rds), + "--col_group", col_group, + "--group1", group1, + "--n_neighbors", str(n_neighbors), + "--log2fc_threshold", str(log2fc_threshold), + "--pval_threshold", str(pval_threshold), + "--assay_name", assay_name, + "--test_function", "regional_ttest", + ] + if group2: + cmd_args.extend(["--group2", group2]) + + return _run_regionalst_script( + script_content=REGIONAL_NONPARAMETRIC_RSCRIPT_TEMPLATE, + cmd_args=cmd_args, + output_filename="regional_ttest_results.csv" + ) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-regionalst/app/bioconductor-regionalst_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-regionalst/app/bioconductor-regionalst_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..82cad80b9213a74c46c817678d3e3c3aa2f09792 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-regionalst/app/bioconductor-regionalst_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-regionalst/app/bioconductor-regionalst_server.py') +SERVER_NAME = 'biosci_bioconductor_regionalst' + + +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-regionalst/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-regionalst/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..eea8e47f483f78be375b2bc87e47096e74695d82 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-regionalst/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-regionalst: + build: . + image: mcp-bioconductor-regionalst:latest + container_name: mcp-bioconductor-regionalst + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-regionalst + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-regionalst/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-regionalst/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7df595636a62837fd9e58013cae1ae3021f57043 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-regionalst/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-regionalst + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-regionalst/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-regionalst/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-regionalst/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1d6c698e62ad8b91053eed83fd9f8d55d7f0f868 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-rgraphviz via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-rgraphviz -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-rgraphviz_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-rgraphviz_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-rgraphviz_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/app/bioconductor-rgraphviz_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/app/bioconductor-rgraphviz_server.py new file mode 100644 index 0000000000000000000000000000000000000000..bfdbec4a9a5f716e4a459c2f09e4bce0ac814a04 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/app/bioconductor-rgraphviz_server.py @@ -0,0 +1,204 @@ +import subprocess +import tempfile +import textwrap +from pathlib import Path +from typing import Dict, List, Optional + +# In a real MCP environment, this would be imported. +# from mcp import tool as mcp_tool +# For the purpose of this exercise, we define a placeholder. +class mcp: + @staticmethod + def tool(func=None, **kwargs): + if func: + return func + return lambda f: f + +@mcp.tool +def plot_graph( + graph_file: Path, + output_file: Path, + layout_engine: str = "dot", + output_format: str = "png", + graph_attributes: Optional[str] = None, + node_attributes: Optional[str] = None, + edge_attributes: Optional[str] = None, +) -> Dict: + """ + Generates a graph visualization using the Rgraphviz library. + + This tool takes a graph defined in a simple edge list format (CSV with 'from' + and 'to' headers) and uses Rgraphviz to create a visual representation, + saving it to a specified output file. + + Args: + graph_file: Path to the input graph file. Must be a CSV with 'from' and 'to' columns. + output_file: Path to save the output image file. + layout_engine: The Graphviz layout algorithm to use. + Valid options: 'dot', 'neato', 'twopi', 'circo', 'fdp'. + output_format: The format of the output image. + Valid options: 'png', 'pdf', 'svg', 'jpg'. + graph_attributes: Semicolon-separated key-value pairs for global graph attributes + (e.g., "rankdir=LR;bgcolor=lightblue;"). + node_attributes: Semicolon-separated key-value pairs for global node attributes + (e.g., "shape=ellipse;color=blue;"). + edge_attributes: Semicolon-separated key-value pairs for global edge attributes + (e.g., "color=red;"). + + Returns: + A dictionary containing the execution command, stdout, stderr, and a list of output files. + """ + # 1. Input Validation + if not graph_file.is_file(): + raise FileNotFoundError(f"Input graph file not found: {graph_file}") + + allowed_layouts = ["dot", "neato", "twopi", "circo", "fdp"] + if layout_engine not in allowed_layouts: + raise ValueError(f"Invalid layout_engine '{layout_engine}'. Must be one of {allowed_layouts}.") + + allowed_formats = ["png", "pdf", "svg", "jpg"] + if output_format not in allowed_formats: + raise ValueError(f"Invalid output_format '{output_format}'. Must be one of {allowed_formats}.") + + if not output_file.parent.exists(): + output_file.parent.mkdir(parents=True, exist_ok=True) + + # 2. R Script Generation + r_script_content = textwrap.dedent(""" + # Load required libraries + # Suppress startup messages for cleaner output + suppressPackageStartupMessages(library(graph)) + suppressPackageStartupMessages(library(Rgraphviz)) + + # Get command line arguments + args <- commandArgs(trailingOnly = TRUE) + if (length(args) < 4) { + stop("Usage: Rscript plot_script.R [graph_attrs] [node_attrs] [edge_attrs]", call. = FALSE) + } + + inputFile <- args[1] + outputFile <- args[2] + layoutEngine <- args[3] + outputFormat <- args[4] + + # Read the edge list + edge_df <- read.csv(inputFile, header = TRUE, stringsAsFactors = FALSE) + + # Check for correct columns + if (!all(c("from", "to") %in% names(edge_df))) { + stop("Input CSV must have 'from' and 'to' columns.", call. = FALSE) + } + + # Create a graphNEL object from the edge list + g <- ftM2graphNEL(as.matrix(edge_df), edgemode = "directed") + + # Helper function to parse attribute strings like "key1=val1;key2=val2" + parse_attrs <- function(attr_string) { + if (is.na(attr_string) || nchar(attr_string) == 0) { + return(list()) + } + # Split by semicolon, but not if it's inside quotes + pairs <- strsplit(attr_string, ";(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", perl=TRUE)[[1]] + attrs <- list() + for (pair in pairs) { + if (grepl("=", pair)) { + kv <- strsplit(pair, "=")[[1]] + key <- trimws(kv[1]) + value <- trimws(kv[2]) + # Try to convert to numeric if possible, otherwise keep as string + if (!is.na(suppressWarnings(as.numeric(value)))) { + attrs[[key]] <- as.numeric(value) + } else { + # Remove quotes if they exist + attrs[[key]] <- gsub('^"|"$', '', value) + } + } + } + return(attrs) + } + + graphAttrs <- if (length(args) >= 5) parse_attrs(args[5]) else list() + nodeAttrs <- if (length(args) >= 6) parse_attrs(args[6]) else list() + edgeAttrs <- if (length(args) >= 7) parse_attrs(args[7]) else list() + + # Open the correct graphics device based on output format + if (outputFormat == "png") { + png(outputFile, width=1024, height=768, res=100) + } else if (outputFormat == "pdf") { + pdf(outputFile) + } else if (outputFormat == "svg") { + svg(outputFile) + } else if (outputFormat == "jpg") { + jpeg(outputFile, width=1024, height=768, res=100) + } else { + stop(paste("Unsupported output format:", outputFormat), call. = FALSE) + } + + # Plot the graph with specified attributes + plot(g, layoutEngine, attrs=list(graph=graphAttrs, node=nodeAttrs, edge=edgeAttrs)) + + # Close the device + dev.off() + + cat(paste("Graph successfully plotted to", outputFile, "\\n")) + """) + + # 3. Subprocess Execution + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R") as r_script_file: + r_script_file.write(r_script_content) + r_script_path = Path(r_script_file.name) + + cmd = [ + "Rscript", + str(r_script_path), + str(graph_file), + str(output_file), + layout_engine, + output_format, + ] + + # Add optional attributes to the command if they are provided + # Pass them as single arguments to prevent shell interpretation issues + cmd.append(graph_attributes if graph_attributes else "") + cmd.append(node_attributes if node_attributes else "") + cmd.append(edge_attributes if edge_attributes else "") + + command_executed = " ".join(f'"{arg}"' if ' ' in arg else arg for arg in cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + stdout = result.stdout + stderr = result.stderr + output_files = [str(output_file)] if output_file.exists() else [] + + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: Rscript not found. Please ensure R is installed and in your PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + finally: + # Clean up the temporary R script + if r_script_path.exists(): + r_script_path.unlink() + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/app/bioconductor-rgraphviz_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/app/bioconductor-rgraphviz_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..86d31a6bd23886f0c4eb7a5645b1a52e644f8967 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/app/bioconductor-rgraphviz_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-rgraphviz/app/bioconductor-rgraphviz_server.py') +SERVER_NAME = 'biosci_bioconductor_rgraphviz' + + +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-rgraphviz/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..514d8237e7a05487cd9859004648dfd4d5d2c069 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-rgraphviz: + build: . + image: mcp-bioconductor-rgraphviz:latest + container_name: mcp-bioconductor-rgraphviz + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-rgraphviz + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a125a84e5394fe87afdc748ab441a528f3c24a44 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-rgraphviz + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..23b2b83e0e1daf22cc0c286cbebf06a5f2214728 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-rhdf5 via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-rhdf5 -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-rhdf5_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-rhdf5_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-rhdf5_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/app/bioconductor-rhdf5_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/app/bioconductor-rhdf5_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4ff5e7e6237cd7aca1efeb5e72ab94820334216f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/app/bioconductor-rhdf5_server.py @@ -0,0 +1,132 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided by the MCP framework. +def tool(*args, **kwargs): + def decorator(func): + return func + return decorator + +mcp = type("mcp", (), {"tool": tool}) + + +@mcp.tool() +def execute_rhdf5_script( + script_file: Optional[Path] = None, + expression: Optional[str] = None, + script_args: Optional[List[str]] = None, + verbose: bool = False, + default_packages: Optional[str] = None, + vanilla: bool = False, + save: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: bool = False, + restore: bool = False, +) -> Dict[str, Any]: + """ + Executes an R script using Rscript in an environment with bioconductor-rhdf5. + + This tool serves as a wrapper for the Rscript executable, allowing you to run + R code that utilizes the rhdf5 library for interacting with HDF5 files. + You must provide either an R script file (`script_file`) or a string + containing an R expression (`expression`). + + Args: + script_file: Path to the R script file to be executed. + expression: An R expression to be executed. Use instead of 'script_file'. + script_args: A list of arguments to be passed to the R script. + verbose: If True, enables verbose output from Rscript. + default_packages: A comma-separated list of packages to be loaded by default. + vanilla: Combines --no-save, --no-restore, --no-site-file, --no-init-file, + and --no-environ. A best practice for clean, reproducible runs. + save: If True, the workspace is saved at the end of the session. + no_environ: If True, site and user environment files are not read. + no_site_file: If True, the site-wide Rprofile is not read. + no_init_file: If True, the user's R profile is not read. + restore: If True, previously saved objects are restored at startup. + + Returns: + A dictionary containing the execution details, including the command, + stdout, stderr, and a list of output files (if any were generated). + """ + # --- Input Validation --- + if not (script_file or expression): + raise ValueError("Either 'script_file' or 'expression' must be provided.") + if script_file and expression: + raise ValueError("'script_file' and 'expression' are mutually exclusive and cannot be used together.") + if script_file: + if not script_file.is_file(): + raise FileNotFoundError(f"The specified script file does not exist: {script_file}") + + # --- Command Construction --- + cmd = ["Rscript"] + + if verbose: + cmd.append("--verbose") + if default_packages: + cmd.extend(["--default-packages", default_packages]) + + if vanilla: + cmd.append("--vanilla") + else: + if save: + cmd.append("--save") + if no_environ: + cmd.append("--no-environ") + if no_site_file: + cmd.append("--no-site-file") + if no_init_file: + cmd.append("--no-init-file") + if restore: + cmd.append("--restore") + + if expression: + cmd.extend(["-e", expression]) + elif script_file: + cmd.append(str(script_file)) + + if script_args: + cmd.extend(script_args) + + command_executed = " ".join(cmd) + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + stdout = result.stdout + stderr = result.stderr + except FileNotFoundError: + # This error occurs if 'Rscript' is not in the system's PATH + return { + "error": "Rscript executable not found. Please ensure R is installed and accessible in the environment's PATH.", + "command_executed": command_executed, + "stdout": "", + "stderr": "", + } + except subprocess.CalledProcessError as e: + # This error occurs if the R script returns a non-zero exit code + return { + "error": f"R script execution failed with return code {e.returncode}.", + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + } + + # --- Structured Result Return --- + # Since this tool runs a generic script, it cannot know what files will be + # created. The user is responsible for knowing the outputs of their script. + 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-rhdf5/app/bioconductor-rhdf5_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/app/bioconductor-rhdf5_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d54170eb8bc689ac8d755791ae8723f72a8f4c07 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/app/bioconductor-rhdf5_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/app/bioconductor-rhdf5_server.py') +SERVER_NAME = 'biosci_bioconductor_rhdf5' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..371502a90b6b0e642754aebfdcfbed6956a61c7d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-rhdf5: + build: . + image: mcp-bioconductor-rhdf5:latest + container_name: mcp-bioconductor-rhdf5 + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-rhdf5 + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cee49d16e0b5556057e50c59af4bc0cf5ee744b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-rhdf5 + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5filters/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5filters/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..70ad418d4a9082937d70718a7a788888f0f4525b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5filters/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-rhdf5filters via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-rhdf5filters -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-rhdf5filters_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-rhdf5filters_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-rhdf5filters_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5filters/app/bioconductor-rhdf5filters_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5filters/app/bioconductor-rhdf5filters_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7ec9a2cfee279b90853b33fbe673f81be3998eab --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5filters/app/bioconductor-rhdf5filters_server.py @@ -0,0 +1,70 @@ +import subprocess +import tempfile +import shutil +from pathlib import Path +from typing import Dict, Any, List + +# MCP decorator is commented out as per instructions +# @mcp.tool() +def check_installation() -> Dict[str, Any]: + """ + Verifies the installation of the bioconductor-rhdf5filters R library. + + bioconductor-rhdf5filters is an R library that provides HDF5 compression + filters and does not have a direct command-line interface. This function + executes a simple R script to confirm that the library is installed and + can be loaded in the R environment, and it reports the installed version. + """ + # Pre-flight check for Rscript executable + if not shutil.which("Rscript"): + raise FileNotFoundError("Rscript executable not found in PATH. R is required to run this tool.") + + r_script_content = """ + if (!requireNamespace("rhdf5filters", quietly = TRUE)) { + cat("Error: The 'rhdf5filters' package is not installed.\\n", file = stderr()) + quit(status = 1) + } + ver <- as.character(packageVersion("rhdf5filters")) + cat(paste0("Successfully loaded 'rhdf5filters' version: ", ver, "\\n")) + quit(status = 0) + """ + + command_executed = "" + script_path = "" + try: + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R", encoding='utf-8') as tmp_r_script: + script_path = tmp_r_script.name + tmp_r_script.write(r_script_content) + + cmd: List[str] = ["Rscript", script_path] + command_executed = " ".join(cmd) + + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [] + } + + except subprocess.CalledProcessError as e: + # This will catch the case where the R script exits with a non-zero status + # (e.g., package not installed) and return a structured error. + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + "error": "R script execution failed. The 'rhdf5filters' package may not be installed or accessible." + } + finally: + # Ensure the temporary file is cleaned up + if script_path and Path(script_path).exists(): + Path(script_path).unlink() diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5filters/app/bioconductor-rhdf5filters_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5filters/app/bioconductor-rhdf5filters_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e2d287bc648131166c898cb78ab7cfacf44a55ec --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5filters/app/bioconductor-rhdf5filters_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-rhdf5filters/app/bioconductor-rhdf5filters_server.py') +SERVER_NAME = 'biosci_bioconductor_rhdf5filters' + + +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-rhdf5filters/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5filters/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5filters/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5filters/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5filters/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..81832d0f80640700360671a525f10b97f2382efa --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5filters/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-rhdf5filters: + build: . + image: mcp-bioconductor-rhdf5filters:latest + container_name: mcp-bioconductor-rhdf5filters + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-rhdf5filters + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5filters/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5filters/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a0adbb1473ea9468bd807b23ff418eeac7f03f44 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5filters/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-rhdf5filters + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5filters/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5filters/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5filters/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5lib/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5lib/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..092f3d6b4424cc3647a52adc9af228e1cb8277d7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5lib/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-rhdf5lib via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-rhdf5lib -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-rhdf5lib_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-rhdf5lib_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-rhdf5lib_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5lib/app/bioconductor-rhdf5lib_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5lib/app/bioconductor-rhdf5lib_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b8d2220d9af2cea444bb287a1944c86b649b3272 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5lib/app/bioconductor-rhdf5lib_server.py @@ -0,0 +1,25 @@ +import subprocess +from pathlib import Path +from typing import Optional, List + +# NOTE: The 'mcp' import is not included as per the instructions. +# import mcp + +# @mcp.tool() +def rhdf5lib_info(): + """ + Provides information about the bioconductor-rhdf5lib package. + + This package is a library and does not provide any command-line executables. + It offers the HDF5 C and C++ libraries for other R packages to link against. + Therefore, this function is for informational purposes only and does not + execute any subprocess. + """ + # This is a library package with no executable. + # The return dictionary reflects that no command can be executed. + return { + "command_executed": "N/A (bioconductor-rhdf5lib is a library, not a command-line tool)", + "stdout": "This package provides C and C++ HDF5 libraries for use within the R environment. It has no direct command-line interface.", + "stderr": "", + "output_files": [] + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5lib/app/bioconductor-rhdf5lib_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5lib/app/bioconductor-rhdf5lib_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f84c93d914726025b6b20f451499a31fd7006322 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5lib/app/bioconductor-rhdf5lib_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-rhdf5lib/app/bioconductor-rhdf5lib_server.py') +SERVER_NAME = 'biosci_bioconductor_rhdf5lib' + + +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-rhdf5lib/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5lib/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5lib/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5lib/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5lib/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..76b1d4811a976df2b79fe83db8d4a84fd0ba1942 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5lib/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-rhdf5lib: + build: . + image: mcp-bioconductor-rhdf5lib:latest + container_name: mcp-bioconductor-rhdf5lib + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-rhdf5lib + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5lib/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5lib/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..017af4d64e893f7c7b7ba39e41e213740bfc4479 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5lib/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-rhdf5lib + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5lib/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5lib/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5lib/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhtslib/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhtslib/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..06606fbc87c7cc914c960f63ba38650caa95bbc6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhtslib/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-rhtslib via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-rhtslib -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-rhtslib_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-rhtslib_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-rhtslib_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhtslib/app/bioconductor-rhtslib_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhtslib/app/bioconductor-rhtslib_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ff69f539da938d6b1107cc350713f46ff6aff994 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhtslib/app/bioconductor-rhtslib_server.py @@ -0,0 +1,72 @@ +import subprocess +import shutil +from typing import Dict, Any + +# MCP framework placeholder for standalone execution +class _Mcp: + def tool(self, *args, **kwargs): + def decorator(func): + return func + return decorator +mcp = _Mcp() + +@mcp.tool() +def check_rhtslib_installation() -> Dict[str, Any]: + """ + Verifies the installation of the bioconductor-rhtslib R package and reports its version. + + bioconductor-rhtslib is an R library package that provides the HTSlib C library + for other R packages to use. It does not offer a direct command-line executable or + any user-facing functions. This utility function serves to confirm that the library + is correctly installed and accessible within the R environment by attempting to + load it and print its version using an Rscript command. + """ + rscript_path = shutil.which("Rscript") + if not rscript_path: + # This is a system configuration error. R is not available. + return { + "command_executed": "Rscript -e '...'", + "stdout": "", + "stderr": "Error: Rscript executable not found. Is R installed and in the system's PATH?", + "output_files": [] + } + + # A simple R command to get the package version. + r_command = 'cat(as.character(packageVersion("Rhtslib")))' + command = [rscript_path, "-e", r_command] + command_executed = " ".join(command) + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + stdout = process.stdout.strip() + stderr = process.stderr.strip() + + return { + "command_executed": command_executed, + "stdout": f"bioconductor-rhtslib version: {stdout}", + "stderr": stderr, + "output_files": [] + } + + except subprocess.CalledProcessError as e: + # This error is expected if the package is not installed in the R environment. + return { + "command_executed": command_executed, + "stdout": e.stdout.strip(), + "stderr": e.stderr.strip(), + "output_files": [] + } + except Exception as e: + # Catch any other unexpected errors during execution. + return { + "command_executed": command_executed, + "stdout": "", + "stderr": f"An unexpected error occurred: {str(e)}", + "output_files": [] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhtslib/app/bioconductor-rhtslib_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhtslib/app/bioconductor-rhtslib_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a9d03b2d72645bf035a722ac60db7a736f5ff279 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhtslib/app/bioconductor-rhtslib_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhtslib/app/bioconductor-rhtslib_server.py') +SERVER_NAME = 'biosci_bioconductor_rhtslib' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhtslib/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhtslib/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhtslib/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhtslib/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhtslib/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e3490324c687de6f1d638054610292218df8d093 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhtslib/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-rhtslib: + build: . + image: mcp-bioconductor-rhtslib:latest + container_name: mcp-bioconductor-rhtslib + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-rhtslib + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhtslib/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhtslib/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8d9fd1f10209694d0af1705cd86798274dadc35c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhtslib/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-rhtslib + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhtslib/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhtslib/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhtslib/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsamtools/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsamtools/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0d3c706e4910bc3c14bf2f9ad377de8d3d4f6d71 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsamtools/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-rsamtools via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-rsamtools -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-rsamtools_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-rsamtools_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-rsamtools_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsamtools/app/bioconductor-rsamtools_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsamtools/app/bioconductor-rsamtools_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d6ab8e0850a2074d07376476de0ffda943179ee8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsamtools/app/bioconductor-rsamtools_server.py @@ -0,0 +1,446 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Union +import tempfile + +@mcp.tool() +def rsamtools_bgzip( + file: str, + dest: Optional[str] = None, + overwrite: bool = False, +): + """ + Compress a file using bgzip via Rsamtools. + + :param file: Path to the file to compress. + :param dest: Destination path for the compressed file. Defaults to file + .gz. + :param overwrite: Whether to overwrite the destination file if it exists. + """ + input_path = Path(file) + if not input_path.exists(): + return {"error": f"Input file {file} does not exist."} + + dest_val = dest if dest else f"{file}.gz" + overwrite_val = "TRUE" if overwrite else "FALSE" + + r_command = f"library(Rsamtools); bgzip(file='{file}', dest='{dest_val}', overwrite={overwrite_val})" + + try: + result = subprocess.run( + ["Rscript", "-e", r_command], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e \"{r_command}\"", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [dest_val] + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def rsamtools_index_tabix( + file: str, + format: str = "vcf", + seq: int = 1, + start: int = 2, + end: int = 3, + skip: int = 0, + comment: str = "#", + zero_based: bool = False, +): + """ + Index a bgzip-compressed file using indexTabix. + + :param file: Path to the bgzip-compressed file. + :param format: Format of the file ('vcf', 'bed', 'gff', 'sam', 'conf'). + :param seq: Column index for sequence name. + :param start: Column index for start position. + :param end: Column index for end position. + :param skip: Number of lines to skip. + :param comment: Comment character. + :param zero_based: Whether the coordinates are zero-based. + """ + input_path = Path(file) + if not input_path.exists(): + return {"error": f"Input file {file} does not exist."} + + zero_based_val = "TRUE" if zero_based else "FALSE" + + r_command = ( + f"library(Rsamtools); " + f"indexTabix(file='{file}', format='{format}', " + f"seq={seq}, start={start}, end={end}, skip={skip}, " + f"comment='{comment}', zeroBased={zero_based_val})" + ) + + try: + result = subprocess.run( + ["Rscript", "-e", r_command], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e \"{r_command}\"", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [f"{file}.tbi"] + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def rsamtools_sort_bam( + file: str, + destination: str, + by_name: bool = False, + max_memory: int = 512, +): + """ + Sort a BAM file using sortBam. + + :param file: Path to the BAM file. + :param destination: Destination prefix (Rsamtools appends .bam). + :param by_name: Sort by query name instead of coordinate. + :param max_memory: Maximum memory in MB. + """ + input_path = Path(file) + if not input_path.exists(): + return {"error": f"Input file {file} does not exist."} + + by_name_val = "TRUE" if by_name else "FALSE" + + r_command = ( + f"library(Rsamtools); " + f"sortBam(file='{file}', destination='{destination}', " + f"byQname={by_name_val}, maxMemory={max_memory})" + ) + + try: + result = subprocess.run( + ["Rscript", "-e", r_command], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e \"{r_command}\"", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [f"{destination}.bam"] + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def rsamtools_index_bam( + file: str, + overwrite: bool = False, +): + """ + Index a BAM file using indexBam. + + :param file: Path to the sorted BAM file. + :param overwrite: Whether to overwrite existing index. + """ + input_path = Path(file) + if not input_path.exists(): + return {"error": f"Input file {file} does not exist."} + + r_command = f"library(Rsamtools); indexBam(file='{file}')" + + try: + result = subprocess.run( + ["Rscript", "-e", r_command], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e \"{r_command}\"", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [f"{file}.bai"] + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def rsamtools_filter_bam( + file: str, + destination: str, + index: Optional[str] = None, + mapq_filter: int = 0, + is_paired: Optional[bool] = None, + is_proper_pair: Optional[bool] = None, + is_unmapped_query: Optional[bool] = None, + has_unmapped_mate: Optional[bool] = None, + is_minus_strand: Optional[bool] = None, + is_mate_minus_strand: Optional[bool] = None, + is_first_mate_read: Optional[bool] = None, + is_second_mate_read: Optional[bool] = None, + is_secondary_alignment: Optional[bool] = None, + is_not_passing_quality_controls: Optional[bool] = None, + is_duplicate: Optional[bool] = None, +): + """ + Filter a BAM file using filterBam and ScanBamParam. + + :param file: Input BAM file. + :param destination: Output BAM file. + :param index: Path to BAM index. + :param mapq_filter: Minimum MAPQ score. + :param is_paired: Filter by paired status. + :param is_proper_pair: Filter by proper pair status. + :param is_unmapped_query: Filter by unmapped query status. + :param has_unmapped_mate: Filter by unmapped mate status. + :param is_minus_strand: Filter by minus strand status. + :param is_mate_minus_strand: Filter by mate minus strand status. + :param is_first_mate_read: Filter by first mate status. + :param is_second_mate_read: Filter by second mate status. + :param is_secondary_alignment: Filter by secondary alignment status. + :param is_not_passing_quality_controls: Filter by QC status. + :param is_duplicate: Filter by duplicate status. + """ + input_path = Path(file) + if not input_path.exists(): + return {"error": f"Input file {file} does not exist."} + + def r_bool(val): + if val is None: return "NA" + return "TRUE" if val else "FALSE" + + flag_args = [ + f"isPaired={r_bool(is_paired)}", + f"isProperPair={r_bool(is_proper_pair)}", + f"isUnmappedQuery={r_bool(is_unmapped_query)}", + f"hasUnmappedMate={r_bool(has_unmapped_mate)}", + f"isMinusStrand={r_bool(is_minus_strand)}", + f"isMateMinusStrand={r_bool(is_mate_minus_strand)}", + f"isFirstMateRead={r_bool(is_first_mate_read)}", + f"isSecondMateRead={r_bool(is_second_mate_read)}", + f"isSecondaryAlignment={r_bool(is_secondary_alignment)}", + f"isNotPassingQualityControls={r_bool(is_not_passing_quality_controls)}", + f"isDuplicate={r_bool(is_duplicate)}" + ] + + flag_str = f"scanBamFlag({', '.join(flag_args)})" + param_str = f"ScanBamParam(flag={flag_str}, mapqFilter={mapq_filter})" + index_str = f"'{index}'" if index else "character()" + + r_command = ( + f"library(Rsamtools); " + f"filterBam(file='{file}', destination='{destination}', " + f"index={index_str}, param={param_str})" + ) + + try: + result = subprocess.run( + ["Rscript", "-e", r_command], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e \"{r_command}\"", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [destination] + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def rsamtools_merge_bam( + files: List[str], + destination: str, + overwrite: bool = False, + header: Optional[str] = None, + region: Optional[str] = None, +): + """ + Merge multiple BAM files using mergeBam. + + :param files: List of paths to BAM files to merge. + :param destination: Path to the output merged BAM file. + :param overwrite: Whether to overwrite the destination file. + :param header: Path to a BAM file from which to take the header. + :param region: Genomic region to merge (e.g., 'chr1:1-100'). + """ + for f in files: + if not Path(f).exists(): + return {"error": f"Input file {f} does not exist."} + + files_r = "c(" + ",".join([f"'{f}'" for f in files]) + ")" + overwrite_val = "TRUE" if overwrite else "FALSE" + header_val = f"'{header}'" if header else "character()" + region_val = f"'{region}'" if region else "character()" + + r_command = ( + f"library(Rsamtools); " + f"mergeBam(files={files_r}, destination='{destination}', " + f"overwrite={overwrite_val}, header={header_val}, region={region_val})" + ) + + try: + result = subprocess.run( + ["Rscript", "-e", r_command], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e \"{r_command}\"", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [destination] + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def rsamtools_count_bam( + file: str, + index: Optional[str] = None, + mapq_filter: int = 0, +): + """ + Count records in a BAM file using countBam. + + :param file: Path to the BAM file. + :param index: Path to the BAM index. + :param mapq_filter: Minimum MAPQ score. + """ + input_path = Path(file) + if not input_path.exists(): + return {"error": f"Input file {file} does not exist."} + + index_str = f"'{index}'" if index else "character()" + r_command = ( + f"library(Rsamtools); " + f"param <- ScanBamParam(mapqFilter={mapq_filter}); " + f"res <- countBam(file='{file}', index={index_str}, param=param); " + f"print(res)" + ) + + try: + result = subprocess.run( + ["Rscript", "-e", r_command], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e \"{r_command}\"", + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def rsamtools_idxstats_bam( + file: str, + index: Optional[str] = None, +): + """ + Retrieve index statistics (mapped/unmapped reads per ref) using idxstatsBam. + + :param file: Path to the BAM file. + :param index: Path to the BAM index. + """ + input_path = Path(file) + if not input_path.exists(): + return {"error": f"Input file {file} does not exist."} + + index_str = f"'{index}'" if index else "character()" + r_command = ( + f"library(Rsamtools); " + f"res <- idxstatsBam(file='{file}', index={index_str}); " + f"print(res)" + ) + + try: + result = subprocess.run( + ["Rscript", "-e", r_command], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e \"{r_command}\"", + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def rsamtools_quickcheck_bam( + file: str, +): + """ + Quickly check if a BAM file is intact using quickcheckBam. + + :param file: Path to the BAM file. + """ + input_path = Path(file) + if not input_path.exists(): + return {"error": f"Input file {file} does not exist."} + + r_command = f"library(Rsamtools); res <- quickcheckBam(file='{file}'); print(res)" + + try: + result = subprocess.run( + ["Rscript", "-e", r_command], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e \"{r_command}\"", + "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-rsamtools/app/bioconductor-rsamtools_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsamtools/app/bioconductor-rsamtools_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9336f1855fc61b51507fed2998746d7f782fd1f3 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsamtools/app/bioconductor-rsamtools_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsamtools/app/bioconductor-rsamtools_server.py') +SERVER_NAME = 'biosci_bioconductor_rsamtools' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsamtools/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsamtools/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsamtools/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsamtools/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsamtools/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d651c7cf7814b6fdfba82ac2f2145cb67d0099d2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsamtools/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-rsamtools: + build: . + image: mcp-bioconductor-rsamtools:latest + container_name: mcp-bioconductor-rsamtools + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-rsamtools + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsamtools/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsamtools/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5c153912d63628e3c8ea76360f2d3f0afac07118 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsamtools/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-rsamtools + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsamtools/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsamtools/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsamtools/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsubread/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsubread/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e4dec6ab2174115a3f1326b6fd37bc802e9c6b00 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsubread/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-rsubread via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-rsubread -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-rsubread_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-rsubread_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-rsubread_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsubread/app/bioconductor-rsubread_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsubread/app/bioconductor-rsubread_server.py new file mode 100644 index 0000000000000000000000000000000000000000..80e5fd6594e70b8effa2a3f95629f5cb3b394c5f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsubread/app/bioconductor-rsubread_server.py @@ -0,0 +1,435 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Union + +# Helper function to execute Rscript commands +def _run_r_script(r_code: str, tool_name: str) -> dict: + """ + Executes an R script using Rscript. + + Args: + r_code: The R code string to execute. + tool_name: The name of the Rsubread function being called, for error reporting. + + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + r_script_content = f"library(Rsubread)\n{r_code}" + + with tempfile.NamedTemporaryFile(mode="w", suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = Path(r_script_file.name) + + command = ["Rscript", str(r_script_path)] + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": [], # To be populated by individual tool functions + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Rsubread {tool_name} failed with exit code {e.returncode}", + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Rscript command not found. Is R installed and in PATH?", + "error": "Rscript not found", + "output_files": [], + } + finally: + # Clean up temporary R script file + r_script_path.unlink(missing_ok=True) + + +@mcp.tool() +def build_index( + index_name: Path, + reference_fasta: Path, + gff_file: Optional[Path] = None, + threads: int = 1, + memory: Optional[int] = None, +) -> dict: + """ + Builds a Subread index for read alignment. + + Args: + index_name: Prefix for the output index files. The actual index files will be + created with this prefix (e.g., index_name.00.b.array, etc.). + reference_fasta: Path to the reference genome FASTA file. + gff_file: Optional path to a GTF/GFF annotation file for splice-aware indexing. + threads: Number of CPU threads to use. Must be at least 1. + memory: Maximum memory (in MB) to use. Must be a positive integer if provided. + + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + if not reference_fasta.is_file(): + raise ValueError(f"Reference FASTA file not found: {reference_fasta}") + if gff_file and not gff_file.is_file(): + raise ValueError(f"GFF/GTF file not found: {gff_file}") + if threads < 1: + raise ValueError("Number of threads must be at least 1.") + if memory is not None and memory <= 0: + raise ValueError("Memory limit must be a positive integer.") + + r_code_params = [ + f'indexName="{index_name.resolve()}"', + f'reference="{reference_fasta.resolve()}"', + ] + if gff_file: + r_code_params.append(f'gffAnnotation="{gff_file.resolve()}"') + if threads > 1: # Rsubread's default is usually 1, so only add if > 1 + r_code_params.append(f'nthreads={threads}') + if memory is not None: + r_code_params.append(f'memory={memory}') + + r_code = f"buildindex({', '.join(r_code_params)})\n" + + result = _run_r_script(r_code, "buildindex") + + # Rsubread creates multiple index files with the given prefix. + # We check for one common file to confirm creation. + expected_index_file_part = Path(f"{index_name.resolve()}.00.b.array") + if expected_index_file_part.is_file(): + # Return the prefix as a representation of the generated index files + result["output_files"].append(str(index_name.resolve())) + + return result + + +@mcp.tool() +def align_reads( + index_name: Path, + read_files: List[Path], + output_bam: Path, + paired_end: bool = False, + threads: int = 1, + unique: bool = False, + max_mismatches: int = 3, + n_subreads: Optional[int] = None, + output_format: str = "BAM", + sort_by_read_name: bool = False, + sort_by_coordinate: bool = False, + phred_offset: int = 33, +) -> dict: + """ + Aligns sequencing reads to a reference genome using the Subread aligner. + + Args: + index_name: Path to the Subread index prefix (created by build_index). + read_files: List of input FASTQ or BAM files. For paired-end, provide two files. + output_bam: Path for the output alignment BAM/SAM file. + paired_end: Set to True if reads are paired-end. + threads: Number of CPU threads to use. Must be at least 1. + unique: If True, only uniquely mapped reads are reported. + max_mismatches: Maximum number of mismatches allowed for an alignment. Must be non-negative. + n_subreads: Number of subreads to use for long reads (if applicable). Must be a positive integer if provided. + output_format: Output format for alignments ("BAM" or "SAM"). + sort_by_read_name: If True, sort output by read name. Cannot be used with `sort_by_coordinate`. + sort_by_coordinate: If True, sort output by coordinate. Cannot be used with `sort_by_read_name`. + phred_offset: Phred score offset (33 or 64). + + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + if not Path(f"{index_name.resolve()}.00.b.array").is_file(): # Check for a common index file + raise ValueError(f"Subread index not found at prefix: {index_name}") + for f in read_files: + if not f.is_file(): + raise ValueError(f"Read file not found: {f}") + if not read_files: + raise ValueError("At least one read file must be provided.") + if paired_end and len(read_files) != 2: + raise ValueError("For paired-end alignment, exactly two read files must be provided.") + if not paired_end and len(read_files) != 1: + raise ValueError("For single-end alignment, exactly one read file must be provided.") + if threads < 1: + raise ValueError("Number of threads must be at least 1.") + if max_mismatches < 0: + raise ValueError("Maximum mismatches cannot be negative.") + if n_subreads is not None and n_subreads <= 0: + raise ValueError("Number of subreads must be a positive integer.") + if output_format not in ["BAM", "SAM"]: + raise ValueError("Output format must be 'BAM' or 'SAM'.") + if phred_offset not in [33, 64]: + raise ValueError("Phred offset must be 33 or 64.") + if sort_by_read_name and sort_by_coordinate: + raise ValueError("Cannot sort by both read name and coordinate simultaneously.") + + read_files_str = ', '.join([f'"{f.resolve()}"' for f in read_files]) + + r_code_params = [ + f'index="{index_name.resolve()}"', + f'readfile=c({read_files_str})', + f'output_file="{output_bam.resolve()}"', + f'nthreads={threads}', + f'unique={str(unique).upper()}', + f'maxMismatches={max_mismatches}', + f'type="{output_format}"', + f'phredOffset={phred_offset}', + ] + if paired_end: + r_code_params.append(f'pairedEnd={str(paired_end).upper()}') + if n_subreads is not None: + r_code_params.append(f'nsubreads={n_subreads}') + if sort_by_read_name: + r_code_params.append(f'sortByReadName={str(sort_by_read_name).upper()}') + if sort_by_coordinate: + r_code_params.append(f'sortReadsByCoordinate={str(sort_by_coordinate).upper()}') + + r_code = f"align({', '.join(r_code_params)})\n" + + result = _run_r_script(r_code, "align") + + if output_bam.is_file(): + result["output_files"].append(str(output_bam.resolve())) + + return result + + +@mcp.tool() +def count_features( + bam_files: List[Path], + annotation_file: Path, + output_file: Path, + feature_type: str = "exon", + gene_id_attribute: str = "gene_id", + is_paired_end: bool = False, + strand_specific: int = 0, + allow_multi_overlap: bool = False, + min_overlap: int = 1, + ignore_multimapping: bool = False, + n_threads: int = 1, + count_multi_mapping_reads: bool = False, + count_primary_alignments_only: bool = True, + fraction: bool = False, + is_long_read: bool = False, +) -> dict: + """ + Counts reads for genomic features (e.g., genes, exons) using featureCounts. + + Args: + bam_files: List of input BAM/SAM files. + annotation_file: Path to the GTF/GFF annotation file. + output_file: Path for the output count file (e.g., TSV). + feature_type: Feature type to count (e.g., "exon", "gene"). + gene_id_attribute: Attribute in the annotation file to use as gene ID (e.g., "gene_id"). + is_paired_end: Set to True if reads are paired-end. + strand_specific: Strand specificity (0: unstranded, 1: stranded, 2: reversely stranded). + allow_multi_overlap: If True, allow reads to overlap multiple features. + min_overlap: Minimum number of overlapping bases required. Must be at least 1. + ignore_multimapping: If True, ignore multi-mapping reads. + n_threads: Number of CPU threads to use. Must be at least 1. + count_multi_mapping_reads: If True, count multi-mapping reads. + count_primary_alignments_only: If True, count only primary alignments. + fraction: If True, assign fractional counts to multi-overlapping features. + is_long_read: If True, treat reads as long reads. + + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + for f in bam_files: + if not f.is_file(): + raise ValueError(f"BAM/SAM file not found: {f}") + if not annotation_file.is_file(): + raise ValueError(f"Annotation file not found: {annotation_file}") + if not bam_files: + raise ValueError("At least one BAM/SAM file must be provided.") + if strand_specific not in [0, 1, 2]: + raise ValueError("Strand specificity must be 0 (unstranded), 1 (stranded), or 2 (reversely stranded).") + if min_overlap < 1: + raise ValueError("Minimum overlap must be at least 1.") + if n_threads < 1: + raise ValueError("Number of threads must be at least 1.") + + bam_files_str = ', '.join([f'"{f.resolve()}"' for f in bam_files]) + + # Infer isGTFAnnotationFile based on suffix + is_gtf = annotation_file.suffix.lower() in [".gtf", ".gff"] + + r_code_params = [ + f'files=c({bam_files_str})', + f'annot.ext="{annotation_file.resolve()}"', + f'isGTFAnnotationFile={str(is_gtf).upper()}', + f'featureType="{feature_type}"', + f'attrType="{gene_id_attribute}"', + f'isPairedEnd={str(is_paired_end).upper()}', + f'strandSpecific={strand_specific}', + f'allowMultiOverlap={str(allow_multi_overlap).upper()}', + f'minOverlap={min_overlap}', + f'ignoreMultimapping={str(ignore_multimapping).upper()}', + f'nthreads={n_threads}', + f'countMultiMappingReads={str(count_multi_mapping_reads).upper()}', + f'countPrimaryAlignmentsOnly={str(count_primary_alignments_only).upper()}', + f'fraction={str(fraction).upper()}', + f'isLongRead={str(is_long_read).upper()}', + ] + + # featureCounts returns a list, we need to extract the counts table and write it. + # The counts table is typically in the 'counts' element of the returned list, + # and summary statistics in 'stat'. + summary_output_file = Path(f"{output_file.resolve()}.summary") + r_code = ( + f"fc_result <- featureCounts({', '.join(r_code_params)})\n" + f'write.table(fc_result$counts, file="{output_file.resolve()}", sep="\\t", quote=FALSE, col.names=NA)\n' + f'write.table(fc_result$stat, file="{summary_output_file.resolve()}", sep="\\t", quote=FALSE, row.names=FALSE)\n' + ) + + result = _run_r_script(r_code, "featureCounts") + + if output_file.is_file(): + result["output_files"].append(str(output_file.resolve())) + if summary_output_file.is_file(): + result["output_files"].append(str(summary_output_file.resolve())) + + return result + + +@mcp.tool() +def detect_structural_variants( + bam_files: List[Path], + reference_fasta: Path, + output_vcf: Path, + threads: int = 1, + min_read_support: int = 3, + min_sv_size: int = 50, + max_sv_size: int = 1000000, + min_map_quality: int = 20, +) -> dict: + """ + Detects structural variants (SVs) from BAM files using Rsubread's detectSV. + + Args: + bam_files: List of input BAM/SAM files. + reference_fasta: Path to the reference genome FASTA file. + output_vcf: Path for the output VCF file containing detected SVs. + threads: Number of CPU threads to use. Must be at least 1. + min_read_support: Minimum number of reads supporting an SV to be reported. Must be at least 1. + min_sv_size: Minimum size of SV to be reported. Must be at least 1. + max_sv_size: Maximum size of SV to be reported. Must be greater than or equal to `min_sv_size`. + min_map_quality: Minimum mapping quality of reads to be considered. Must be non-negative. + + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + for f in bam_files: + if not f.is_file(): + raise ValueError(f"BAM/SAM file not found: {f}") + if not reference_fasta.is_file(): + raise ValueError(f"Reference FASTA file not found: {reference_fasta}") + if not bam_files: + raise ValueError("At least one BAM/SAM file must be provided.") + if threads < 1: + raise ValueError("Number of threads must be at least 1.") + if min_read_support < 1: + raise ValueError("Minimum read support must be at least 1.") + if min_sv_size < 1: + raise ValueError("Minimum SV size must be at least 1.") + if max_sv_size < min_sv_size: + raise ValueError("Maximum SV size cannot be less than minimum SV size.") + if min_map_quality < 0: + raise ValueError("Minimum mapping quality cannot be negative.") + + bam_files_str = ', '.join([f'"{f.resolve()}"' for f in bam_files]) + + r_code_params = [ + f'bamFile=c({bam_files_str})', + f'reference="{reference_fasta.resolve()}"', + f'outputFile="{output_vcf.resolve()}"', + f'nthreads={threads}', + f'minReadSupport={min_read_support}', + f'minSVSize={min_sv_size}', + f'maxSVSize={max_sv_size}', + f'minMapQual={min_map_quality}', + ] + + r_code = f"detectSV({', '.join(r_code_params)})\n" + + result = _run_r_script(r_code, "detectSV") + + if output_vcf.is_file(): + result["output_files"].append(str(output_vcf.resolve())) + + return result + + +@mcp.tool() +def find_gene_fusions( + bam_files: List[Path], + reference_fasta: Path, + output_file: Path, + threads: int = 1, + min_read_support: int = 3, + min_junction_reads: int = 1, +) -> dict: + """ + Detects gene fusions from BAM files using Rsubread's findFusion. + + Args: + bam_files: List of input BAM/SAM files. + reference_fasta: Path to the reference genome FASTA file. + output_file: Path for the output file containing detected gene fusions (e.g., TSV). + threads: Number of CPU threads to use. Must be at least 1. + min_read_support: Minimum number of reads supporting a fusion to be reported. Must be at least 1. + min_junction_reads: Minimum number of reads spanning the fusion junction. Must be at least 1. + + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + for f in bam_files: + if not f.is_file(): + raise ValueError(f"BAM/SAM file not found: {f}") + if not reference_fasta.is_file(): + raise ValueError(f"Reference FASTA file not found: {reference_fasta}") + if not bam_files: + raise ValueError("At least one BAM/SAM file must be provided.") + if threads < 1: + raise ValueError("Number of threads must be at least 1.") + if min_read_support < 1: + raise ValueError("Minimum read support must be at least 1.") + if min_junction_reads < 1: + raise ValueError("Minimum junction reads must be at least 1.") + + bam_files_str = ', '.join([f'"{f.resolve()}"' for f in bam_files]) + + r_code_params = [ + f'bamFile=c({bam_files_str})', + f'reference="{reference_fasta.resolve()}"', + f'outputFile="{output_file.resolve()}"', + f'nthreads={threads}', + f'minReadSupport={min_read_support}', + f'minJunctionReads={min_junction_reads}', + ] + + r_code = f"findFusion({', '.join(r_code_params)})\n" + + result = _run_r_script(r_code, "findFusion") + + if output_file.is_file(): + result["output_files"].append(str(output_file.resolve())) + + return result \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsubread/app/bioconductor-rsubread_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsubread/app/bioconductor-rsubread_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f61b643bfbae0660e35563150014a240ef6193aa --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsubread/app/bioconductor-rsubread_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsubread/app/bioconductor-rsubread_server.py') +SERVER_NAME = 'biosci_bioconductor_rsubread' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsubread/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsubread/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsubread/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsubread/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsubread/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e2725ed890f216390d4ca45f72fe80e813511c82 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsubread/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-rsubread: + build: . + image: mcp-bioconductor-rsubread:latest + container_name: mcp-bioconductor-rsubread + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-rsubread + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsubread/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsubread/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fdd1061efad1bac463df38b14d847bf8a1798168 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsubread/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-rsubread + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsubread/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsubread/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rsubread/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rtracklayer/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rtracklayer/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rtracklayer/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4arrays/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4arrays/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..45dc028e4d07c5027c3bea3abcb96085e1d18429 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4arrays/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-s4arrays via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-s4arrays -y && conda clean -a + +# 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-s4arrays_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-s4arrays_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-s4arrays_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4arrays/app/bioconductor-s4arrays_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4arrays/app/bioconductor-s4arrays_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0401fa2456a61d2e88773701db53114c59a283e0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4arrays/app/bioconductor-s4arrays_server.py @@ -0,0 +1,87 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# MCP-standard mock decorator. +# In a real MCP environment, this would be provided by the mcp.py library. +def tool(func): + def wrapper(*args, **kwargs): + # This is a mock implementation for local testing. + # The actual MCP framework would handle the execution. + print(f"Executing tool: {func.__name__}") + print(f"Arguments: {args}") + print(f"Keyword Arguments: {kwargs}") + return func(*args, **kwargs) + return wrapper + +mcp = type("mcp", (), {"tool": tool}) + +@mcp.tool +def s4arrays_run_script( + r_script: Path, + r_executable: str = "Rscript", +) -> dict: + """ + Executes a user-provided R script in an environment with the S4Arrays package. + + bioconductor-s4arrays is an R library, not a standalone command-line tool. + It provides foundational classes and functions for creating and manipulating + array-like data structures within the R/Bioconductor ecosystem. This function + allows you to run an R script that utilizes the S4Arrays library. + + Args: + r_script (Path): Path to the R script file to be executed. The script + should use the S4Arrays library (e.g., via `library(S4Arrays)`). + r_executable (str): The command to execute R scripts. Defaults to 'Rscript'. + Can be changed if R is installed in a non-standard location + or a specific version is required. + + Returns: + dict: A dictionary containing the results of the execution, including + the command executed, stdout, stderr, and a list of output files. + """ + # Input validation + if not r_script.is_file(): + raise FileNotFoundError(f"The specified R script does not exist: {r_script}") + + if not r_script.suffix == ".R" and not r_script.suffix == ".r": + print(f"Warning: Script file '{r_script}' does not have a standard .R or .r extension.") + + command = [r_executable, str(r_script)] + + try: + # Execute the R script + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + stdout = process.stdout + stderr = process.stderr + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": f"Error: '{r_executable}' not found. Please ensure R is installed and in your PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + # Since this function doesn't know what the R script will produce, + # it's the user's responsibility to know the output files. + # We return an empty list here, but a more advanced implementation + # could scan the working directory for new files. + return { + "command_executed": " ".join(command), + "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-s4arrays/app/bioconductor-s4arrays_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4arrays/app/bioconductor-s4arrays_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fd1788a58dbff95745b330c872028f3af8e745ce --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4arrays/app/bioconductor-s4arrays_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-s4arrays/app/bioconductor-s4arrays_server.py') +SERVER_NAME = 'biosci_bioconductor_s4arrays' + + +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-s4arrays/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4arrays/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4arrays/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4arrays/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4arrays/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e3e99e2a211ee9ac8bba771fc2b95333db7f60f6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4arrays/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-s4arrays: + build: . + image: mcp-bioconductor-s4arrays:latest + container_name: mcp-bioconductor-s4arrays + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-s4arrays + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-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-s4arrays/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4arrays/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c8c2a9280e99d175c63d114ef3260ae5da77afa1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4arrays/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-s4arrays + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4arrays/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4arrays/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4arrays/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4vectors/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4vectors/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a0f6bd4e1941b807a9cae7ac378ba476bff35c0d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4vectors/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-s4vectors via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-s4vectors -y && conda clean -a + +# 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-s4vectors_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-s4vectors_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-s4vectors_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4vectors/app/bioconductor-s4vectors_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4vectors/app/bioconductor-s4vectors_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0e4d5c4dc43ef33ccd68a153d3fb771e93c76e73 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4vectors/app/bioconductor-s4vectors_server.py @@ -0,0 +1,295 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Union +import tempfile +import json + +@mcp.tool() +def s4vectors_inspect_dataframe( + input_csv: str, + has_header: bool = True, + row_names_col: Optional[int] = None +): + """ + Load a CSV file into an S4Vectors DataFrame and return its structure, metadata, and summary. + + Args: + input_csv: Path to the input CSV file. + has_header: Whether the CSV has a header row. + row_names_col: Optional column index (1-based) to use as row names. + """ + input_path = Path(input_csv) + if not input_path.exists(): + return {"error": f"Input file {input_csv} not found."} + + row_names_arg = f"row.names = {row_names_col}" if row_names_col is not None else "" + header_arg = "TRUE" if has_header else "FALSE" + + r_script = f""" + suppressPackageStartupMessages(library(S4Vectors)) + df <- DataFrame(read.csv("{input_csv}", header = {header_arg}, {row_names_arg})) + cat("--- SHOW ---\\n") + show(df) + cat("\\n--- SUMMARY ---\\n") + print(summary(df)) + cat("\\n--- METADATA ---\\n") + print(metadata(df)) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e 'S4Vectors::DataFrame(read.csv(\"{input_csv}\"))'", + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def s4vectors_rle_compute( + values: List[Union[int, float, str]], +): + """ + Compute Run-Length Encoding (Rle) for a sequence of values. + Useful for compressing genomic data or identifying runs of identical values. + + Args: + values: A list of numeric or string values to encode. + """ + # Convert python list to R vector string + r_values = ", ".join([f'"{v}"' if isinstance(v, str) else str(v) for v in values]) + + r_script = f""" + suppressPackageStartupMessages(library(S4Vectors)) + vec <- c({r_values}) + rle_obj <- Rle(vec) + cat("--- RLE OBJECT ---\\n") + show(rle_obj) + cat("\\n--- RUN LENGTHS ---\\n") + cat(runLength(rle_obj), "\\n") + cat("\\n--- RUN VALUES ---\\n") + cat(runValue(rle_obj), "\\n") + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "Rscript -e 'S4Vectors::Rle(...)'", + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stderr": e.stderr + } + +@mcp.tool() +def s4vectors_dataframe_subset( + input_csv: str, + output_csv: str, + subset_expression: str, +): + """ + Filter an S4Vectors DataFrame using R-style subsetting and save to a new CSV. + + Args: + input_csv: Path to the input CSV file. + output_csv: Path where the filtered CSV will be saved. + subset_expression: R logical expression for filtering (e.g., "score > 10 & type == 'exon'"). + """ + input_path = Path(input_csv) + if not input_path.exists(): + return {"error": f"Input file {input_csv} not found."} + + r_script = f""" + suppressPackageStartupMessages(library(S4Vectors)) + df <- DataFrame(read.csv("{input_csv}")) + filtered_df <- subset(df, {subset_expression}) + write.csv(as.data.frame(filtered_df), file = "{output_csv}", row.names = FALSE) + cat("Filtered rows:", nrow(filtered_df), "\\n") + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e 'subset(DataFrame, {subset_expression})'", + "stdout": result.stdout, + "output_files": [output_csv] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stderr": e.stderr + } + +@mcp.tool() +def s4vectors_hits_summary( + from_indices: List[int], + to_indices: List[int], + nLnode: int, + nRnode: int +): + """ + Create an S4Vectors Hits object representing links between two sets of nodes (e.g., overlaps). + + Args: + from_indices: List of 1-based indices for the 'query' or 'left' side. + to_indices: List of 1-based indices for the 'subject' or 'right' side. + nLnode: Total number of nodes in the left set. + nRnode: Total number of nodes in the right set. + """ + if len(from_indices) != len(to_indices): + return {"error": "from_indices and to_indices must have the same length."} + + from_str = ", ".join(map(str, from_indices)) + to_str = ", ".join(map(str, to_indices)) + + r_script = f""" + suppressPackageStartupMessages(library(S4Vectors)) + hits <- Hits(from = c({from_str}), to = c({to_str}), nLnode = {nLnode}, nRnode = {nRnode}) + cat("--- HITS OBJECT ---\\n") + show(hits) + cat("\\n--- TABULATION ---\\n") + cat("Query hits count:\\n") + print(table(queryHits(hits))) + cat("Subject hits count:\\n") + print(table(subjectHits(hits))) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "Rscript -e 'S4Vectors::Hits(...)'", + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stderr": e.stderr + } + +@mcp.tool() +def s4vectors_factor_create( + levels: List[str], + values: List[str] +): + """ + Create an S4Vectors Factor object, which is more memory-efficient than standard R factors. + + Args: + levels: The allowed levels for the factor. + values: The actual data values to be converted to factor. + """ + levels_str = ", ".join([f'"{l}"' for l in levels]) + values_str = ", ".join([f'"{v}"' for v in values]) + + r_script = f""" + suppressPackageStartupMessages(library(S4Vectors)) + f <- Factor(c({values_str}), levels = c({levels_str})) + cat("--- FACTOR SHOW ---\\n") + show(f) + cat("\\n--- LEVELS ---\\n") + print(levels(f)) + cat("\\n--- FREQUENCIES ---\\n") + print(table(f)) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "Rscript -e 'S4Vectors::Factor(...)'", + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stderr": e.stderr + } + +@mcp.tool() +def s4vectors_merge_dataframes( + csv_a: str, + csv_b: str, + output_csv: str, + join_by: str, + all_x: bool = True, + all_y: bool = False +): + """ + Merge two CSV files using S4Vectors DataFrame join logic. + + Args: + csv_a: Path to the first CSV file. + csv_b: Path to the second CSV file. + output_csv: Path to save the merged CSV. + join_by: Column name to join on. + all_x: Logical; if TRUE, keep all rows from csv_a (Left Join). + all_y: Logical; if TRUE, keep all rows from csv_b (Right Join). + """ + path_a = Path(csv_a) + path_b = Path(csv_b) + if not path_a.exists() or not path_b.exists(): + return {"error": "One or both input files not found."} + + all_x_r = "TRUE" if all_x else "FALSE" + all_y_r = "TRUE" if all_y else "FALSE" + + r_script = f""" + suppressPackageStartupMessages(library(S4Vectors)) + df1 <- DataFrame(read.csv("{csv_a}")) + df2 <- DataFrame(read.csv("{csv_b}")) + merged <- merge(df1, df2, by = "{join_by}", all.x = {all_x_r}, all.y = {all_y_r}) + write.csv(as.data.frame(merged), file = "{output_csv}", row.names = FALSE) + cat("Merged rows:", nrow(merged), "\\n") + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e 'merge(DataFrame1, DataFrame2, by=\"{join_by}\")'", + "stdout": result.stdout, + "output_files": [output_csv] + } + 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-s4vectors/app/bioconductor-s4vectors_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4vectors/app/bioconductor-s4vectors_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8b86e16e57dbe84efd0f4736091ce69b23a1e44e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4vectors/app/bioconductor-s4vectors_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-s4vectors/app/bioconductor-s4vectors_server.py') +SERVER_NAME = 'biosci_bioconductor_s4vectors' + + +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-s4vectors/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4vectors/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4vectors/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4vectors/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4vectors/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..ff63a9afa9c91bdd1fedf1de7792eba50df1fd67 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4vectors/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-s4vectors: + build: . + image: mcp-bioconductor-s4vectors:latest + container_name: mcp-bioconductor-s4vectors + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-s4vectors + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-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-s4vectors/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4vectors/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4f7f827691cc7fe8d0a06fd3125b0b48a926aae --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4vectors/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-s4vectors + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4vectors/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4vectors/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-s4vectors/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scaledmatrix/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scaledmatrix/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..862c5654ed91a4cfaa8e41acd84193b7855f55c1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scaledmatrix/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-scaledmatrix via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scaledmatrix -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-scaledmatrix_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-scaledmatrix_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-scaledmatrix_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scaledmatrix/app/bioconductor-scaledmatrix_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scaledmatrix/app/bioconductor-scaledmatrix_server.py new file mode 100644 index 0000000000000000000000000000000000000000..086284b349e38795be7b562f2c4941915b3a1ce9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scaledmatrix/app/bioconductor-scaledmatrix_server.py @@ -0,0 +1,280 @@ +from typing import Optional, List, Union +import subprocess +from pathlib import Path +import json +import tempfile + +@mcp.tool() +def create_scaled_matrix( + input_path: str, + output_path: str, + center: bool = True, + scale: bool = True, + center_vector: Optional[List[float]] = None, + scale_vector: Optional[List[float]] = None, + input_format: str = "rds" +): + """ + Creates a ScaledMatrix object (a DelayedMatrix of scaled and centered values). + The result is equivalent to using the scale() function but avoids explicit realization of a dense matrix. + + Args: + input_path: Path to the input matrix file (RDS, CSV, or TSV). + output_path: Path to save the resulting ScaledMatrix object as an RDS file. + center: Whether to center the columns. Ignored if center_vector is provided. + scale: Whether to scale the columns. Ignored if scale_vector is provided. + center_vector: Specific numeric vector to use for centering (length must match number of columns). + scale_vector: Specific numeric vector to use for scaling (length must match number of columns). + input_format: Format of the input file ('rds', 'csv', 'tsv'). + """ + input_p = Path(input_path) + output_p = Path(output_path) + + if not input_p.exists(): + return {"error": f"Input file not found: {input_path}"} + + # Prepare R arguments for center and scale + r_center = "TRUE" if center else "FALSE" + if center_vector is not None: + r_center = f"c({','.join(map(str, center_vector))})" + + r_scale = "TRUE" if scale else "FALSE" + if scale_vector is not None: + r_scale = f"c({','.join(map(str, scale_vector))})" + + # Construct R script + r_script = f""" + library(ScaledMatrix) + library(Matrix) + + # Load input + if ("{input_format}" == "rds") {{ + x <- readRDS("{input_path}") + }} else if ("{input_format}" == "csv") {{ + x <- as.matrix(read.csv("{input_path}", row.names=1)) + }} else if ("{input_format}" == "tsv") {{ + x <- as.matrix(read.table("{input_path}", sep="\\t", header=TRUE, row.names=1)) + }} else {{ + stop("Unsupported input format") + }} + + # Create ScaledMatrix + sm <- ScaledMatrix(x, center = {r_center}, scale = {r_scale}) + + # Save object + saveRDS(sm, "{output_path}") + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + check=True, + capture_output=True, + text=True + ) + return { + "command_executed": f"ScaledMatrix(x, center={r_center}, scale={r_scale})", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_p)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def realize_scaled_matrix( + input_rds_path: str, + output_path: str, + output_format: str = "csv" +): + """ + Realizes a ScaledMatrix object into a dense matrix and saves it to a file. + Use this to get the actual computed values after scaling/centering. + + Args: + input_rds_path: Path to the ScaledMatrix RDS file. + output_path: Path to save the realized matrix. + output_format: Format of the output file ('csv', 'tsv', 'rds'). + """ + input_p = Path(input_rds_path) + if not input_p.exists(): + return {"error": f"Input file not found: {input_rds_path}"} + + r_script = f""" + library(ScaledMatrix) + sm <- readRDS("{input_rds_path}") + mat <- as.matrix(sm) + + if ("{output_format}" == "csv") {{ + write.csv(mat, "{output_path}") + }} else if ("{output_format}" == "tsv") {{ + write.table(mat, "{output_path}", sep="\\t", quote=FALSE) + }} else if ("{output_format}" == "rds") {{ + saveRDS(mat, "{output_path}") + }} + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + check=True, + capture_output=True, + text=True + ) + return { + "command_executed": "as.matrix(sm)", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_path] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def get_centering_vector(input_rds_path: str): + """ + Extracts the centering vector from a ScaledMatrix object. + + Args: + input_rds_path: Path to the ScaledMatrix RDS file. + """ + input_p = Path(input_rds_path) + if not input_p.exists(): + return {"error": f"Input file not found: {input_rds_path}"} + + r_script = f""" + library(ScaledMatrix) + sm <- readRDS("{input_rds_path}") + cat(jsonlite::toJSON(CenteringVector(sm))) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + check=True, + capture_output=True, + text=True + ) + return { + "centering_vector": json.loads(result.stdout), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} + +@mcp.tool() +def get_scaling_factor(input_rds_path: str): + """ + Extracts the scaling factors from a ScaledMatrix object. + + Args: + input_rds_path: Path to the ScaledMatrix RDS file. + """ + input_p = Path(input_rds_path) + if not input_p.exists(): + return {"error": f"Input file not found: {input_rds_path}"} + + r_script = f""" + library(ScaledMatrix) + sm <- readRDS("{input_rds_path}") + cat(jsonlite::toJSON(ScalingFactor(sm))) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + check=True, + capture_output=True, + text=True + ) + return { + "scaling_factors": json.loads(result.stdout), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} + +@mcp.tool() +def get_unscaled_matrix(input_rds_path: str, output_path: str): + """ + Extracts the original unscaled matrix from a ScaledMatrix object. + + Args: + input_rds_path: Path to the ScaledMatrix RDS file. + output_path: Path to save the unscaled matrix (as RDS). + """ + input_p = Path(input_rds_path) + if not input_p.exists(): + return {"error": f"Input file not found: {input_rds_path}"} + + r_script = f""" + library(ScaledMatrix) + sm <- readRDS("{input_rds_path}") + unscaled_mat <- unscaled(sm) + saveRDS(unscaled_mat, "{output_path}") + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + check=True, + capture_output=True, + text=True + ) + return { + "command_executed": "unscaled(sm)", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_path] + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} + +@mcp.tool() +def get_scaled_matrix_metadata(input_rds_path: str): + """ + Returns metadata about the ScaledMatrix object, including dimensions and whether it is centered/scaled. + + Args: + input_rds_path: Path to the ScaledMatrix RDS file. + """ + input_p = Path(input_rds_path) + if not input_p.exists(): + return {"error": f"Input file not found: {input_rds_path}"} + + r_script = f""" + library(ScaledMatrix) + sm <- readRDS("{input_rds_path}") + info <- list( + dim = dim(sm), + is_centered = !is.null(CenteringVector(sm)), + is_scaled = !is.null(ScalingFactor(sm)), + class = class(sm)[1] + ) + cat(jsonlite::toJSON(info, auto_unbox=TRUE)) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + check=True, + capture_output=True, + text=True + ) + return { + "metadata": json.loads(result.stdout), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scaledmatrix/app/bioconductor-scaledmatrix_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scaledmatrix/app/bioconductor-scaledmatrix_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..74e9c6b68f0095c45c14a100810a6f5da7cd30e9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scaledmatrix/app/bioconductor-scaledmatrix_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-scaledmatrix/app/bioconductor-scaledmatrix_server.py') +SERVER_NAME = 'biosci_bioconductor_scaledmatrix' + + +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-scaledmatrix/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scaledmatrix/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scaledmatrix/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scaledmatrix/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scaledmatrix/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..579e240112737466516689b1a6b524bd1197a6da --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scaledmatrix/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-scaledmatrix: + build: . + image: mcp-bioconductor-scaledmatrix:latest + container_name: mcp-bioconductor-scaledmatrix + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-scaledmatrix + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scaledmatrix/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scaledmatrix/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..878ec71749037ad915d6b8be492005dbf6be2188 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scaledmatrix/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-scaledmatrix + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scaledmatrix/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scaledmatrix/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scaledmatrix/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scalign/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scalign/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b59bf89a693f43400c771a6d529f61bafc3eafa5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scalign/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-scalign via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scalign -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-scalign_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-scalign_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-scalign_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scalign/app/bioconductor-scalign_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scalign/app/bioconductor-scalign_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9ee159d61d2b9a5b1897cdedd404e738a9f9b898 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scalign/app/bioconductor-scalign_server.py @@ -0,0 +1,216 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Literal + +# NOTE: The `@mcp.tool` decorator is a placeholder. +# In a real MCP environment, it would be provided by the MCP framework. +# For this code to be executable standalone, you would need to define or remove the decorator. +class _MCP: + def tool(self, *args, **kwargs): + def decorator(func): + return func + return decorator +mcp = _MCP() + + +@mcp.tool() +def scalign( + sce_objects: List[Path], + output_prefix: str, + genes_use_file: Optional[Path] = None, + data_use: str = "counts", + architecture: Literal["small", "medium", "large", "large_deep"] = "large_deep", + num_dim: int = 32, + mini_batch_size: int = 256, + num_steps: int = 10000, + learning_rate: float = 0.001, + log_every: int = 100, + run_tsne: bool = True, + tsne_dims: int = 2, + tsne_perplexity: int = 30, + seed: Optional[int] = None, +) -> dict: + """ + Aligns multiple single-cell datasets using the scAlign R package. + + This tool is a wrapper for the Bioconductor package scAlign, which performs + unsupervised deep learning to align and integrate single-cell genomic data + across different conditions, tissues, or species. The primary input is a list + of SingleCellExperiment objects saved in RDS format. + + Args: + sce_objects: A list of paths to input SingleCellExperiment objects stored in RDS format. + output_prefix: The prefix for all output files. The main output will be an RDS file + named `{output_prefix}_aligned.rds`. + genes_use_file: An optional path to a file containing a list of genes to use for + alignment, one gene per line. If not provided, all shared genes are used. + data_use: The assay name from the SingleCellExperiment objects to use for alignment + (e.g., 'counts', 'logcounts'). + architecture: The neural network architecture to use for the alignment model. + num_dim: The number of dimensions in the latent space. + mini_batch_size: The size of mini-batches for training the neural network. + num_steps: The total number of training steps. + learning_rate: The learning rate for the Adam optimizer. + log_every: The frequency (in steps) to log training progress. + run_tsne: If True, run t-SNE on the aligned cell embeddings. + tsne_dims: The number of dimensions for the t-SNE embedding. + tsne_perplexity: The perplexity parameter for t-SNE. + seed: An optional integer seed for reproducibility. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a list of + output file paths. + """ + # --- Input Validation --- + if not sce_objects: + raise ValueError("At least one SingleCellExperiment object path must be provided in sce_objects.") + for p in sce_objects: + if not p.is_file(): + raise FileNotFoundError(f"Input file not found: {p}") + + if genes_use_file and not genes_use_file.is_file(): + raise FileNotFoundError(f"Genes file not found: {genes_use_file}") + + if num_dim <= 0: + raise ValueError("num_dim must be a positive integer.") + if mini_batch_size <= 0: + raise ValueError("mini_batch_size must be a positive integer.") + if num_steps <= 0: + raise ValueError("num_steps must be a positive integer.") + if learning_rate <= 0: + raise ValueError("learning_rate must be a positive float.") + if log_every <= 0: + raise ValueError("log_every must be a positive integer.") + if tsne_dims <= 0: + raise ValueError("tsne_dims must be a positive integer.") + if tsne_perplexity <= 0: + raise ValueError("tsne_perplexity must be a positive integer.") + + # --- R Script Generation --- + # This script will be executed by Rscript. It loads the data, runs scAlign, + # and saves the results. + r_script_content = f""" + # Load necessary libraries + library(scAlign) + library(SingleCellExperiment) + + # --- Parse Arguments --- + args <- commandArgs(trailingOnly = TRUE) + output_prefix <- args[1] + data_use <- args[2] + architecture <- args[3] + num_dim <- as.integer(args[4]) + mini_batch_size <- as.integer(args[5]) + num_steps <- as.integer(args[6]) + learning_rate <- as.numeric(args[7]) + log_every <- as.integer(args[8]) + run_tsne <- as.logical(args[9]) + tsne_dims <- as.integer(args[10]) + tsne_perplexity <- as.integer(args[11]) + seed_val <- args[12] + genes_file_path <- args[13] + sce_paths <- args[14:length(args)] + + # --- Set Seed for Reproducibility --- + if (seed_val != "NULL") {{ + set.seed(as.integer(seed_val)) + }} + + # --- Load Data --- + message("Loading SingleCellExperiment objects...") + sce.objects <- lapply(sce_paths, readRDS) + message(paste("Loaded", length(sce.objects), "objects.")) + + # --- Load Genes --- + genes.use <- NULL + if (genes_file_path != "NULL") {{ + message(paste("Reading genes from:", genes_file_path)) + genes.use <- readLines(genes_file_path) + }} + + # --- Run scAlign --- + message("Running scAlign alignment...") + scAlign.result <- scAlign( + sce.objects = sce.objects, + genes.use = genes.use, + data.use = data_use, + options = scAlignOptions( + architecture = architecture, + num.dim = num_dim, + mini.batch.size = mini_batch_size, + num.steps = num_steps, + learning.rate = learning_rate, + log.every = log_every + ), + run.tsne = run_tsne, + tsne.dims = tsne_dims, + tsne.perplexity = tsne_perplexity + ) + message("scAlign finished.") + + # --- Save Output --- + output_rds_path <- paste0(output_prefix, "_aligned.rds") + message(paste("Saving aligned object to:", output_rds_path)) + saveRDS(scAlign.result, file = output_rds_path) + message("Script finished successfully.") + """ + + # --- Subprocess Execution --- + r_script_path = "" + command_executed = "" + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = r_script_file.name + + cmd = [ + "Rscript", + r_script_path, + output_prefix, + data_use, + architecture, + str(num_dim), + str(mini_batch_size), + str(num_steps), + str(learning_rate), + str(log_every), + str(run_tsne).upper(), # R expects TRUE/FALSE + str(tsne_dims), + str(tsne_perplexity), + str(seed) if seed is not None else "NULL", + str(genes_use_file) if genes_use_file is not None else "NULL", + ] + cmd.extend([str(p.resolve()) for p in sce_objects]) + + command_executed = " ".join(cmd) + + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + output_files = [f"{output_prefix}_aligned.rds"] + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "scAlign execution failed.", + "return_code": e.returncode, + "output_files": [], + } + finally: + # Clean up the temporary R script + if r_script_path and Path(r_script_path).exists(): + Path(r_script_path).unlink() diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scalign/app/bioconductor-scalign_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scalign/app/bioconductor-scalign_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f4102d9632bba6a84eaa4930b67a019cd6aba933 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scalign/app/bioconductor-scalign_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-scalign/app/bioconductor-scalign_server.py') +SERVER_NAME = 'biosci_bioconductor_scalign' + + +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-scalign/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scalign/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b197320002adf2df3eed71f0358d144c8e308035 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scalign/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-scalign: + build: . + image: mcp-bioconductor-scalign:latest + container_name: mcp-bioconductor-scalign + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-scalign + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scalign/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scalign/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4b20c4d1e54e4c60f5efb46364108fdf4f769534 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scalign/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-scalign + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scalign/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scalign/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scalign/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scannotatr/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scannotatr/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..987f45428d4cd9ad643e81d0084ba21896dca330 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scannotatr/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-scannotatr via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scannotatr -y && conda clean -a + +# 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-scannotatr_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-scannotatr_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-scannotatr_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scannotatr/app/bioconductor-scannotatr_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scannotatr/app/bioconductor-scannotatr_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5347c63ed12635bb23380045dd3b12acab516ac0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scannotatr/app/bioconductor-scannotatr_server.py @@ -0,0 +1,368 @@ +import subprocess +import tempfile +import logging +from pathlib import Path +from typing import Optional, List + +# Configure logging +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') + +# @mcp.tool() +def scannotatr_classify( + seurat_object: Path, + output_predictions: Path, + model: str = "scAnnotatR_human_main_v1", + output_object: Optional[Path] = None, +) -> dict: + """ + Annotates cells in a Seurat object using a pre-trained scAnnotatR model. + + This function takes a Seurat object, applies a specified pre-trained classification + model from AnnotationHub, and outputs the cell type predictions to a CSV file. + It can also optionally save the fully annotated Seurat object. + + Args: + seurat_object: Path to the input Seurat object file in .rds format. + output_predictions: Path to save the output cell type predictions in CSV format. + model: The name of the pre-trained model to use from AnnotationHub. + output_object: Optional path to save the annotated Seurat object in .rds format. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # Input validation + if not seurat_object.is_file(): + raise FileNotFoundError(f"Input Seurat object not found at: {seurat_object}") + + output_files = [str(output_predictions)] + if output_object: + output_files.append(str(output_object)) + + r_script_content = f""" + # R script for scAnnotatR classification + options(warn=-1) + suppressPackageStartupMessages({{ + library(optparse) + library(scAnnotatR) + library(Seurat) + }}) + + option_list <- list( + make_option(c("-i", "--input_object"), type="character", help="Path to input Seurat object (.rds)."), + make_option(c("-p", "--output_predictions"), type="character", help="Path for the output predictions CSV file."), + make_option(c("-m", "--model"), type="character", help="Model name from AnnotationHub."), + make_option(c("-s", "--output_object"), type="character", default=NULL, help="Optional path to save the annotated Seurat object (.rds).") + ) + + args <- parse_args(OptionParser(option_list=option_list)) + + # Load data + seurat_obj <- readRDS(args$input_object) + + # Run classification + cat("Running scAnnotatR classification...\\n") + seurat_obj <- scAnnotatR(seurat_obj, model = args$model, plot = FALSE) + cat("Classification complete.\\n") + + # Determine prediction column name + pred_col_name <- paste0(args$model, "_prediction") + if (!pred_col_name %in% colnames(seurat_obj@meta.data)) {{ + # Fallback for potential naming variations + pred_col_name_alt <- "scAnnotatR_cell_type" + if (pred_col_name_alt %in% colnames(seurat_obj@meta.data)) {{ + pred_col_name <- pred_col_name_alt + }} else {{ + stop(paste("Prediction column '", pred_col_name, "' not found in Seurat object metadata.", sep="")) + }} + }} + + # Extract and save predictions + predictions <- seurat_obj@meta.data[, pred_col_name, drop = FALSE] + colnames(predictions)[1] <- "predicted_cell_type" + write.csv(predictions, file = args$output_predictions, row.names = TRUE) + cat(paste("Predictions saved to", args$output_predictions, "\\n")) + + # Save the full object if requested + if (!is.null(args$output_object)) {{ + saveRDS(seurat_obj, file = args$output_object) + cat(paste("Annotated Seurat object saved to", args$output_object, "\\n")) + }} + """ + + with tempfile.TemporaryDirectory() as temp_dir: + r_script_path = Path(temp_dir) / "classify.R" + with open(r_script_path, "w") as f: + f.write(r_script_content) + + cmd = [ + "Rscript", str(r_script_path), + "--input_object", str(seurat_object), + "--output_predictions", str(output_predictions), + "--model", model, + ] + if output_object: + cmd.extend(["--output_object", str(output_object)]) + + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + cwd=temp_dir + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + logging.error(f"Error executing scAnnotatR classification: {e.stderr}") + raise e + +# @mcp.tool() +def scannotatr_train_basic_model( + seurat_object: Path, + cell_type_column: str, + output_model: Path, + model_name: str, + n_features: int = 2000, + svm_kernel: str = "radial", + cv_folds: int = 5, +) -> dict: + """ + Trains a new basic scAnnotatR model from a labeled Seurat object. + + Args: + seurat_object: Path to the input Seurat object (.rds) with cell type labels in metadata. + cell_type_column: The name of the metadata column containing the cell type labels. + output_model: Path to save the trained model file (.rds). + model_name: A descriptive name for the new model. + n_features: Number of variable features to use for training. + svm_kernel: The SVM kernel to use. Must be one of 'linear', 'radial', 'polynomial', 'sigmoid'. + cv_folds: Number of folds for cross-validation during training. + + Returns: + A dictionary containing the executed command, stdout, stderr, and the path to the output model. + """ + # Input validation + if not seurat_object.is_file(): + raise FileNotFoundError(f"Input Seurat object not found at: {seurat_object}") + + valid_kernels = ['linear', 'radial', 'polynomial', 'sigmoid'] + if svm_kernel not in valid_kernels: + raise ValueError(f"Invalid svm_kernel '{svm_kernel}'. Must be one of {valid_kernels}.") + + if n_features <= 0: + raise ValueError("n_features must be a positive integer.") + + if cv_folds <= 1: + raise ValueError("cv_folds must be an integer greater than 1.") + + r_script_content = f""" + # R script for training a basic scAnnotatR model + options(warn=-1) + suppressPackageStartupMessages({{ + library(optparse) + library(scAnnotatR) + library(Seurat) + }}) + + option_list <- list( + make_option(c("-i", "--input_object"), type="character", help="Path to input Seurat object (.rds)."), + make_option(c("-c", "--cell_type_column"), type="character", help="Metadata column containing cell type labels."), + make_option(c("-o", "--output_model"), type="character", help="Path to save the trained model (.rds)."), + make_option(c("-n", "--model_name"), type="character", help="A name for the new model."), + make_option(c("-f", "--n_features"), type="integer", help="Number of variable features."), + make_option(c("-k", "--svm_kernel"), type="character", help="SVM kernel."), + make_option(c("-v", "--cv_folds"), type="integer", help="Number of cross-validation folds.") + ) + + args <- parse_args(OptionParser(option_list=option_list)) + + cat("Loading Seurat object...\\n") + seurat_obj <- readRDS(args$input_object) + + cat("Starting model training...\\n") + trained_model <- train_model( + seurat_object = seurat_obj, + cell_type_column = args$cell_type_column, + model_name = args$model_name, + n_features = args$n_features, + svm_kernel = args$svm_kernel, + cv_folds = args$cv_folds + ) + cat("Model training complete.\\n") + + saveRDS(trained_model, file = args$output_model) + cat(paste("Trained model saved to", args$output_model, "\\n")) + """ + + with tempfile.TemporaryDirectory() as temp_dir: + r_script_path = Path(temp_dir) / "train_basic.R" + with open(r_script_path, "w") as f: + f.write(r_script_content) + + cmd = [ + "Rscript", str(r_script_path), + "--input_object", str(seurat_object), + "--cell_type_column", cell_type_column, + "--output_model", str(output_model), + "--model_name", model_name, + "--n_features", str(n_features), + "--svm_kernel", svm_kernel, + "--cv_folds", str(cv_folds), + ] + + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + cwd=temp_dir + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_model)], + } + except subprocess.CalledProcessError as e: + logging.error(f"Error executing scAnnotatR basic model training: {e.stderr}") + raise e + +# @mcp.tool() +def scannotatr_train_child_model( + seurat_object: Path, + cell_type_column: str, + parent_model: Path, + parent_cell_type: str, + output_model: Path, + model_name: str, + n_features: int = 2000, + svm_kernel: str = "radial", + cv_folds: int = 5, +) -> dict: + """ + Trains a new child model to sub-classify a cell type from a parent model. + + Args: + seurat_object: Path to the input Seurat object (.rds) with subtype labels. + cell_type_column: Metadata column with the subtype labels for training. + parent_model: Path to the parent scAnnotatR model file (.rds). + parent_cell_type: The cell type in the parent model to be sub-classified. + output_model: Path to save the updated model containing the new child model (.rds). + model_name: A descriptive name for the new child model. + n_features: Number of variable features to use for training. + svm_kernel: The SVM kernel to use. Must be one of 'linear', 'radial', 'polynomial', 'sigmoid'. + cv_folds: Number of folds for cross-validation. + + Returns: + A dictionary containing the executed command, stdout, stderr, and the path to the output model. + """ + # Input validation + if not seurat_object.is_file(): + raise FileNotFoundError(f"Input Seurat object not found at: {seurat_object}") + if not parent_model.is_file(): + raise FileNotFoundError(f"Parent model file not found at: {parent_model}") + + valid_kernels = ['linear', 'radial', 'polynomial', 'sigmoid'] + if svm_kernel not in valid_kernels: + raise ValueError(f"Invalid svm_kernel '{svm_kernel}'. Must be one of {valid_kernels}.") + + if n_features <= 0: + raise ValueError("n_features must be a positive integer.") + + if cv_folds <= 1: + raise ValueError("cv_folds must be an integer greater than 1.") + + r_script_content = f""" + # R script for training a child scAnnotatR model + options(warn=-1) + suppressPackageStartupMessages({{ + library(optparse) + library(scAnnotatR) + library(Seurat) + }}) + + option_list <- list( + make_option(c("-i", "--input_object"), type="character", help="Path to input Seurat object (.rds)."), + make_option(c("-c", "--cell_type_column"), type="character", help="Metadata column with subtype labels."), + make_option(c("-p", "--parent_model"), type="character", help="Path to the parent model (.rds)."), + make_option(c("-t", "--parent_cell_type"), type="character", help="Parent cell type to sub-classify."), + make_option(c("-o", "--output_model"), type="character", help="Path to save the updated model (.rds)."), + make_option(c("-n", "--model_name"), type="character", help="Name for the new child model."), + make_option(c("-f", "--n_features"), type="integer", help="Number of variable features."), + make_option(c("-k", "--svm_kernel"), type="character", help="SVM kernel."), + make_option(c("-v", "--cv_folds"), type="integer", help="Number of cross-validation folds.") + ) + + args <- parse_args(OptionParser(option_list=option_list)) + + cat("Loading data and parent model...\\n") + seurat_obj <- readRDS(args$input_object) + parent_model_obj <- readRDS(args$parent_model) + + cat("Starting child model training...\\n") + updated_model <- train_child_model( + seurat_object = seurat_obj, + cell_type_column = args$cell_type_column, + parent_model = parent_model_obj, + parent_cell_type = args$parent_cell_type, + model_name = args$model_name, + n_features = args$n_features, + svm_kernel = args$svm_kernel, + cv_folds = args$cv_folds + ) + cat("Child model training complete.\\n") + + saveRDS(updated_model, file = args$output_model) + cat(paste("Updated model saved to", args$output_model, "\\n")) + """ + + with tempfile.TemporaryDirectory() as temp_dir: + r_script_path = Path(temp_dir) / "train_child.R" + with open(r_script_path, "w") as f: + f.write(r_script_content) + + cmd = [ + "Rscript", str(r_script_path), + "--input_object", str(seurat_object), + "--cell_type_column", cell_type_column, + "--parent_model", str(parent_model), + "--parent_cell_type", parent_cell_type, + "--output_model", str(output_model), + "--model_name", model_name, + "--n_features", str(n_features), + "--svm_kernel", svm_kernel, + "--cv_folds", str(cv_folds), + ] + + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + cwd=temp_dir + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_model)], + } + except subprocess.CalledProcessError as e: + logging.error(f"Error executing scAnnotatR child model training: {e.stderr}") + raise e \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scannotatr/app/bioconductor-scannotatr_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scannotatr/app/bioconductor-scannotatr_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1b57facd8bc2f5d4936ab167fd7575591c7df953 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scannotatr/app/bioconductor-scannotatr_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-scannotatr/app/bioconductor-scannotatr_server.py') +SERVER_NAME = 'biosci_bioconductor_scannotatr' + + +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-scannotatr/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scannotatr/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d56a0de8b473bf686343cf188737909efb23e7ea --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scannotatr/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-scannotatr: + build: . + image: mcp-bioconductor-scannotatr:latest + container_name: mcp-bioconductor-scannotatr + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-scannotatr + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-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-scannotatr/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scannotatr/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c76371f56992320e4953b376a21d71e39611702a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scannotatr/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-scannotatr + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scannotatr/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scannotatr/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scannotatr/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scarray.sat/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scarray.sat/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2a2ae6de9292099994cb6deedf1e0671bc84fe9c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scarray.sat/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-scarray.sat via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scarray.sat -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-scarray.sat_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-scarray.sat_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-scarray.sat_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scarray.sat/app/bioconductor-scarray.sat_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scarray.sat/app/bioconductor-scarray.sat_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9929f15ac3d64e02e0ab8a480ab77af92f5030ac --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scarray.sat/app/bioconductor-scarray.sat_server.py @@ -0,0 +1,138 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Dict, Optional + +# MCP decorator is assumed to be available from the environment +# import mcp + +@mcp.tool() +def create_gds_seurat_object( + input_dir: Path, + output_rds: Path, + output_gds: Path, + project_name: str = "scproject", + min_cells: int = 3, + min_features: int = 200, +) -> Dict: + """ + Creates a GDS-backed Seurat object from 10x Genomics data using SCArray.sat. + + This tool wraps the bioconductor-scarray.sat R package to convert a standard + 10x Genomics count matrix directory (containing matrix.mtx, features.tsv, + and barcodes.tsv files) into a Seurat object. The key feature is that the + count matrix is stored in a memory-efficient Genomic Data Structure (GDS) file, + making it suitable for very large datasets. + + Args: + input_dir: Path to the input directory containing 10x Genomics data files + (e.g., 'matrix.mtx.gz', 'features.tsv.gz', 'barcodes.tsv.gz'). + output_rds: Path to save the output Seurat object (.rds file). + output_gds: Path to save the generated Genomic Data Structure (.gds file). + project_name: Name for the Seurat project. + min_cells: Include features detected in at least this many cells. + min_features: Include cells with at least this many detected features. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a + dictionary of output file paths. + """ + # --- Input Validation --- + if not input_dir.is_dir(): + raise ValueError(f"Input directory '{input_dir}' does not exist or is not a directory.") + + # Check for required 10x files (allowing for .gz extension and alternative names) + barcodes_path = next(input_dir.glob("barcodes.tsv*"), None) + features_path = next(input_dir.glob("features.tsv*"), None) or next(input_dir.glob("genes.tsv*"), None) + matrix_path = next(input_dir.glob("matrix.mtx*"), None) + + if not all([barcodes_path, features_path, matrix_path]): + raise FileNotFoundError( + "The input directory must contain 'barcodes.tsv', 'features.tsv' (or 'genes.tsv'), " + "and 'matrix.mtx'. Compressed versions (.gz) are accepted." + ) + + if min_cells < 0: + raise ValueError("min_cells must be a non-negative integer.") + if min_features < 0: + raise ValueError("min_features must be a non-negative integer.") + + # --- R Script Generation --- + # This script performs the core logic using the R libraries. + r_script_content = f""" + # Load required libraries + library(Seurat) + library(SCArray.sat) + library(SCArray) + + # Define parameters passed from the Python wrapper + input_dir_path <- "{input_dir.resolve()}" + output_rds_path <- "{output_rds.resolve()}" + output_gds_path <- "{output_gds.resolve()}" + project_id <- "{project_name}" + min_cell_count <- {min_cells} + min_feature_count <- {min_features} + + # Read the 10X data. Read10X handles compressed files automatically. + counts <- Seurat::Read10X(data.dir = input_dir_path) + + # Create the GDS file from the count matrix. This is the main step + # provided by the SCArray package. + SCArray::scarray_create(output_gds_path, counts, verbose = TRUE) + + # Create the Seurat object using the GDS-backed matrix. + # The scarray() function loads the GDS file as a DelayedMatrix object. + seurat_obj <- Seurat::CreateSeuratObject( + counts = SCArray::scarray(output_gds_path), + project = project_id, + min.cells = min_cell_count, + min.features = min_feature_count + ) + + # Save the final Seurat object to an RDS file for later use in R. + saveRDS(seurat_obj, file = output_rds_path) + + cat("Successfully created GDS-backed Seurat object and saved to RDS.\\n") + """ + + # --- Subprocess Execution --- + # Use a temporary file to hold the R script + r_script_path = None + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = Path(r_script_file.name) + + cmd = ["Rscript", str(r_script_path)] + command_executed = " ".join(cmd) + + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + + # --- Return Structured Output --- + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": { + "seurat_object_rds": str(output_rds.resolve()), + "gds_file": str(output_gds.resolve()) + } + } + except subprocess.CalledProcessError as e: + # --- Error Handling --- + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + "error": "R script execution failed. Please check the logs for details from Seurat or SCArray." + } + finally: + # Ensure the temporary R script is cleaned up + if r_script_path and r_script_path.exists(): + r_script_path.unlink() diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scarray.sat/app/bioconductor-scarray.sat_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scarray.sat/app/bioconductor-scarray.sat_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c2ec698164f847a41c4d28c009bd64e6581fc2d9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scarray.sat/app/bioconductor-scarray.sat_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-scarray.sat/app/bioconductor-scarray.sat_server.py') +SERVER_NAME = 'biosci_bioconductor_scarray_sat' + + +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-scarray.sat/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scarray.sat/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..db5d8105ceb8dd08e531d26a061c149becd2a8cb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scarray.sat/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-scarray.sat: + build: . + image: mcp-bioconductor-scarray.sat:latest + container_name: mcp-bioconductor-scarray.sat + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-scarray.sat + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scarray.sat/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scarray.sat/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..af4e00630553847553f47ff1414b313f83f1b409 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scarray.sat/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-scarray.sat + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scarray.sat/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scarray.sat/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scarray.sat/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scater/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scater/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ecac8858d36b4624367e8f98d559c4516e813f36 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scater/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-scater via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scater -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-scater_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-scater_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-scater_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scater/app/bioconductor-scater_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scater/app/bioconductor-scater_server.py new file mode 100644 index 0000000000000000000000000000000000000000..073da0c304d07ed6cf2081cc74be6357b8e69b36 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scater/app/bioconductor-scater_server.py @@ -0,0 +1,215 @@ +import subprocess +import tempfile +import textwrap +from pathlib import Path +from typing import List, Optional + + +def _validate_r_input(input_path: Path): + """Check if the input file exists and has a .rds extension.""" + if not input_path.exists(): + raise FileNotFoundError(f"Input file not found: {input_path}") + if input_path.suffix.lower() != ".rds": + raise ValueError(f"Input file must be an RDS file (*.rds), but got: {input_path}") + +# @mcp.tool() decorator would be here in a real MCP environment +def run_scater_workflow( + input_sce_rds: Path, + output_prefix: str = "scater_analysis", + mito_pattern: str = "^MT-", + nmads: float = 3.0, + min_library_size: Optional[int] = None, + min_features: Optional[int] = None, + max_mito_percent: Optional[float] = None, + run_pca: bool = True, + n_pca_components: int = 50, + run_tsne: bool = True, + tsne_perplexity: int = 30, + run_umap: bool = True, + umap_n_neighbors: int = 15, + n_top_features_plot: int = 20, + plot_format: str = "png", +) -> dict: + """ + Executes a standard scRNA-seq QC and visualization workflow using the scater R package. + + This tool takes a SingleCellExperiment object (in RDS format), calculates quality + control metrics, performs filtering, normalizes the data, runs dimensionality + reduction (PCA, t-SNE, UMAP), and generates diagnostic plots. + + Args: + input_sce_rds: Path to the input SingleCellExperiment object saved as an RDS file. + output_prefix: Prefix for all output files (e.g., plots, processed RDS). + mito_pattern: Regex pattern to identify mitochondrial genes for QC. + nmads: Number of median absolute deviations (MADs) to use for adaptive thresholding in QC filtering. + min_library_size: If set, filters cells with a total library size (sum of counts) below this value. Overrides MAD-based filtering for library size. + min_features: If set, filters cells with a number of detected features below this value. Overrides MAD-based filtering for features. + max_mito_percent: If set, filters cells with a mitochondrial read percentage above this value. Overrides MAD-based filtering for mito percent. + run_pca: Whether to perform Principal Component Analysis (PCA). + n_pca_components: Number of principal components to compute. + run_tsne: Whether to perform t-SNE dimensionality reduction. + tsne_perplexity: Perplexity parameter for the t-SNE algorithm. + run_umap: Whether to perform UMAP dimensionality reduction. + umap_n_neighbors: Number of neighbors parameter for the UMAP algorithm. + n_top_features_plot: Number of top expressed features to include in the summary plot. + plot_format: The file format for the output plots ('png', 'pdf', 'svg'). + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output file paths. + """ + # --- Input Validation --- + _validate_r_input(input_sce_rds) + if n_pca_components <= 0: + raise ValueError("n_pca_components must be a positive integer.") + if tsne_perplexity <= 0: + raise ValueError("tsne_perplexity must be a positive integer.") + if umap_n_neighbors <= 0: + raise ValueError("umap_n_neighbors must be a positive integer.") + if n_top_features_plot <= 0: + raise ValueError("n_top_features_plot must be a positive integer.") + if plot_format.lower() not in ["png", "pdf", "svg"]: + raise ValueError("plot_format must be one of 'png', 'pdf', or 'svg'.") + + # --- R Script Generation --- + # Note: Modern scater relies heavily on scuttle for QC and normalization. + # The script reflects current best practices. + r_script_content = textwrap.dedent(f""" + # Load necessary libraries + suppressPackageStartupMessages(library(scater)) + suppressPackageStartupMessages(library(scuttle)) + suppressPackageStartupMessages(library(SingleCellExperiment)) + suppressPackageStartupMessages(library(ggplot2)) + suppressPackageStartupMessages(library(BiocParallel)) + + # Set a seed for reproducibility + set.seed(42) + + # --- 1. Load Data --- + cat("Loading input SingleCellExperiment object from {input_sce_rds}\\n") + sce <- readRDS("{input_sce_rds}") + + # --- 2. Quality Control --- + cat("Calculating per-cell QC metrics...\\n") + mito_genes <- grepl("{mito_pattern}", rownames(sce)) + sce <- addPerCellQC(sce, subsets=list(Mito=mito_genes), BPPARAM=SerialParam()) + + # --- 3. Filtering --- + cat("Filtering low-quality cells...\\n") + # Using isOutlier from scuttle for adaptive filtering + qc_reasons <- perCellQCFilters(sce, sub.fields="subsets_Mito_percent", nmads={nmads}) + + # Override with fixed thresholds if provided + if (!is.null({min_library_size if min_library_size is not None else 'NULL'})) {{ + qc_reasons$low_libsize <- sce$sum < {min_library_size} + }} + if (!is.null({min_features if min_features is not None else 'NULL'})) {{ + qc_reasons$low_n_features <- sce$detected < {min_features} + }} + if (!is.null({max_mito_percent if max_mito_percent is not None else 'NULL'})) {{ + qc_reasons$high_subsets_Mito_percent <- sce$subsets_Mito_percent > {max_mito_percent} + }} + + # Combine filters and subset the object + colData(sce)$discard <- qc_reasons$discard + sce_filtered <- sce[, !sce$discard] + cat(paste("Removed", sum(sce$discard), "cells out of", ncol(sce), "\\n")) + cat(paste("Remaining cells:", ncol(sce_filtered), "\\n")) + + # --- 4. Normalization --- + cat("Performing log-normalization...\\n") + sce_filtered <- logNormCounts(sce_filtered) + + # --- 5. Dimensionality Reduction --- + if ({str(run_pca).upper()}) {{ + cat("Running PCA...\\n") + sce_filtered <- runPCA(sce_filtered, ncomponents={n_pca_components}) + }} + if ({str(run_tsne).upper()}) {{ + cat("Running t-SNE...\\n") + sce_filtered <- runTSNE(sce_filtered, dimred="PCA", perplexity={tsne_perplexity}, BPPARAM=SerialParam()) + }} + if ({str(run_umap).upper()}) {{ + cat("Running UMAP...\\n") + sce_filtered <- runUMAP(sce_filtered, dimred="PCA", n_neighbors={umap_n_neighbors}) + }} + + # --- 6. Visualization --- + cat("Generating plots...\\n") + plot_ext <- ".{plot_format.lower()}" + + # Plot QC metrics on original data + p1 <- plotColData(sce, x="sum", y="detected", colour_by="discard", + other_fields="subsets_Mito_percent") + + scale_x_log10() + scale_y_log10() + + labs(title="QC: Library Size vs Features", x="Total Counts (log10)", y="Detected Features (log10)") + + guides(colour=guide_legend(title="Discarded"), size=guide_legend(title="Mito %")) + ggsave(paste0("{output_prefix}_qc_metrics", plot_ext), p1, width=7, height=5) + + # Plot highest expressed features + p2 <- plotHighestExprs(sce_filtered, n={n_top_features_plot}) + + labs(title="Top Expressed Features") + ggsave(paste0("{output_prefix}_highest_exprs", plot_ext), p2, width=8, height=6) + + # Plot reduced dimensions + if ({str(run_pca).upper()}) {{ + p_pca <- plotReducedDim(sce_filtered, "PCA", colour_by="sum") + + labs(title="PCA colored by Library Size") + ggsave(paste0("{output_prefix}_pca", plot_ext), p_pca, width=6, height=5) + }} + if ({str(run_tsne).upper()}) {{ + p_tsne <- plotReducedDim(sce_filtered, "TSNE", colour_by="detected") + + labs(title="t-SNE colored by Detected Features") + ggsave(paste0("{output_prefix}_tsne", plot_ext), p_tsne, width=6, height=5) + }} + if ({str(run_umap).upper()}) {{ + p_umap <- plotReducedDim(sce_filtered, "UMAP", colour_by="subsets_Mito_percent") + + labs(title="UMAP colored by Mito %") + ggsave(paste0("{output_prefix}_umap", plot_ext), p_umap, width=6, height=5) + }} + + # --- 7. Save Processed Object --- + output_rds_path <- paste0("{output_prefix}_processed.rds") + cat(paste("Saving processed SingleCellExperiment object to", output_rds_path, "\\n")) + saveRDS(sce_filtered, file=output_rds_path) + + cat("Workflow completed successfully.\\n") + """) + + with tempfile.TemporaryDirectory() as temp_dir: + temp_path = Path(temp_dir) + r_script_path = temp_path / "scater_script.R" + with open(r_script_path, "w") as f: + f.write(r_script_content) + + cmd = ["Rscript", str(r_script_path)] + command_executed = " ".join(cmd) + + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + cwd=temp_path, # Run in temp_dir to catch output files + ) + + # --- Collect Output Files --- + output_files: List[str] = [] + for f in temp_path.glob(f"{output_prefix}*"): + # In a real scenario, you'd move these to a persistent output directory + output_files.append(str(f.resolve())) + + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Scater R script execution failed.", + "return_code": e.returncode, + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scater/app/bioconductor-scater_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scater/app/bioconductor-scater_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2281998b22206c810d9cd745e0de12783d2ebc53 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scater/app/bioconductor-scater_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-scater/app/bioconductor-scater_server.py') +SERVER_NAME = 'biosci_bioconductor_scater' + + +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-scater/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scater/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scater/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scater/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scater/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..2cee130eee4b88d8d1c1eb77ebf9173ae81d9e07 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scater/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-scater: + build: . + image: mcp-bioconductor-scater:latest + container_name: mcp-bioconductor-scater + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-scater + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scater/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scater/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4e2a13db73602caa732ca760f80d8e2a9c6c4493 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scater/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-scater + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scater/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scater/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scater/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scbubbletree/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scbubbletree/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..41a95da8aa5b5a70f34d14b5821dab5b2ac86b27 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scbubbletree/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-scbubbletree via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scbubbletree -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-scbubbletree_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-scbubbletree_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-scbubbletree_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scbubbletree/app/bioconductor-scbubbletree_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scbubbletree/app/bioconductor-scbubbletree_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3e6c69bab2ca287d2c6a918b39139a1b644b1527 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scbubbletree/app/bioconductor-scbubbletree_server.py @@ -0,0 +1,209 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional +import logging + +# Configure logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# Per the user's instructions, the mcp decorator is assumed to be available +# in the execution environment, so no import is needed. +# For local testing, a dummy decorator can be used: +# class mcp: +# @staticmethod +# def tool(): +# def decorator(func): +# return func +# return decorator + +@mcp.tool() +def scbubbletree( + sce_file: Path, + output_file: Path, + group: str, + feature: str, + node_level: str, + node_color: Optional[str] = None, + node_label: Optional[str] = None, + node_size: Optional[str] = None, + node_shape: Optional[str] = None, + edge_label: Optional[str] = None, + edge_width: Optional[str] = None, + edge_arrow_size: Optional[float] = None, + layout: str = "tree", + direction: str = "down", + scale: str = "log", + plot_width: float = 10.0, + plot_height: float = 8.0, +): + """ + Generates a bubble tree plot for visualizing hierarchical relationships in single-cell data. + + This tool is a wrapper around the R/Bioconductor package 'scBubbleTree'. It takes a + SingleCellExperiment object (in RDS format) and various plotting parameters to + create a customizable bubble tree visualization. The main function covered is scBubbleTree(). + + Args: + sce_file: Path to the input SingleCellExperiment object saved in RDS format. + output_file: Path to save the output plot file (e.g., 'plot.pdf', 'plot.png'). + group: The name of the column in colData(sce) that contains the cell group information. + feature: A comma-separated string of feature names (e.g., genes) to be plotted. + node_level: The name of the column in colData(sce) that contains the node level information for the tree structure. + node_color: The name of the column in colData(sce) to be used for coloring the nodes. + node_label: The name of the column in colData(sce) to be used for labeling the nodes. + node_size: The name of the column in colData(sce) to be used for sizing the nodes. + node_shape: The name of the column in colData(sce) to be used for the shape of the nodes. + edge_label: The name of the column in colData(sce) to be used for labeling the edges. + edge_width: The name of the column in colData(sce) to be used for the width of the edges. + edge_arrow_size: A numeric value indicating the size of the arrowheads on the edges. + layout: The layout of the tree (default: 'tree'). Passed to ggraph. + direction: The direction of the tree layout (default: 'down'). + scale: The scale to be used for the bubble size (default: 'log'). + plot_width: The width of the output plot in inches (default: 10.0). + plot_height: The height of the output plot in inches (default: 8.0). + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not sce_file.is_file(): + raise FileNotFoundError(f"Input SCE file not found: {sce_file}") + + if not output_file.parent.exists(): + logger.info(f"Output directory {output_file.parent} does not exist. Creating it.") + output_file.parent.mkdir(parents=True, exist_ok=True) + elif not output_file.parent.is_dir(): + raise NotADirectoryError(f"The parent path of the output file is not a directory: {output_file.parent}") + + if not feature: + raise ValueError("The 'feature' parameter cannot be an empty string.") + + if plot_width <= 0 or plot_height <= 0: + raise ValueError("Plot width and height must be positive values.") + + if edge_arrow_size is not None and edge_arrow_size < 0: + raise ValueError("Edge arrow size must be a non-negative value if specified.") + + # --- R Script Generation --- + def r_format(value): + """Helper to convert Python types to R-compatible string representations.""" + if value is None: + return "NULL" + elif isinstance(value, (str, Path)): + # Escape backslashes and quotes for R string + clean_value = str(value).replace('\\', '\\\\').replace('"', '\\"') + return f'"{clean_value}"' + else: + return str(value) + + r_script_content = f""" + # Ensure all required packages are installed and loaded + packages <- c("scBubbleTree", "SingleCellExperiment", "ggplot2") + for (pkg in packages) {{ + if (!requireNamespace(pkg, quietly = TRUE)) {{ + stop(paste("Package '", pkg, "' is not installed. Please install it."), call. = FALSE) + }} + }} + library(scBubbleTree) + library(SingleCellExperiment) + library(ggplot2) + + # --- Read Inputs from Python wrapper --- + sce_file_path <- {r_format(sce_file)} + output_file_path <- {r_format(output_file)} + + # Read the SingleCellExperiment object + sce <- readRDS(sce_file_path) + + # Parse features from comma-separated string + features <- unlist(strsplit({r_format(feature)}, ",")) + + # --- Build Argument List for scBubbleTree --- + sc_args <- list( + sce = sce, + group = {r_format(group)}, + feature = features, + node.level = {r_format(node_level)}, + node.color = {r_format(node_color)}, + node.label = {r_format(node_label)}, + node.size = {r_format(node_size)}, + node.shape = {r_format(node_shape)}, + edge.label = {r_format(edge_label)}, + edge.width = {r_format(edge_width)}, + edge.arrow.size = {r_format(edge_arrow_size)}, + layout = {r_format(layout)}, + direction = {r_format(direction)}, + scale = {r_format(scale)} + ) + + # Remove NULL arguments from the list to use R function defaults + sc_args <- sc_args[!sapply(sc_args, is.null)] + + # --- Execute scBubbleTree and Save Plot --- + tryCatch({{ + # Generate the plot object + p <- do.call(scBubbleTree, sc_args) + + # Save the plot to the specified file + ggsave( + filename = output_file_path, + plot = p, + width = {plot_width}, + height = {plot_height}, + units = "in", + dpi = 300 + ) + + cat("Successfully generated and saved the bubble tree plot to:", output_file_path, "\\n") + + }}, error = function(e) {{ + # Print a more informative error message to stderr + write(paste("Error in scBubbleTree execution:", e$message), stderr()) + quit(status = 1, save = "no") + }}) + """ + + # --- Subprocess Execution --- + command = [] + script_path = None + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, encoding='utf-8') as r_script_file: + r_script_file.write(r_script_content) + script_path = r_script_file.name + + command = ["Rscript", script_path] + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + stdout_str = process.stdout + stderr_str = process.stderr + + except FileNotFoundError: + raise RuntimeError("Rscript command not found. Please ensure R is installed and 'Rscript' is in your system's PATH.") + except subprocess.CalledProcessError as e: + logger.error(f"R script failed with exit code {e.returncode}.") + logger.error(f"STDOUT: {e.stdout}") + logger.error(f"STDERR: {e.stderr}") + raise RuntimeError( + f"R script execution failed. Please check the logs and input parameters.\n" + f"Command: {' '.join(command)}\n" + f"Stderr: {e.stderr}" + ) + finally: + # Clean up the temporary R script file + if script_path and Path(script_path).exists(): + Path(script_path).unlink() + + # --- Structured Result Return --- + return { + "command_executed": " ".join(command), + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": [str(output_file)] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scbubbletree/app/bioconductor-scbubbletree_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scbubbletree/app/bioconductor-scbubbletree_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f7694de2d7f01bac45c9c2790f67e008a38ae3af --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scbubbletree/app/bioconductor-scbubbletree_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-scbubbletree/app/bioconductor-scbubbletree_server.py') +SERVER_NAME = 'biosci_bioconductor_scbubbletree' + + +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-scbubbletree/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scbubbletree/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..a6a5d46ad7336b70ac46e4328d13acb8f021e3af --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scbubbletree/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-scbubbletree: + build: . + image: mcp-bioconductor-scbubbletree:latest + container_name: mcp-bioconductor-scbubbletree + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-scbubbletree + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scbubbletree/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scbubbletree/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6ae5e1881049c0646c50d3c1d832049326b49d71 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scbubbletree/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-scbubbletree + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scbubbletree/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scbubbletree/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scbubbletree/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scclassifr/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scclassifr/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0199e6470eb8a2609d41ef0bd1ef8f0982c7c79b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scclassifr/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-scclassifr via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scclassifr -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-scclassifr_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-scclassifr_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-scclassifr_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scclassifr/app/bioconductor-scclassifr_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scclassifr/app/bioconductor-scclassifr_server.py new file mode 100644 index 0000000000000000000000000000000000000000..565e41f4cf0287753665eed1f72053b3f1d7c5b0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scclassifr/app/bioconductor-scclassifr_server.py @@ -0,0 +1,431 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Literal, Optional, List, Dict, Any + +# This is a placeholder for the actual MCP decorator as per the instructions. +# In a real MCP environment, you would use `from mcp import tool`. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +# Define the available algorithms as a Literal type for type safety and validation +Algorithm = Literal["logistic", "svm", "randomforest", "dlda", "scmap", "scsorter", "seurat"] + +# --- R Script Templates --- +# These scripts are executed by the Python functions to interact with the scClassifR library. + +R_TRAIN_SCRIPT = """ +# R script to train a scClassifR model +suppressPackageStartupMessages(library(optparse)) +suppressPackageStartupMessages(library(scClassifR)) + +option_list <- list( + make_option(c("-e", "--expr_mat"), type="character", default=NULL, + help="Path to the expression matrix CSV file (cells as columns, genes as rows)", metavar="character"), + make_option(c("-c", "--cell_types"), type="character", default=NULL, + help="Path to the cell types CSV file (two columns: cell_id, cell_type)", metavar="character"), + make_option(c("-a", "--algorithm"), type="character", default="logistic", + help="Classification algorithm to use", metavar="character"), + make_option(c("-o", "--output_model"), type="character", default="model.rds", + help="Path to save the output model RDS file", metavar="character") +) + +opt_parser <- OptionParser(option_list=option_list) +opt <- parse_args(opt_parser) + +if (is.null(opt$expr_mat) || is.null(opt$cell_types)){ + print_help(opt_parser) + stop("Expression matrix and cell types files must be supplied.", call.=FALSE) +} + +# Read data +message("Reading expression matrix...") +expr_mat <- as.matrix(read.csv(opt$expr_mat, row.names=1, check.names=FALSE)) +message("Reading cell types...") +cell_types_df <- read.csv(opt$cell_types) + +# Align cell types with expression matrix columns +if (ncol(cell_types_df) < 2) { + stop("Cell types file must have at least two columns (e.g., cell_id, cell_type).", call.=FALSE) +} +colnames(cell_types_df)[1:2] <- c("cell_id", "cell_type") +cell_types_vec <- cell_types_df$cell_type +names(cell_types_vec) <- cell_types_df$cell_id +cell_types_aligned <- cell_types_vec[colnames(expr_mat)] + +if(any(is.na(cell_types_aligned))) { + warning("Some cells in the expression matrix do not have a corresponding cell type. These will be ignored.") + valid_cells <- !is.na(cell_types_aligned) + expr_mat <- expr_mat[, valid_cells] + cell_types_aligned <- cell_types_aligned[valid_cells] +} + +# Train model +message("Training model with algorithm: ", opt$algorithm) +fit <- run_scClassifR(expr_mat = expr_mat, + cell_type = cell_types_aligned, + algorithm = opt$algorithm) + +# Save model +message("Saving model to: ", opt$output_model) +saveRDS(fit, file = opt$output_model) + +message("Training complete.") +""" + +R_PREDICT_SCRIPT = """ +# R script to predict using a trained scClassifR model +suppressPackageStartupMessages(library(optparse)) +suppressPackageStartupMessages(library(scClassifR)) + +option_list <- list( + make_option(c("-t", "--test_data"), type="character", default=NULL, + help="Path to the test data matrix CSV file (cells as columns, genes as rows)", metavar="character"), + make_option(c("-m", "--model"), type="character", default=NULL, + help="Path to the trained model RDS file", metavar="character"), + make_option(c("-o", "--output_predictions"), type="character", default="predictions.csv", + help="Path to save the output predictions CSV file", metavar="character") +) + +opt_parser <- OptionParser(option_list=option_list) +opt <- parse_args(opt_parser) + +if (is.null(opt$test_data) || is.null(opt$model)){ + print_help(opt_parser) + stop("Test data and model file must be supplied.", call.=FALSE) +} + +# Read data and model +message("Reading test data from: ", opt$test_data) +test_data <- as.matrix(read.csv(opt$test_data, row.names=1, check.names=FALSE)) + +message("Loading model from: ", opt$model) +fit <- readRDS(opt$model) + +# Predict +message("Predicting cell types...") +predictions <- predict_scClassifR(test_data = test_data, + fit = fit) + +# Standardize and save predictions +pred_df <- data.frame(cell_id = colnames(test_data), + predicted_cell_type = predictions$pred_labs) + +message("Saving predictions to: ", opt$output_predictions) +write.csv(pred_df, file = opt$output_predictions, row.names = FALSE) + +message("Prediction complete.") +""" + +R_CLASSIFY_SCRIPT = """ +# R script to train and predict with scClassifR in one step +suppressPackageStartupMessages(library(optparse)) +suppressPackageStartupMessages(library(scClassifR)) + +option_list <- list( + make_option(c("--train_data"), type="character", default=NULL, + help="Path to the training expression matrix CSV file", metavar="character"), + make_option(c("--train_cell_types"), type="character", default=NULL, + help="Path to the training cell types CSV file", metavar="character"), + make_option(c("--test_data"), type="character", default=NULL, + help="Path to the test expression matrix CSV file", metavar="character"), + make_option(c("-a", "--algorithm"), type="character", default="logistic", + help="Classification algorithm to use", metavar="character"), + make_option(c("-o", "--output_predictions"), type="character", default="predictions.csv", + help="Path to save the output predictions CSV file", metavar="character"), + make_option(c("-m", "--output_model"), type="character", default=NULL, + help="Optional path to save the trained model RDS file", metavar="character") +) + +opt_parser <- OptionParser(option_list=option_list) +opt <- parse_args(opt_parser) + +if (is.null(opt$train_data) || is.null(opt$train_cell_types) || is.null(opt$test_data)){ + print_help(opt_parser) + stop("Training data, training cell types, and test data must be supplied.", call.=FALSE) +} + +# Read training data +message("Reading training data...") +train_data <- as.matrix(read.csv(opt$train_data, row.names=1, check.names=FALSE)) +train_cell_types_df <- read.csv(opt$train_cell_types) + +# Align training cell types +if (ncol(train_cell_types_df) < 2) { + stop("Training cell types file must have at least two columns (e.g., cell_id, cell_type).", call.=FALSE) +} +colnames(train_cell_types_df)[1:2] <- c("cell_id", "cell_type") +train_cell_types_vec <- train_cell_types_df$cell_type +names(train_cell_types_vec) <- train_cell_types_df$cell_id +train_cell_types_aligned <- train_cell_types_vec[colnames(train_data)] + +if(any(is.na(train_cell_types_aligned))) { + warning("Some cells in the training expression matrix do not have a corresponding cell type. These will be ignored.") + valid_cells <- !is.na(train_cell_types_aligned) + train_data <- train_data[, valid_cells] + train_cell_types_aligned <- train_cell_types_aligned[valid_cells] +} + +# Read test data +message("Reading test data...") +test_data <- as.matrix(read.csv(opt$test_data, row.names=1, check.names=FALSE)) + +# Classify +message("Running classification with algorithm: ", opt$algorithm) +results <- classify_scClassifR(train_data = train_data, + train_cell_type = train_cell_types_aligned, + test_data = test_data, + algorithm = opt$algorithm) + +# Save predictions +pred_df <- data.frame(cell_id = colnames(test_data), + predicted_cell_type = results$pred_labs) + +message("Saving predictions to: ", opt$output_predictions) +write.csv(pred_df, file = opt$output_predictions, row.names = FALSE) + +# Optionally save model +if (!is.null(opt$output_model)) { + message("Saving model to: ", opt$output_model) + saveRDS(results$fit, file = opt$output_model) +} + +message("Classification complete.") +""" + +@mcp.tool() +def scclassifr_train( + expression_matrix: Path, + cell_types: Path, + output_model_path: Path, + algorithm: Algorithm = "logistic", +) -> Dict[str, Any]: + """ + Trains a scClassifR model on a given expression matrix and cell type labels. + + This tool requires R to be installed in the environment, along with the + Bioconductor package 'scClassifR' and the CRAN package 'optparse'. + + Args: + expression_matrix: Path to the expression matrix CSV file. The first column + should be gene names/IDs (and set as row names), and + subsequent columns should be cell IDs. + cell_types: Path to the cell types CSV file. It must contain at least + two columns: the first for cell IDs (matching the expression + matrix) and the second for cell type labels. + output_model_path: Path to save the trained model as an RDS file. + algorithm: The classification algorithm to use. + + Returns: + A dictionary containing the command executed, stdout, stderr, and + the path to the output model file. + """ + # Input validation + if not expression_matrix.is_file(): + raise FileNotFoundError(f"Expression matrix file not found: {expression_matrix}") + if not cell_types.is_file(): + raise FileNotFoundError(f"Cell types file not found: {cell_types}") + + command_executed = "" + r_script_path_str = "" + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(R_TRAIN_SCRIPT) + r_script_path_str = r_script_file.name + + cmd = [ + "Rscript", + r_script_path_str, + "--expr_mat", str(expression_matrix.resolve()), + "--cell_types", str(cell_types.resolve()), + "--algorithm", algorithm, + "--output_model", str(output_model_path.resolve()), + ] + command_executed = " ".join(cmd) + + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_model_path.resolve())] + } + + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed with exit code {e.returncode}", + "output_files": [] + } + finally: + if r_script_path_str and Path(r_script_path_str).exists(): + Path(r_script_path_str).unlink() + +@mcp.tool() +def scclassifr_predict( + test_data: Path, + model: Path, + output_predictions_path: Path, +) -> Dict[str, Any]: + """ + Predicts cell types for a test dataset using a pre-trained scClassifR model. + + This tool requires R to be installed in the environment, along with the + Bioconductor package 'scClassifR' and the CRAN package 'optparse'. + + Args: + test_data: Path to the test data expression matrix CSV file. Format should + match the training data (genes as rows, cells as columns). + model: Path to the pre-trained model RDS file generated by scclassifr_train. + output_predictions_path: Path to save the prediction results as a CSV file. + + Returns: + A dictionary containing the command executed, stdout, stderr, and + the path to the output predictions file. + """ + # Input validation + if not test_data.is_file(): + raise FileNotFoundError(f"Test data file not found: {test_data}") + if not model.is_file(): + raise FileNotFoundError(f"Model file not found: {model}") + + command_executed = "" + r_script_path_str = "" + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(R_PREDICT_SCRIPT) + r_script_path_str = r_script_file.name + + cmd = [ + "Rscript", + r_script_path_str, + "--test_data", str(test_data.resolve()), + "--model", str(model.resolve()), + "--output_predictions", str(output_predictions_path.resolve()), + ] + command_executed = " ".join(cmd) + + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_predictions_path.resolve())] + } + + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed with exit code {e.returncode}", + "output_files": [] + } + finally: + if r_script_path_str and Path(r_script_path_str).exists(): + Path(r_script_path_str).unlink() + +@mcp.tool() +def scclassifr_classify( + train_data: Path, + train_cell_types: Path, + test_data: Path, + output_predictions_path: Path, + algorithm: Algorithm = "logistic", + output_model_path: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Trains a scClassifR model and predicts on a test set in a single step. + + This tool requires R to be installed in the environment, along with the + Bioconductor package 'scClassifR' and the CRAN package 'optparse'. + + Args: + train_data: Path to the training expression matrix CSV file. + train_cell_types: Path to the training cell types CSV file. + test_data: Path to the test expression matrix CSV file. + output_predictions_path: Path to save the prediction results as a CSV file. + algorithm: The classification algorithm to use. + output_model_path: Optional path to save the trained model as an RDS file. + + Returns: + A dictionary containing the command executed, stdout, stderr, and + paths to the output files (predictions and optionally the model). + """ + # Input validation + if not train_data.is_file(): + raise FileNotFoundError(f"Training data file not found: {train_data}") + if not train_cell_types.is_file(): + raise FileNotFoundError(f"Training cell types file not found: {train_cell_types}") + if not test_data.is_file(): + raise FileNotFoundError(f"Test data file not found: {test_data}") + + command_executed = "" + r_script_path_str = "" + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(R_CLASSIFY_SCRIPT) + r_script_path_str = r_script_file.name + + cmd = [ + "Rscript", + r_script_path_str, + "--train_data", str(train_data.resolve()), + "--train_cell_types", str(train_cell_types.resolve()), + "--test_data", str(test_data.resolve()), + "--algorithm", algorithm, + "--output_predictions", str(output_predictions_path.resolve()), + ] + + if output_model_path: + cmd.extend(["--output_model", str(output_model_path.resolve())]) + + command_executed = " ".join(cmd) + + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + + output_files = [str(output_predictions_path.resolve())] + if output_model_path: + output_files.append(str(output_model_path.resolve())) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed with exit code {e.returncode}", + "output_files": [] + } + finally: + if r_script_path_str and Path(r_script_path_str).exists(): + Path(r_script_path_str).unlink() \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scclassifr/app/bioconductor-scclassifr_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scclassifr/app/bioconductor-scclassifr_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..25572150f7704ef52f628431094317584d8bc5fe --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scclassifr/app/bioconductor-scclassifr_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-scclassifr/app/bioconductor-scclassifr_server.py') +SERVER_NAME = 'biosci_bioconductor_scclassifr' + + +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-scclassifr/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scclassifr/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f82f48002d24d6289d3b99f9fba2179a4f651aae --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scclassifr/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-scclassifr: + build: . + image: mcp-bioconductor-scclassifr:latest + container_name: mcp-bioconductor-scclassifr + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-scclassifr + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scclassifr/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scclassifr/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3fb43e58b7333525a1ea7c834d4fb1019f2b9276 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scclassifr/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-scclassifr + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scclassifr/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scclassifr/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scclassifr/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scdotplot/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scdotplot/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3d4c868a815aa829265425f503d9268db6cc690e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scdotplot/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-scdotplot via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scdotplot -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-scdotplot_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-scdotplot_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-scdotplot_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scdotplot/app/bioconductor-scdotplot_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scdotplot/app/bioconductor-scdotplot_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d4fce23c3ba0d1aebe5c1a8c1847921e95095ff8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scdotplot/app/bioconductor-scdotplot_server.py @@ -0,0 +1,265 @@ +import subprocess +import tempfile +import json +from pathlib import Path +from typing import List, Optional, Union + +@mcp.tool() +def sc_dot_plot( + input_path: str, + features: List[str], + group_by: str, + output_path: str = "dotplot.pdf", + cluster_cols: bool = True, + cluster_rows: bool = True, + assay: str = "RNA", + slot: str = "data", + scale: bool = True, + cap: float = 2.5, + annotation_cols: Optional[List[str]] = None, + annotation_rows: Optional[List[str]] = None, +) -> dict: + """ + Generate a clustered single-cell RNA-seq dot plot using the scDotPlot package. + + Args: + input_path: Path to the input file (RDS format containing Seurat or SingleCellExperiment object). + features: List of gene names or features to plot. + group_by: Metadata column name to group cells by (e.g., 'ident' or 'cluster'). + output_path: Path where the resulting plot (PDF, PNG, etc.) will be saved. + cluster_cols: Whether to perform hierarchical clustering on the columns (features). + cluster_rows: Whether to perform hierarchical clustering on the rows (cell groups). + assay: Name of the assay to use (for Seurat objects). + slot: Name of the slot to use (e.g., 'data', 'counts'). + scale: Whether to scale the expression data. + cap: Value at which to cap the scaled expression data. + annotation_cols: Optional list of metadata columns to use for annotating the columns. + annotation_rows: Optional list of metadata columns to use for annotating the rows. + """ + # Input validation + input_file = Path(input_path) + if not input_file.exists(): + return {"error": f"Input file not found: {input_path}"} + + output_file = Path(output_path) + output_file.parent.mkdir(parents=True, exist_ok=True) + + # Prepare R script + features_r = ", ".join([f"'{f}'" for f in features]) + + # Handle optional annotations + ann_cols_r = "NULL" + if annotation_cols: + ann_cols_r = "c(" + ", ".join([f"'{a}'" for a in annotation_cols]) + ")" + + ann_rows_r = "NULL" + if annotation_rows: + ann_rows_r = "c(" + ", ".join([f"'{a}'" for a in annotation_rows]) + ")" + + r_script = f""" + library(scDotPlot) + library(Seurat) + library(SingleCellExperiment) + library(ggplot2) + + # Load object + obj <- readRDS('{input_path}') + + # Generate plot + p <- scDotPlot( + object = obj, + features = c({features_r}), + group.by = '{group_by}', + cluster.cols = {str(cluster_cols).upper()}, + cluster.rows = {str(cluster_rows).upper()}, + assay = '{assay}', + slot = '{slot}', + scale = {str(scale).upper()}, + cap = {cap}, + annotation_cols = {ann_cols_r}, + annotation_rows = {ann_rows_r} + ) + + # Save plot + ggsave('{output_path}', plot = p) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + try: + result = subprocess.run( + ["Rscript", tmp_path], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"scDotPlot on {input_path}", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file.absolute())] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": f"Rscript {tmp_path}" + } + finally: + Path(tmp_path).unlink(missing_ok=True) + +@mcp.tool() +def sc_dot_plot_data( + input_path: str, + features: List[str], + group_by: str, + output_csv: str = "dotplot_data.csv", + assay: str = "RNA", + slot: str = "data", + scale: bool = True, + cap: float = 2.5, +) -> dict: + """ + Extract the underlying data frame used for generating a scDotPlot. + + Args: + input_path: Path to the input file (RDS format). + features: List of gene names or features. + group_by: Metadata column name to group cells by. + output_csv: Path to save the extracted data as a CSV file. + assay: Name of the assay to use. + slot: Name of the slot to use. + scale: Whether to scale the expression data. + cap: Value at which to cap the scaled expression data. + """ + input_file = Path(input_path) + if not input_file.exists(): + return {"error": f"Input file not found: {input_path}"} + + features_r = ", ".join([f"'{f}'" for f in features]) + + r_script = f""" + library(scDotPlot) + library(Seurat) + library(SingleCellExperiment) + + obj <- readRDS('{input_path}') + + # Extract data using the internal data preparation logic + plot_data <- scDotPlotData( + object = obj, + features = c({features_r}), + group.by = '{group_by}', + assay = '{assay}', + slot = '{slot}', + scale = {str(scale).upper()}, + cap = {cap} + ) + + write.csv(plot_data, '{output_csv}', row.names = FALSE) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + try: + result = subprocess.run( + ["Rscript", tmp_path], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"scDotPlotData on {input_path}", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(Path(output_csv).absolute())] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + finally: + Path(tmp_path).unlink(missing_ok=True) + +@mcp.tool() +def sc_dot_plot_custom_df( + data_path: str, + features_col: str, + groups_col: str, + avg_exp_col: str, + pct_exp_col: str, + output_path: str = "dotplot_from_df.pdf", + cluster_cols: bool = True, + cluster_rows: bool = True, +) -> dict: + """ + Generate a clustered dot plot from a pre-calculated data frame instead of a Seurat/SCE object. + + Args: + data_path: Path to a CSV file containing the summarized expression data. + features_col: Column name in the CSV containing gene/feature names. + groups_col: Column name in the CSV containing cell group/cluster names. + avg_exp_col: Column name in the CSV containing average expression values. + pct_exp_col: Column name in the CSV containing percent of cells expressing the gene. + output_path: Path where the resulting plot will be saved. + cluster_cols: Whether to perform hierarchical clustering on columns. + cluster_rows: Whether to perform hierarchical clustering on rows. + """ + data_file = Path(data_path) + if not data_file.exists(): + return {"error": f"Data file not found: {data_path}"} + + r_script = f""" + library(scDotPlot) + library(ggplot2) + + # Load data frame + df <- read.csv('{data_path}') + + # Generate plot using the data frame method + # Note: scDotPlot handles data frames by mapping columns + p <- scDotPlot( + object = df, + features = '{features_col}', + group.by = '{groups_col}', + avg.exp = '{avg_exp_col}', + pct.exp = '{pct_exp_col}', + cluster.cols = {str(cluster_cols).upper()}, + cluster.rows = {str(cluster_rows).upper()} + ) + + ggsave('{output_path}', plot = p) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + try: + result = subprocess.run( + ["Rscript", tmp_path], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"scDotPlot on data frame {data_path}", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(Path(output_path).absolute())] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + finally: + Path(tmp_path).unlink(missing_ok=True) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scdotplot/app/bioconductor-scdotplot_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scdotplot/app/bioconductor-scdotplot_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4cf11410a2198475428a5e4e13de21ca25accd6c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scdotplot/app/bioconductor-scdotplot_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-scdotplot/app/bioconductor-scdotplot_server.py') +SERVER_NAME = 'biosci_bioconductor_scdotplot' + + +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-scdotplot/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scdotplot/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scdotplot/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scdotplot/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scdotplot/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..75f17138ca6bc36ee85fef8d3f0095d8611fcb9c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scdotplot/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-scdotplot: + build: . + image: mcp-bioconductor-scdotplot:latest + container_name: mcp-bioconductor-scdotplot + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-scdotplot + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scdotplot/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scdotplot/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a13eaadf703def4a3951f4ee0662665909ca7c19 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scdotplot/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-scdotplot + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scdotplot/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scdotplot/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scdotplot/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scfeatures/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scfeatures/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..30151fe7846b8c0045d8f7ed6d3d8c9f985c48ba --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scfeatures/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-scfeatures via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scfeatures -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-scfeatures_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-scfeatures_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-scfeatures_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scfeatures/app/bioconductor-scfeatures_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scfeatures/app/bioconductor-scfeatures_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8b405addb0f5e2f10530051dedc15ef8f5158fba --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scfeatures/app/bioconductor-scfeatures_server.py @@ -0,0 +1,242 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided by the MCP framework. +def tool(func): + def wrapper(*args, **kwargs): + # In a real scenario, the MCP framework would handle + # registration, UI generation, and execution. + print(f"Executing tool: {func.__name__}") + return func(*args, **kwargs) + return wrapper + +mcp = type("mcp", (), {"tool": tool}) + + +@mcp.tool +def scfeatures( + input_object: Path, + output_rds: Path, + features: List[str], + species: str = "human", + gene_set_file: Optional[Path] = None, + gene_set_name: str = "custom_gene_set", + n_cores: int = 1, + log_transformed: bool = False, + group_by: Optional[str] = None, + cor_method: str = "spearman", + mito_pattern: str = "^MT-", + ribo_pattern: str = "^RP[SL]", + reduction: Optional[str] = None, +) -> Dict[str, Any]: + """ + Generates multi-view representations of single-cell and spatial data using scFeatures. + + This tool wraps the main `scFeatures()` function from the R/Bioconductor package. + It takes a Seurat or SingleCellExperiment object (in .rds format) and computes + a specified set of features, saving the updated object to a new .rds file. + + Args: + input_object: Path to the input RDS file containing a Seurat or SingleCellExperiment object. + output_rds: Path to save the output RDS file with added features. + features: A list of feature types to compute. + Valid options: 'cell_cell_communication_Spatalk', 'cell_cycle', + 'gene_body_tms', 'gene_gene_correlation', 'gene_set_aucell', + 'gene_set_gsva', 'ligand_receptor_gsea', 'metabolic_pathway_gsea', + 'number_of_genes', 'number_of_umis', 'percent_mito', 'percent_ribo', + 'phate', 'pseudotime', 'spatial_autocorrelation', + 'spatial_cross_correlation', 'spatial_enrichment'. + species: The species of the data. Used for gene set-based features. + Defaults to "human". + gene_set_file: Optional path to a custom gene set file in GMT format. + Required for 'gene_set_aucell' or 'gene_set_gsva' if not using default sets. + gene_set_name: The name for the custom gene set list when using `gene_set_file`. + Defaults to "custom_gene_set". + n_cores: Number of cores to use for parallel processing. Defaults to 1. + log_transformed: Set to True if the input data is already log-transformed. + Defaults to False. + group_by: Metadata column name to group cells by for features like + 'gene_gene_correlation' or 'pseudotime'. + cor_method: Correlation method for 'gene_gene_correlation'. + Defaults to "spearman". + mito_pattern: Regex pattern to identify mitochondrial genes for 'percent_mito'. + Defaults to "^MT-". + ribo_pattern: Regex pattern to identify ribosomal genes for 'percent_ribo'. + Defaults to "^RP[SL]". + reduction: Name of the dimensionality reduction to use for 'pseudotime' calculation. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # 1. Input Validation + if not input_object.is_file(): + raise FileNotFoundError(f"Input file not found: {input_object}") + + if n_cores <= 0: + raise ValueError("n_cores must be a positive integer.") + + if species not in ["human", "mouse"]: + raise ValueError(f"Invalid species: '{species}'. Must be 'human' or 'mouse'.") + + if cor_method not in ["spearman", "pearson", "kendall"]: + raise ValueError(f"Invalid cor_method: '{cor_method}'. Must be 'spearman', 'pearson', or 'kendall'.") + + valid_features = { + 'cell_cell_communication_Spatalk', 'cell_cycle', 'gene_body_tms', + 'gene_gene_correlation', 'gene_set_aucell', 'gene_set_gsva', + 'ligand_receptor_gsea', 'metabolic_pathway_gsea', 'number_of_genes', + 'number_of_umis', 'percent_mito', 'percent_ribo', 'phate', + 'pseudotime', 'spatial_autocorrelation', 'spatial_cross_correlation', + 'spatial_enrichment' + } + for feature in features: + if feature not in valid_features: + raise ValueError(f"Invalid feature '{feature}'. Please choose from the list of valid features.") + + if gene_set_file and not gene_set_file.is_file(): + raise FileNotFoundError(f"Gene set file not found: {gene_set_file}") + + # 2. R Script Generation + # This script will be executed by Rscript. It loads the data, runs scFeatures, + # and saves the result. + r_script_content = f""" + # Load necessary libraries + suppressPackageStartupMessages(library(optparse)) + suppressPackageStartupMessages(library(scFeatures)) + suppressPackageStartupMessages(library(Seurat)) + suppressPackageStartupMessages(library(SingleCellExperiment)) + suppressPackageStartupMessages(library(BiocParallel)) + suppressPackageStartupMessages(library(GSEABase)) # For reading GMT files + + # Define command-line options + option_list <- list( + make_option(c("-i", "--input_object"), type="character", help="Input RDS file path"), + make_option(c("-o", "--output_rds"), type="character", help="Output RDS file path"), + make_option(c("-f", "--features"), type="character", help="Comma-separated list of features"), + make_option(c("-s", "--species"), type="character", default="human", help="Species"), + make_option(c("--gene_set_file"), type="character", default=NULL, help="Path to GMT gene set file"), + make_option(c("--gene_set_name"), type="character", default="custom_gene_set", help="Name for custom gene set"), + make_option(c("-n", "--n_cores"), type="integer", default=1, help="Number of cores"), + make_option(c("--log_transformed"), action="store_true", default=FALSE, help="Flag for log-transformed data"), + make_option(c("--group_by"), type="character", default=NULL, help="Metadata column for grouping"), + make_option(c("--cor_method"), type="character", default="spearman", help="Correlation method"), + make_option(c("--mito_pattern"), type="character", default="^MT-", help="Mitochondrial gene pattern"), + make_option(c("--ribo_pattern"), type="character", default="^RP[SL]", help="Ribosomal gene pattern"), + make_option(c("--reduction"), type="character", default=NULL, help="Reduction for pseudotime") + ) + + # Parse options + opt_parser <- OptionParser(option_list=option_list) + opt <- parse_args(opt_parser) + + # Read input object + message("Reading input object from: ", opt$input_object) + input_obj <- readRDS(opt$input_object) + + # Parse features string into a character vector + features_to_run <- strsplit(opt$features, ",")[[1]] + message("Features to compute: ", paste(features_to_run, collapse=", ")) + + # Set up parallel processing + bpparam <- MulticoreParam(workers = opt$n_cores) + + # Prepare arguments for scFeatures function + scfeatures_args <- list( + object = input_obj, + features = features_to_run, + species = opt$species, + log_transformed = opt$log_transformed, + cor_method = opt$cor_method, + mito_pattern = opt$mito_pattern, + ribo_pattern = opt$ribo_pattern, + BPPARAM = bpparam + ) + + # Add optional arguments if they are provided + if (!is.null(opt$group_by)) {{ + scfeatures_args$group_by <- opt$group_by + }} + if (!is.null(opt$reduction)) {{ + scfeatures_args$reduction <- opt$reduction + }} + if (!is.null(opt$gene_set_file)) {{ + message("Reading custom gene sets from: ", opt$gene_set_file) + gmt <- getGmt(opt$gene_set_file) + gene_sets <- geneIds(gmt) + gene_set_list <- list(gene_sets) + names(gene_set_list) <- opt$gene_set_name + scfeatures_args$gene_set_list <- gene_set_list + }} + + # Run scFeatures with the constructed arguments + message("Running scFeatures...") + output_obj <- do.call(scFeatures, scfeatures_args) + message("scFeatures finished.") + + # Save the resulting object + message("Saving output object to: ", opt$output_rds) + saveRDS(output_obj, file = opt$output_rds) + + message("Successfully completed.") + """ + + with tempfile.TemporaryDirectory() as temp_dir: + r_script_path = Path(temp_dir) / "run_scfeatures.R" + with open(r_script_path, "w") as f: + f.write(r_script_content) + + # 3. Subprocess Execution + cmd = [ + "Rscript", + str(r_script_path), + "--input_object", str(input_object), + "--output_rds", str(output_rds), + "--features", ",".join(features), + "--species", species, + "--n_cores", str(n_cores), + "--cor_method", cor_method, + "--mito_pattern", mito_pattern, + "--ribo_pattern", ribo_pattern, + ] + + if log_transformed: + cmd.append("--log_transformed") + if group_by: + cmd.extend(["--group_by", group_by]) + if reduction: + cmd.extend(["--reduction", reduction]) + if gene_set_file: + cmd.extend(["--gene_set_file", str(gene_set_file)]) + cmd.extend(["--gene_set_name", gene_set_name]) + + command_executed = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + cwd=temp_dir, + ) + stdout = result.stdout + stderr = result.stderr + except subprocess.CalledProcessError as e: + # 4. Error Handling + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": f"scFeatures execution failed with return code {e.returncode}", + } + + # 5. Structured Result Return + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_rds)], + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scfeatures/app/bioconductor-scfeatures_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scfeatures/app/bioconductor-scfeatures_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..225fbe57eaae417b7a3c97ecae2bc64839c54d84 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scfeatures/app/bioconductor-scfeatures_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-scfeatures/app/bioconductor-scfeatures_server.py') +SERVER_NAME = 'biosci_bioconductor_scfeatures' + + +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-scfeatures/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scfeatures/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scfeatures/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scfeatures/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scfeatures/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..3a374dfaeba8ef4b7b99f13fbe7a562d00865cdd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scfeatures/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-scfeatures: + build: . + image: mcp-bioconductor-scfeatures:latest + container_name: mcp-bioconductor-scfeatures + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-scfeatures + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-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-scfeatures/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scfeatures/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2560d6362940e0407d694c41ddd5b91ef2ae71bf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scfeatures/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-scfeatures + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scfeatures/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scfeatures/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scfeatures/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scider/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scider/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e46a957702f3848c6506b86567b32db307d5f4d9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scider/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-scider via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scider -y && conda clean -a + +# 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-scider_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-scider_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-scider_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scider/app/bioconductor-scider_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scider/app/bioconductor-scider_server.py new file mode 100644 index 0000000000000000000000000000000000000000..60c8a7734bc57a8b48d1237b09ddec16cf0f4364 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scider/app/bioconductor-scider_server.py @@ -0,0 +1,465 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Literal, Optional + +# It is assumed that the mcp package is installed and its decorator is available. +# from mcp import tool as mcp_tool +# For the purpose of this example, we will use a dummy decorator. +class mcp: + def tool(func): + return func + +TEST_USE_METHODS = Literal[ + "wilcox", "bimod", "roc", "t", "negbinom", "poisson", "LR", "MAST", "DESeq2" +] + +def _execute_r_script(r_script_content: str, command_name: str) -> dict: + """ + A helper function to execute an R script using a temporary file. + + Args: + r_script_content: A string containing the R code to execute. + command_name: The name of the scider function being called, for error reporting. + + Returns: + A dictionary containing the execution results. + """ + try: + with tempfile.NamedTemporaryFile( + mode="w", suffix=".R", delete=False + ) as r_script_file: + r_script_path = Path(r_script_file.name) + r_script_file.write(r_script_content) + + command = ["Rscript", str(r_script_path)] + process = subprocess.run( + command, capture_output=True, text=True, check=True + ) + + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + } + except FileNotFoundError: + return { + "command_executed": " ".join(command) if 'command' in locals() else "Rscript not found", + "stdout": "", + "stderr": "Rscript not found. Please ensure R and Rscript are in your system's PATH.", + "error": "Prerequisite not met." + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed for {command_name}.", + "return_code": e.returncode, + } + finally: + if "r_script_path" in locals() and r_script_path.exists(): + r_script_path.unlink() + + +@mcp.tool +def recluster( + input_rds: Path, + output_rds: Path, + recluster_method: Literal["Default", "SNN", "hclust"] = "Default", + resolution: float = 0.5, + num_pc: int = 10, +): + """ + Re-clusters a Seurat object using methods from the scider package. + + Args: + input_rds: Path to the input Seurat object saved as an RDS file. + output_rds: Path to save the re-clustered Seurat object as an RDS file. + recluster_method: Method to use for reclustering. + resolution: Resolution parameter for clustering. + num_pc: Number of principal components to use. + """ + if not input_rds.is_file(): + raise FileNotFoundError(f"Input file not found: {input_rds}") + + output_rds.parent.mkdir(parents=True, exist_ok=True) + + r_script = f""" + library(scider) + library(Seurat) + + seurat_object <- readRDS("{input_rds.resolve()}") + + updated_object <- recluster( + object = seurat_object, + recluster_method = "{recluster_method}", + resolution = {resolution}, + num_pc = {num_pc} + ) + + saveRDS(updated_object, file = "{output_rds.resolve()}") + print("Reclustering completed successfully.") + """ + + result = _execute_r_script(r_script, "recluster") + if "error" not in result: + result["output_files"] = [str(output_rds.resolve())] + return result + + +@mcp.tool +def find_isc( + input_rds: Path, + output_rds: Path, + species: Literal["human", "mouse"] = "human", + tissue: str = "Default", + isc_genes_default: str = "Default", + isc_genes_user: Optional[Path] = None, + isc_method: Literal["Default", "Average"] = "Default", + isc_threshold: float = 0.5, + assay: str = "RNA", + slot: str = "data", +): + """ + Calculates the In-Situ Co-expression (ISC) score for a Seurat object. + + Args: + input_rds: Path to the input Seurat object saved as an RDS file. + output_rds: Path to save the updated Seurat object as an RDS file. + species: Species of the sample ('human' or 'mouse'). + tissue: Tissue type for default gene lists. + isc_genes_default: Default ISC gene list to use. + isc_genes_user: Path to a file with a user-provided list of ISC genes. + isc_method: Method for ISC calculation. + isc_threshold: Threshold for ISC score. + assay: Assay to use from the Seurat object. + slot: Slot to use from the assay. + """ + if not input_rds.is_file(): + raise FileNotFoundError(f"Input file not found: {input_rds}") + if isc_genes_user and not isc_genes_user.is_file(): + raise FileNotFoundError(f"User ISC genes file not found: {isc_genes_user}") + + output_rds.parent.mkdir(parents=True, exist_ok=True) + + isc_genes_user_r = f"'{isc_genes_user.resolve()}'" if isc_genes_user else "NULL" + + r_script = f""" + library(scider) + library(Seurat) + + seurat_object <- readRDS("{input_rds.resolve()}") + + updated_object <- findISC( + object = seurat_object, + species = "{species}", + tissue = "{tissue}", + ISC_genes_default = "{isc_genes_default}", + ISC_genes_user = {isc_genes_user_r}, + ISC_method = "{isc_method}", + ISC_threshold = {isc_threshold}, + assay = "{assay}", + slot = "{slot}" + ) + + saveRDS(updated_object, file = "{output_rds.resolve()}") + print("ISC calculation completed successfully.") + """ + + result = _execute_r_script(r_script, "findISC") + if "error" not in result: + result["output_files"] = [str(output_rds.resolve())] + return result + + +@mcp.tool +def find_de_genes( + input_rds: Path, + output_rds: Path, + logfc_threshold: float = 0.25, + test_use: TEST_USE_METHODS = "wilcox", + min_pct: float = 0.1, + min_diff_pct: Optional[float] = None, + only_pos: bool = False, + max_cells_per_ident: Optional[int] = None, + random_seed: int = 1, + min_cells_group: int = 3, + pseudocount_use: int = 1, + verbose: bool = True, + assay: str = "RNA", + slot: str = "data", +): + """ + Finds differentially expressed (DE) genes between cell clusters. + + Args: + input_rds: Path to the input Seurat object saved as an RDS file. + output_rds: Path to save the updated Seurat object as an RDS file. + logfc_threshold: Log-fold change threshold. + test_use: Statistical test to use. + min_pct: Minimum percentage of cells expressing the gene in either group. + min_diff_pct: Minimum percentage difference between the two groups. Defaults to -Inf. + only_pos: Only return positive markers. + max_cells_per_ident: Max cells per identity to subsample. Defaults to Inf. + random_seed: Random seed for reproducibility. + min_cells_group: Minimum number of cells in a group. + pseudocount_use: Pseudocount to add to averaged expression values. + verbose: Print progress and informational messages. + assay: Assay to use from the Seurat object. + slot: Slot to use from the assay. + """ + if not input_rds.is_file(): + raise FileNotFoundError(f"Input file not found: {input_rds}") + + output_rds.parent.mkdir(parents=True, exist_ok=True) + + min_diff_pct_r = str(min_diff_pct) if min_diff_pct is not None else "-Inf" + max_cells_per_ident_r = ( + str(max_cells_per_ident) if max_cells_per_ident is not None else "Inf" + ) + + r_script = f""" + library(scider) + library(Seurat) + + seurat_object <- readRDS("{input_rds.resolve()}") + + updated_object <- findDEgenes( + object = seurat_object, + logfc.threshold = {logfc_threshold}, + test.use = "{test_use}", + min.pct = {min_pct}, + min.diff.pct = {min_diff_pct_r}, + only.pos = {str(only_pos).upper()}, + max.cells.per.ident = {max_cells_per_ident_r}, + random.seed = {random_seed}, + min.cells.group = {min_cells_group}, + pseudocount.use = {pseudocount_use}, + verbose = {str(verbose).upper()}, + assay = "{assay}", + slot = "{slot}" + ) + + saveRDS(updated_object, file = "{output_rds.resolve()}") + print("DE gene analysis completed successfully.") + """ + + result = _execute_r_script(r_script, "findDEgenes") + if "error" not in result: + result["output_files"] = [str(output_rds.resolve())] + return result + + +@mcp.tool +def find_dr_genes( + input_rds: Path, + output_rds: Path, + logfc_threshold: float = 0.25, + test_use: TEST_USE_METHODS = "wilcox", + min_pct: float = 0.1, + min_diff_pct: Optional[float] = None, + only_pos: bool = False, + max_cells_per_ident: Optional[int] = None, + random_seed: int = 1, + min_cells_group: int = 3, + pseudocount_use: int = 1, + verbose: bool = True, + assay: str = "RNA", + slot: str = "data", +): + """ + Finds differentially regulated (DR) genes between cell clusters. + + Args: + input_rds: Path to the input Seurat object saved as an RDS file. + output_rds: Path to save the updated Seurat object as an RDS file. + logfc_threshold: Log-fold change threshold. + test_use: Statistical test to use. + min_pct: Minimum percentage of cells expressing the gene in either group. + min_diff_pct: Minimum percentage difference between the two groups. Defaults to -Inf. + only_pos: Only return positive markers. + max_cells_per_ident: Max cells per identity to subsample. Defaults to Inf. + random_seed: Random seed for reproducibility. + min_cells_group: Minimum number of cells in a group. + pseudocount_use: Pseudocount to add to averaged expression values. + verbose: Print progress and informational messages. + assay: Assay to use from the Seurat object. + slot: Slot to use from the assay. + """ + if not input_rds.is_file(): + raise FileNotFoundError(f"Input file not found: {input_rds}") + + output_rds.parent.mkdir(parents=True, exist_ok=True) + + min_diff_pct_r = str(min_diff_pct) if min_diff_pct is not None else "-Inf" + max_cells_per_ident_r = ( + str(max_cells_per_ident) if max_cells_per_ident is not None else "Inf" + ) + + r_script = f""" + library(scider) + library(Seurat) + + seurat_object <- readRDS("{input_rds.resolve()}") + + updated_object <- findDRgenes( + object = seurat_object, + logfc.threshold = {logfc_threshold}, + test.use = "{test_use}", + min.pct = {min_pct}, + min.diff.pct = {min_diff_pct_r}, + only.pos = {str(only_pos).upper()}, + max.cells.per.ident = {max_cells_per_ident_r}, + random.seed = {random_seed}, + min.cells.group = {min_cells_group}, + pseudocount.use = {pseudocount_use}, + verbose = {str(verbose).upper()}, + assay = "{assay}", + slot = "{slot}" + ) + + saveRDS(updated_object, file = "{output_rds.resolve()}") + print("DR gene analysis completed successfully.") + """ + + result = _execute_r_script(r_script, "findDRgenes") + if "error" not in result: + result["output_files"] = [str(output_rds.resolve())] + return result + + +@mcp.tool +def run_scider( + input_rds: Path, + output_dir: Path, + project: str = "scider", + method: Literal["DE", "DR", "ISC"] = "DE", + de_method: TEST_USE_METHODS = "wilcox", + dr_method: TEST_USE_METHODS = "wilcox", + logfc_threshold: float = 0.25, + test_use: TEST_USE_METHODS = "wilcox", + min_pct: float = 0.1, + min_diff_pct: Optional[float] = None, + return_thresh: float = 0.01, + only_pos: bool = False, + max_cells_per_ident: Optional[int] = None, + random_seed: int = 1, + min_cells_group: int = 3, + pseudocount_use: int = 1, + verbose: bool = True, + assay: str = "RNA", + slot: str = "data", + isc_method: Literal["Default", "Average"] = "Default", + isc_threshold: float = 0.5, + recluster_method: Literal["Default", "SNN", "hclust"] = "Default", + resolution: float = 0.5, + num_pc: int = 10, + species: Literal["human", "mouse"] = "human", + tissue: str = "Default", + isc_genes_default: str = "Default", + isc_genes_user: Optional[Path] = None, + marker_genes_default: str = "Default", + marker_genes_user: Optional[Path] = None, +): + """ + Run the main scider pipeline for cell type identification. + + Args: + input_rds: Path to the input Seurat object saved as an RDS file. + output_dir: Directory to save the output files. + project: Name for the project. + method: Main analysis method to run ('DE', 'DR', or 'ISC'). + de_method: Test to use for DE analysis. + dr_method: Test to use for DR analysis. + logfc_threshold: Log-fold change threshold. + test_use: Statistical test to use (often same as de_method). + min_pct: Minimum percentage of cells expressing a gene. + min_diff_pct: Minimum percentage difference. Defaults to -Inf. + return_thresh: P-value threshold for returning genes. + only_pos: Only return positive markers. + max_cells_per_ident: Max cells to subsample. Defaults to Inf. + random_seed: Random seed for reproducibility. + min_cells_group: Minimum number of cells in a group. + pseudocount_use: Pseudocount for expression averaging. + verbose: Print progress messages. + assay: Assay to use from the Seurat object. + slot: Slot to use from the assay. + isc_method: Method for ISC calculation. + isc_threshold: Threshold for ISC score. + recluster_method: Method for reclustering. + resolution: Resolution for clustering. + num_pc: Number of principal components. + species: Species of the sample. + tissue: Tissue type for default gene lists. + isc_genes_default: Default ISC gene list. + isc_genes_user: Path to user-provided ISC genes. + marker_genes_default: Default marker gene list. + marker_genes_user: Path to user-provided marker genes. + """ + if not input_rds.is_file(): + raise FileNotFoundError(f"Input file not found: {input_rds}") + if isc_genes_user and not isc_genes_user.is_file(): + raise FileNotFoundError(f"User ISC genes file not found: {isc_genes_user}") + if marker_genes_user and not marker_genes_user.is_file(): + raise FileNotFoundError(f"User marker genes file not found: {marker_genes_user}") + + output_dir.mkdir(parents=True, exist_ok=True) + + min_diff_pct_r = str(min_diff_pct) if min_diff_pct is not None else "-Inf" + max_cells_per_ident_r = ( + str(max_cells_per_ident) if max_cells_per_ident is not None else "Inf" + ) + isc_genes_user_r = f"'{isc_genes_user.resolve()}'" if isc_genes_user else "NULL" + marker_genes_user_r = ( + f"'{marker_genes_user.resolve()}'" if marker_genes_user else "NULL" + ) + + r_script = f""" + library(scider) + library(Seurat) + + seurat_object <- readRDS("{input_rds.resolve()}") + + runScider( + object = seurat_object, + method = "{method}", + de.method = "{de_method}", + dr.method = "{dr_method}", + logfc.threshold = {logfc_threshold}, + test.use = "{test_use}", + min.pct = {min_pct}, + min.diff.pct = {min_diff_pct_r}, + return.thresh = {return_thresh}, + only.pos = {str(only_pos).upper()}, + max.cells.per.ident = {max_cells_per_ident_r}, + random.seed = {random_seed}, + min.cells.group = {min_cells_group}, + pseudocount.use = {pseudocount_use}, + verbose = {str(verbose).upper()}, + assay = "{assay}", + slot = "{slot}", + ISC_method = "{isc_method}", + ISC_threshold = {isc_threshold}, + recluster_method = "{recluster_method}", + resolution = {resolution}, + num_pc = {num_pc}, + species = "{species}", + tissue = "{tissue}", + ISC_genes_default = "{isc_genes_default}", + ISC_genes_user = {isc_genes_user_r}, + marker_genes_default = "{marker_genes_default}", + marker_genes_user = {marker_genes_user_r}, + output_dir = "{output_dir.resolve()}", + project = "{project}" + ) + + print("scider analysis completed successfully.") + """ + + result = _execute_r_script(r_script, "runScider") + if "error" not in result: + result["output_files"] = [ + str(f) for f in output_dir.resolve().glob(f"{project}*") + ] + return result \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scider/app/bioconductor-scider_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scider/app/bioconductor-scider_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..55294290adfe64b2e63c750edb59f7ee1df8c7d4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scider/app/bioconductor-scider_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-scider/app/bioconductor-scider_server.py') +SERVER_NAME = 'biosci_bioconductor_scider' + + +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-scider/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scider/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scider/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scider/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scider/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..1b88e208285fa5607f1149c009f5c374d3dafc66 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scider/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-scider: + build: . + image: mcp-bioconductor-scider:latest + container_name: mcp-bioconductor-scider + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-scider + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-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-scider/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scider/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4510862e3080f9e7b6678fbf28cb472d328a3b90 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scider/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-scider + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scider/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scider/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scider/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scqtltools/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scqtltools/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..243ff88d4f23396752214f09fd8e70673e3bf694 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scqtltools/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-scqtltools via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scqtltools -y && conda clean -a + +# 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-scqtltools_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-scqtltools_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-scqtltools_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scqtltools/app/bioconductor-scqtltools_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scqtltools/app/bioconductor-scqtltools_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4e5fcb24aa3ad8c815823e9e21cbf01eff878a74 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scqtltools/app/bioconductor-scqtltools_server.py @@ -0,0 +1,179 @@ +import subprocess +import logging +import shlex +from pathlib import Path +from typing import Optional, List + +# MCP decorator is used to define the tool. +# It is assumed that the 'mcp' library is available in the execution environment. +# from some_mcp_library import mcp + +logger = logging.getLogger(__name__) + +@mcp.tool() +def run_scqtl_pipeline( + sce_file: Path, + genotype_file: Path, + gene_info_file: Path, + output_dir: Path, + sample_id: str, + cell_type_id: str, + covariate_file: Optional[Path] = None, + cis_dist: int = 1000000, + n_cores: int = 1, + n_perm: int = 1000, + fdr_threshold: float = 0.05, + min_samps_per_cell_type: int = 10, + min_cells_per_samp: int = 5, + min_counts_per_gene: int = 10, + min_genes_per_cell: int = 100, + run_interaction: bool = False, + interaction_cov: Optional[str] = None, + run_tensorqtl: bool = False, + tensorqtl_mode: str = "cis", + use_long_format: bool = False, + verbose: bool = True, +) -> dict: + """ + Runs the scQTL-Tools pipeline for single-cell eQTL analysis. + + This tool identifies expression quantitative trait loci (eQTLs) in single-cell + RNA-seq data by associating genetic variants with gene expression levels. + It wraps the 'scqtl-pipeline' command-line tool. + + Args: + sce_file: Path to the SingleCellExperiment object file (.rds). + genotype_file: Path to the genotype file in VCF format. + gene_info_file: Path to the gene information file in GTF format. + output_dir: Path to the directory where output files will be saved. + sample_id: The identifier for the sample being analyzed. + cell_type_id: The identifier for the cell type being analyzed. + covariate_file: Optional path to a file containing covariates. + cis_dist: The maximum distance (in bp) between a SNP and a gene to be considered a cis-eQTL. + n_cores: Number of CPU cores to use for parallel processing. + n_perm: Number of permutations to perform for calculating empirical p-values. + fdr_threshold: The False Discovery Rate threshold for calling significant eQTLs. + min_samps_per_cell_type: Minimum number of samples required per cell type. + min_cells_per_samp: Minimum number of cells required per sample. + min_counts_per_gene: Minimum total counts required for a gene to be included. + min_genes_per_cell: Minimum number of expressed genes required for a cell to be included. + run_interaction: If True, perform an interaction analysis. + interaction_cov: The name of the covariate to use for interaction analysis. Required if run_interaction is True. + run_tensorqtl: If True, use tensorQTL for the analysis. + tensorqtl_mode: The mode for tensorQTL analysis ('cis', 'cis_nominal', 'cis_independent'). + use_long_format: If True, output results in a long format. + verbose: If True, enable verbose logging. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not sce_file.is_file(): + raise FileNotFoundError(f"Input SCE file not found: {sce_file}") + if not genotype_file.is_file(): + raise FileNotFoundError(f"Input genotype file not found: {genotype_file}") + if not gene_info_file.is_file(): + raise FileNotFoundError(f"Input gene info file not found: {gene_info_file}") + if covariate_file and not covariate_file.is_file(): + raise FileNotFoundError(f"Input covariate file not found: {covariate_file}") + + if n_cores <= 0: + raise ValueError("n_cores must be a positive integer.") + if n_perm < 0: + raise ValueError("n_perm must be a non-negative integer.") + if not (0.0 < fdr_threshold <= 1.0): + raise ValueError("fdr_threshold must be between 0 and 1.") + + if run_interaction and not interaction_cov: + raise ValueError("interaction_cov must be provided when run_interaction is True.") + + allowed_tensorqtl_modes = ["cis", "cis_nominal", "cis_independent"] + if tensorqtl_mode not in allowed_tensorqtl_modes: + raise ValueError(f"tensorqtl_mode must be one of {allowed_tensorqtl_modes}, but got '{tensorqtl_mode}'.") + + # --- File Path Handling --- + try: + output_dir.mkdir(parents=True, exist_ok=True) + except OSError as e: + logger.error(f"Failed to create output directory {output_dir}: {e}") + raise + + # --- Command Construction --- + base_cmd = "scqtl-pipeline" + cmd = [base_cmd] + + # Add arguments, assuming CLI flags use hyphens (e.g., --sce-file) + cmd.extend(["--sce-file", str(sce_file)]) + cmd.extend(["--genotype-file", str(genotype_file)]) + cmd.extend(["--gene-info-file", str(gene_info_file)]) + cmd.extend(["--output-dir", str(output_dir)]) + cmd.extend(["--sample-id", sample_id]) + cmd.extend(["--cell-type-id", cell_type_id]) + + if covariate_file: + cmd.extend(["--covariate-file", str(covariate_file)]) + + cmd.extend(["--cis-dist", str(cis_dist)]) + cmd.extend(["--n-cores", str(n_cores)]) + cmd.extend(["--n-perm", str(n_perm)]) + cmd.extend(["--fdr-threshold", str(fdr_threshold)]) + cmd.extend(["--min-samps-per-cell-type", str(min_samps_per_cell_type)]) + cmd.extend(["--min-cells-per-samp", str(min_cells_per_samp)]) + cmd.extend(["--min-counts-per-gene", str(min_counts_per_gene)]) + cmd.extend(["--min-genes-per-cell", str(min_genes_per_cell)]) + + if run_interaction: + cmd.append("--run-interaction") + if interaction_cov: + cmd.extend(["--interaction-cov", interaction_cov]) + + if run_tensorqtl: + cmd.append("--run-tensorqtl") + cmd.extend(["--tensorqtl-mode", tensorqtl_mode]) + + if use_long_format: + cmd.append("--use-long-format") + + if verbose: + cmd.append("--verbose") + + command_executed = shlex.join(cmd) + logger.info(f"Executing command: {command_executed}") + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + output_files = [str(p) for p in output_dir.glob("**/*") if p.is_file()] + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + + except FileNotFoundError: + error_message = f"Error: Command '{base_cmd}' not found. Please ensure 'scqtl-pipeline' is installed and in your system's PATH." + logger.error(error_message) + return { + "command_executed": command_executed, + "stdout": "", + "stderr": error_message, + "output_files": [], + } + except subprocess.CalledProcessError as e: + logger.error(f"Command failed with exit code {e.returncode}") + logger.error(f"stdout: {e.stdout}") + logger.error(f"stderr: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scqtltools/app/bioconductor-scqtltools_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scqtltools/app/bioconductor-scqtltools_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..98158f619bd09295905599680680ff6c7fb199b7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scqtltools/app/bioconductor-scqtltools_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-scqtltools/app/bioconductor-scqtltools_server.py') +SERVER_NAME = 'biosci_bioconductor_scqtltools' + + +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-scqtltools/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scqtltools/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scqtltools/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scqtltools/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scqtltools/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..13fd5a7ea3d8215981584b18f3133ba1dadc2894 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scqtltools/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-scqtltools: + build: . + image: mcp-bioconductor-scqtltools:latest + container_name: mcp-bioconductor-scqtltools + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-scqtltools + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-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-scqtltools/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scqtltools/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..650dd7d782c43ae9bc45b88682db3970151ed78c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scqtltools/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-scqtltools + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scqtltools/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scqtltools/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scqtltools/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scran/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scran/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ee42b24907b2269d79cf963fd9088464c06b5048 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scran/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-scran via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scran -y && conda clean -a + +# 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-scran_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-scran_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-scran_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scran/app/bioconductor-scran_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scran/app/bioconductor-scran_server.py new file mode 100644 index 0000000000000000000000000000000000000000..bc1a56637f82552584395a44766d455696e27170 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scran/app/bioconductor-scran_server.py @@ -0,0 +1,107 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# MCP decorator is omitted as per instructions. +# @mcp.tool() + +def scran_normalize( + input_sce_rds: Path, + output_sce_rds: Path, + clusters_csv: Optional[Path] = None, + min_mean: float = 0.1, + bpparam_workers: int = 1, +) -> dict: + """ + Performs normalization of single-cell RNA-seq data using scran's deconvolution method. + + This tool serves as a wrapper for a hypothetical R script that utilizes the + 'scran' Bioconductor package. 'scran' itself is an R library without a native + command-line interface. This function assumes an R script ('run_scran.R') + exists that can take command-line arguments to perform normalization. + + Args: + input_sce_rds (Path): Path to the input SingleCellExperiment object saved as an RDS file. + This object should contain the raw count matrix. + output_sce_rds (Path): Path to save the output SingleCellExperiment object (in RDS format) + with the calculated size factors added. + clusters_csv (Optional[Path]): Path to a CSV file containing cell cluster assignments. + If provided, normalization is performed per cluster. + The CSV should have two columns: cell_barcode, cluster_id. + min_mean (float): The minimum mean expression for a gene to be used for normalization. + Corresponds to the 'min.mean' parameter in scran's computeSumFactors. + Defaults to 0.1. + bpparam_workers (int): Number of worker processes to use for parallel computation. + Defaults to 1 (no parallelization). + + Returns: + dict: A dictionary containing the executed command, stdout, stderr, and a list + of output files. + """ + # --- Input Validation --- + if not input_sce_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {input_sce_rds}") + if clusters_csv and not clusters_csv.is_file(): + raise FileNotFoundError(f"Clusters CSV file not found: {clusters_csv}") + if min_mean < 0: + raise ValueError("min_mean must be a non-negative number.") + if bpparam_workers < 1: + raise ValueError("bpparam_workers must be at least 1.") + + # --- Command Construction --- + # This assumes a hypothetical R script 'run_scran.R' that we have created + # to expose scran functionality to the command line. + cmd = [ + "Rscript", + "run_scran.R", + "normalize", + "--input", + str(input_sce_rds), + "--output", + str(output_sce_rds), + "--min-mean", + str(min_mean), + "--workers", + str(bpparam_workers), + ] + + if clusters_csv: + cmd.extend(["--clusters", str(clusters_csv)]) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + try: + # In a real scenario, the R script would need to be in the PATH or specified with its full path. + # For this example, we assume it's available. + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + stdout = result.stdout + stderr = result.stderr + except FileNotFoundError: + # This error would be raised if 'Rscript' or 'run_scran.R' is not found. + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'Rscript' or the wrapper 'run_scran.R' not found. Please ensure R and the necessary wrapper script are in the system's PATH.", + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + + # --- Return Structured Output --- + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_sce_rds)], + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scran/app/bioconductor-scran_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scran/app/bioconductor-scran_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..be8bbebb15055e1478bdaaa0e56f9152fac640ad --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scran/app/bioconductor-scran_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-scran/app/bioconductor-scran_server.py') +SERVER_NAME = 'biosci_bioconductor_scran' + + +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-scran/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scran/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scran/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scran/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scran/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..40666027b239fd5d5871e3fafad5cd1946229c73 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scran/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-scran: + build: . + image: mcp-bioconductor-scran:latest + container_name: mcp-bioconductor-scran + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-scran + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-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-scran/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scran/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d6b2da108b267b289f9f7e6f439b9e905e015c79 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scran/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-scran + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scran/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scran/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scran/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scrnaseqapp/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scrnaseqapp/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5ba94c43f0b5e6bb4f3518febcfc266f87f27ab9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scrnaseqapp/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-scrnaseqapp via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scrnaseqapp -y && conda clean -a + +# 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-scrnaseqapp_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-scrnaseqapp_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-scrnaseqapp_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scrnaseqapp/app/bioconductor-scrnaseqapp_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scrnaseqapp/app/bioconductor-scrnaseqapp_server.py new file mode 100644 index 0000000000000000000000000000000000000000..83aa42e5f88b0bc5ff3a931be4f4dcab7a4284ff --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scrnaseqapp/app/bioconductor-scrnaseqapp_server.py @@ -0,0 +1,229 @@ +from pathlib import Path +import subprocess +import tempfile +from typing import Optional, List + +@mcp.tool() +def scrnaseqapp_make_shiny_files( + input_rds: str, + output_dir: str, + prefix: str, + assay: str = "RNA", + slot: str = "data", + dimreds: str = "umap,tsne", + metadata_columns: Optional[str] = None, +): + """ + Prepare single-cell data (Seurat or SingleCellExperiment) for the scRNAseqApp. + This function converts an RDS object into the specific file structure required by the Shiny app. + + Args: + input_rds: Path to the input .rds file containing a Seurat or SingleCellExperiment object. + output_dir: Directory where the prepared shiny files will be saved. + prefix: Prefix for the output files (e.g., dataset name). + assay: The assay to use from the object (default: 'RNA'). + slot: The slot to use (default: 'data'). + dimreds: Comma-separated list of dimensionality reductions to include (e.g., 'umap,tsne'). + metadata_columns: Optional comma-separated list of metadata columns to include. + """ + input_path = Path(input_rds) + output_path = Path(output_dir) + + if not input_path.exists(): + return {"error": f"Input file not found: {input_rds}"} + + output_path.mkdir(parents=True, exist_ok=True) + + # Prepare R vectors + dimreds_vec = ", ".join([f"'{d.strip()}'" for d in dimreds.split(",")]) + meta_cmd = "" + if metadata_columns: + meta_vec = ", ".join([f"'{m.strip()}'" for m in metadata_columns.split(",")]) + meta_cmd = f", metadata = c({meta_vec})" + + r_script = f""" + library(scRNAseqApp) + library(Seurat) + library(SingleCellExperiment) + + obj <- readRDS('{input_path.absolute()}') + makeShinyFiles( + obj = obj, + filePrefix = '{prefix}', + shinyDir = '{output_path.absolute()}', + assay = '{assay}', + slot = '{slot}', + dimreds = c({dimreds_vec}) + {meta_cmd} + ) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e \"{r_script.strip()}\"", + "stdout": result.stdout, + "stderr": result.stderr, + "output_directory": str(output_path.absolute()), + "status": "Success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript -e \"{r_script.strip()}\"", + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to prepare shiny files." + } + +@mcp.tool() +def scrnaseqapp_launch( + storage_path: str, + host: str = "0.0.0.0", + port: int = 3838, + launch_browser: bool = False +): + """ + Launch the scRNAseqApp Shiny application to visualize prepared datasets. + + Args: + storage_path: Path to the directory containing the prepared datasets (created by make_shiny_files). + host: The IPv4 address that the application should listen on. + port: The TCP port that the application should listen on. + launch_browser: Whether to attempt to launch a web browser automatically. + """ + data_path = Path(storage_path) + if not data_path.exists(): + return {"error": f"Storage path does not exist: {storage_path}"} + + # Note: This will block the process as it starts a web server. + # In an MCP context, this is usually used to generate the command or start a background service. + r_script = f""" + library(scRNAseqApp) + scRNAseqApp( + storagePath = '{data_path.absolute()}', + options = list(host = '{host}', port = {port}, launch.browser = {str(launch_browser).upper()}) + ) + """ + + cmd = ["Rscript", "-e", r_script] + + return { + "info": "To run the app, execute the following command in your terminal. Note that it will start a persistent web server.", + "command_executed": " ".join(cmd), + "access_url": f"http://{host}:{port}" + } + +@mcp.tool() +def scrnaseqapp_create_config( + output_config_path: str, + data_dir: str, + app_title: str = "scRNAseqApp Visualization", + description: str = "Interactive single-cell data analysis" +): + """ + Create a configuration file for the scRNAseqApp to manage multiple datasets and app settings. + + Args: + output_config_path: Path where the config.json or config.R file should be saved. + data_dir: Path to the directory where datasets are stored. + app_title: Title to display in the Shiny app header. + description: Brief description of the app content. + """ + config_path = Path(output_config_path) + data_path = Path(data_dir) + + r_script = f""" + library(scRNAseqApp) + # This package uses a specific internal structure for configs + # We simulate the creation of a basic configuration setup + dir.create('{data_path.absolute()}', showWarnings = FALSE, recursive = TRUE) + + # Example of setting up the app directory structure + # The app expects a specific folder structure for multi-dataset support + message('Initializing app configuration at {config_path.absolute()}') + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e \"{r_script.strip()}\"", + "stdout": result.stdout, + "stderr": result.stderr, + "status": "Configuration directory initialized" + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to create configuration.", + "stderr": e.stderr + } + +@mcp.tool() +def scrnaseqapp_add_user( + db_path: str, + username: str, + password: str, + permissions: str = "admin" +): + """ + Add a user to the scRNAseqApp user management system (SQLite database). + + Args: + db_path: Path to the SQLite database file used by shinymanager. + username: Username for the new user. + password: Password for the new user (will be encrypted using scrypt). + permissions: User permissions (e.g., 'admin', 'standard'). + """ + db_file = Path(db_path) + + r_script = f""" + library(shinymanager) + library(scrypt) + + # Create or update the credentials database + credentials <- data.frame( + user = '{username}', + password = '{password}', + admin = {'TRUE' if permissions == 'admin' else 'FALSE'}, + stringsAsFactors = FALSE + ) + + if (!file.exists('{db_file.absolute()}')) {{ + create_db( + credentials_data = credentials, + sqlite_path = '{db_file.absolute()}', + passphrase = 'default_passphrase' + ) + }} else {{ + # Logic to append user would go here if supported by the specific app implementation + message('Database already exists. Manual update required or use shinymanager functions.') + }} + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "Rscript execution for user management", + "stdout": result.stdout, + "stderr": result.stderr, + "db_location": str(db_file.absolute()) + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to add user to database.", + "stderr": e.stderr + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scrnaseqapp/app/bioconductor-scrnaseqapp_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scrnaseqapp/app/bioconductor-scrnaseqapp_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..43a7ab639febd94c75c09ed17c015f4f51bf2f88 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scrnaseqapp/app/bioconductor-scrnaseqapp_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-scrnaseqapp/app/bioconductor-scrnaseqapp_server.py') +SERVER_NAME = 'biosci_bioconductor_scrnaseqapp' + + +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-scrnaseqapp/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scrnaseqapp/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scrnaseqapp/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scrnaseqapp/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scrnaseqapp/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..9568328ffe51207bffb8b9d69f419fd5d17b555a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scrnaseqapp/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-scrnaseqapp: + build: . + image: mcp-bioconductor-scrnaseqapp:latest + container_name: mcp-bioconductor-scrnaseqapp + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-scrnaseqapp + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-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-scrnaseqapp/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scrnaseqapp/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e4f9f67eb95066fccd57bbcdf9b972e2100e5b07 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scrnaseqapp/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-scrnaseqapp + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scrnaseqapp/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scrnaseqapp/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scrnaseqapp/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sctreeviz/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sctreeviz/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..db3573a50eaad1021ad649a63e1b97a92c25f462 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sctreeviz/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-sctreeviz via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-sctreeviz -y && conda clean -a + +# 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-sctreeviz_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-sctreeviz_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-sctreeviz_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sctreeviz/app/bioconductor-sctreeviz_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sctreeviz/app/bioconductor-sctreeviz_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0a4e645265bc22e4ddb59df7a39b0c26e216fe82 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sctreeviz/app/bioconductor-sctreeviz_server.py @@ -0,0 +1,222 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any +import logging +import shlex + +# Set up logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# Mock mcp.tool decorator for standalone execution +def mcp_tool_mock(): + def decorator(func): + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + return wrapper + return decorator + +mcp = type('mcp', (), {'tool': mcp_tool_mock})() + + +@mcp.tool() +def generate_cluster_tree( + sce_rds: Path, + output_plot: Path, + cluster_steps: str = "2,4,6,8", + assay_name: str = "logcounts", + dimred_name: str = "PCA", + cluster_prefix: str = "sctv_cluster_", +) -> Dict[str, Any]: + """ + Generates a cluster tree visualization from a SingleCellExperiment object. + + This tool uses the scTreeViz R package to perform clustering at multiple + resolutions and visualize the resulting hierarchy as a 'clustree' plot. + It requires a pre-processed SingleCellExperiment object saved as an .rds file, + which must contain a dimensionality reduction result (e.g., PCA). + + Args: + sce_rds: Path to the input SingleCellExperiment object saved as an RDS file. + This object must contain a dimensionality reduction result specified + by `dimred_name`. + output_plot: Path to save the output plot. The file extension (e.g., .png, + .pdf, .svg) determines the output format. + cluster_steps: A comma-separated string of integer 'steps' for the + `igraph::cluster_walktrap` algorithm, used to generate + clusters at different resolutions. + assay_name: The name of the assay in the SCE object to use for building the graph. + dimred_name: The name of the dimensionality reduction result in the SCE + object to use for building the SNN graph. + cluster_prefix: The prefix for the new cluster columns added to the + colData of the SCE object. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list + of output files. + """ + # 1. Input validation + if not sce_rds.is_file(): + raise FileNotFoundError(f"Input file not found: {sce_rds}") + + if not output_plot.parent.exists(): + logger.info(f"Output directory {output_plot.parent} does not exist. Creating it.") + output_plot.parent.mkdir(parents=True, exist_ok=True) + + try: + # Validate that cluster_steps contains comma-separated integers + [int(s.strip()) for s in cluster_steps.split(',')] + except ValueError: + raise ValueError("`cluster_steps` must be a comma-separated string of integers.") + + # 2. R script generation + r_script_content = f""" + # Load necessary libraries + if (!requireNamespace("scTreeViz", quietly = TRUE)) stop("Package scTreeViz not found.") + if (!requireNamespace("SingleCellExperiment", quietly = TRUE)) stop("Package SingleCellExperiment not found.") + if (!requireNamespace("scran", quietly = TRUE)) stop("Package scran not found.") + if (!requireNamespace("igraph", quietly = TRUE)) stop("Package igraph not found.") + if (!requireNamespace("ggplot2", quietly = TRUE)) stop("Package ggplot2 not found.") + + library(scTreeViz) + library(SingleCellExperiment) + library(scran) + library(igraph) + library(ggplot2) + + # --- Get arguments from command line --- + args <- commandArgs(trailingOnly=TRUE) + sce_rds_path <- args[1] + output_plot_path <- args[2] + cluster_steps_str <- args[3] + assay_name <- args[4] + dimred_name <- args[5] + cluster_prefix <- args[6] + + cat("--- scTreeViz Analysis Parameters ---\\n") + cat("Input SCE RDS: ", sce_rds_path, "\\n") + cat("Output Plot: ", output_plot_path, "\\n") + cat("Cluster Steps: ", cluster_steps_str, "\\n") + cat("Assay Name: ", assay_name, "\\n") + cat("DimRed Name: ", dimred_name, "\\n") + cat("Cluster Prefix: ", cluster_prefix, "\\n") + cat("-------------------------------------\\n\\n") + + # --- Main analysis --- + tryCatch({{ + # Read input SingleCellExperiment object + cat("Reading SCE object from:", sce_rds_path, "\\n") + sce <- readRDS(sce_rds_path) + + # Check for dimensionality reduction result + if (!dimred_name %in% reducedDimNames(sce)) {{ + stop(paste0("Dimensionality reduction '", dimred_name, "' not found in the SCE object.")) + }} + + # Build SNN graph + cat("Building SNN graph using '", dimred_name, "'...\\n") + g <- buildSNNGraph(sce, use.dimred=dimred_name, assay.type=assay_name) + + # Parse cluster steps + steps_vec <- as.integer(strsplit(cluster_steps_str, ",")[[1]]) + + # Perform clustering for each step value + cat("Performing clustering for steps:", paste(steps_vec, collapse=", "), "\\n") + for (s in steps_vec) {{ + set.seed(42) # for reproducibility + col_name <- paste0(cluster_prefix, "s", s) + clust <- igraph::cluster_walktrap(g, steps=s)$membership + sce[[col_name]] <- as.factor(clust) + }} + + # Get the names of the cluster columns we just created + clust_cols <- grep(paste0("^", cluster_prefix), colnames(colData(sce)), value = TRUE) + if (length(clust_cols) == 0) {{ + stop("No cluster columns were generated. Check cluster_prefix and clustering steps.") + }} + cat("Generated cluster columns:", paste(clust_cols, collapse=", "), "\\n") + + # Create the TreeViz object + cat("Creating TreeViz object...\\n") + sctv <- TreeViz(sce, colData_cols = clust_cols) + + # Generate the clustree plot + cat("Generating clustree plot...\\n") + p <- sctv_clustree(sctv, prefix = cluster_prefix) + + # Save the plot + cat("Saving plot to:", output_plot_path, "\\n") + ggsave(output_plot_path, plot = p, width = 10, height = 8, dpi = 300) + + cat("\\n--- Analysis successfully completed! ---\\n") + + }}, error = function(e) {{ + cat("Error during scTreeViz analysis:\\n") + message(e) + quit(status = 1) + }}) + """ + + # 3. Subprocess execution + command = [] + result_dict = { + "command_executed": "", + "stdout": "", + "stderr": "", + "output_files": [], + } + + 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 + + command = [ + "Rscript", + r_script_path, + str(sce_rds), + str(output_plot), + cluster_steps, + assay_name, + dimred_name, + cluster_prefix, + ] + + command_str = " ".join(shlex.quote(c) for c in command) + logger.info(f"Executing command: {command_str}") + result_dict["command_executed"] = command_str + + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + + result_dict["stdout"] = process.stdout + result_dict["stderr"] = process.stderr + if output_plot.exists(): + result_dict["output_files"].append(str(output_plot)) + + logger.info(f"Successfully generated cluster tree plot: {output_plot}") + + except FileNotFoundError: + error_msg = "Rscript not found. Please ensure R is installed and in your PATH." + logger.error(error_msg) + result_dict["stderr"] = error_msg + raise RuntimeError(error_msg) from None + except subprocess.CalledProcessError as e: + logger.error(f"Error executing scTreeViz R script.") + logger.error(f"Return code: {e.returncode}") + logger.error(f"Stdout: {e.stdout}") + logger.error(f"Stderr: {e.stderr}") + result_dict["stdout"] = e.stdout + result_dict["stderr"] = e.stderr + raise + finally: + # Clean up the temporary R script + if 'r_script_path' in locals() and Path(r_script_path).exists(): + Path(r_script_path).unlink() + + return result_dict \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sctreeviz/app/bioconductor-sctreeviz_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sctreeviz/app/bioconductor-sctreeviz_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..483e706c6c9ff0537d6f42c24ff831d3cea3659e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sctreeviz/app/bioconductor-sctreeviz_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-sctreeviz/app/bioconductor-sctreeviz_server.py') +SERVER_NAME = 'biosci_bioconductor_sctreeviz' + + +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-sctreeviz/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sctreeviz/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sctreeviz/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sctreeviz/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sctreeviz/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d2f1a306dafbdf96297b18b6841fa9e72e0aede1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sctreeviz/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-sctreeviz: + build: . + image: mcp-bioconductor-sctreeviz:latest + container_name: mcp-bioconductor-sctreeviz + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-sctreeviz + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-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-sctreeviz/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sctreeviz/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..15505792d6eebae17f827d895c90a82b765b845e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sctreeviz/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-sctreeviz + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sctreeviz/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sctreeviz/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sctreeviz/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scuttle/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scuttle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6ee53d55bd3a3c228d647c5517fa0f11641009fd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scuttle/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-scuttle via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scuttle -y && conda clean -a + +# 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-scuttle_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-scuttle_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-scuttle_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scuttle/app/bioconductor-scuttle_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scuttle/app/bioconductor-scuttle_server.py new file mode 100644 index 0000000000000000000000000000000000000000..21d810a8c5b16b334b531d6f864405712d83f988 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scuttle/app/bioconductor-scuttle_server.py @@ -0,0 +1,205 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional + +# Assume @mcp.tool is imported +# from mcp import tool as mcp_tool + +# This is a placeholder for the actual decorator as per instructions. +def mcp_tool_placeholder(*args, **kwargs): + def decorator(func): + return func + return decorator + +mcp = type("MCP", (), {"tool": mcp_tool_placeholder}) + + +@mcp.tool() +def normalize_counts( + counts_matrix: Path, + output_matrix: Path, + size_factors_file: Optional[Path] = None, + center_size_factors: bool = True, + log_transform: bool = True, + pseudo_count: float = 1.0, +): + """ + Performs scaling normalization on a count matrix using scuttle::normalizeCounts. + + This function can compute normalized expression values, optionally on the log-scale. + It serves as a versatile wrapper for one of scuttle's primary normalization functions. + + Args: + counts_matrix: Path to the input count matrix file in CSV format. + The first column should contain gene names, and the header should contain cell names. + output_matrix: Path to save the output normalized matrix in CSV format. + size_factors_file: Optional path to a single-column file containing size factors for each cell. + If not provided, library sizes are used as size factors. + center_size_factors: A boolean indicating whether to center the size factors to have a mean of 1. + log_transform: A boolean indicating whether to apply a log2-transformation to the normalized counts. + pseudo_count: A positive pseudo-count to be added to counts before log-transformation. + This is only used if log_transform is True. + """ + # Input validation + if not counts_matrix.is_file(): + raise FileNotFoundError(f"Input counts matrix not found at {counts_matrix}") + if log_transform and pseudo_count <= 0: + raise ValueError("pseudo_count must be a positive number when log_transform is True.") + + size_factors_r_arg = "NULL" + if size_factors_file: + if not size_factors_file.is_file(): + raise FileNotFoundError(f"Size factors file not found at {size_factors_file}") + size_factors_r_arg = f'"{size_factors_file.resolve()}"' + + # Convert Python bool to R's TRUE/FALSE strings + center_sf_r = "TRUE" if center_size_factors else "FALSE" + log_transform_r = "TRUE" if log_transform else "FALSE" + + r_script_content = f""" + library(scuttle) + library(SingleCellExperiment) + + # Read the counts matrix + counts <- as.matrix(read.csv("{counts_matrix.resolve()}", row.names=1, check.names=FALSE)) + sce <- SingleCellExperiment(assays = list(counts = counts)) + + # Handle size factors if provided + size_factors_path <- {size_factors_r_arg} + size_factors_arg <- NULL + if (!is.null(size_factors_path)) {{ + sf <- read.table(size_factors_path, header=FALSE) + size_factors_arg <- as.numeric(sf[,1]) + }} + + # Perform normalization + normalized_matrix <- normalizeCounts( + sce, + size.factors=size_factors_arg, + center.size.factors={center_sf_r}, + log={log_transform_r}, + pseudo.count={pseudo_count} + ) + + # Write the output + write.csv(normalized_matrix, file="{output_matrix.resolve()}", row.names=TRUE, quote=FALSE) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_script: + script_path = Path(tmp_script.name) + tmp_script.write(r_script_content) + + cmd = ["Rscript", str(script_path)] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_matrix)] + } + 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 + finally: + # Ensure temporary script is always cleaned up + if script_path.exists(): + script_path.unlink() + + +@mcp.tool() +def aggregate_across_cells( + counts_matrix: Path, + ids_file: Path, + output_aggregated_matrix: Path, + use_assay_type: str = "counts", +): + """ + Aggregates counts across cells for specified groups using scuttle::aggregateAcrossCells. + + This is useful for creating pseudo-bulk expression profiles from single-cell data. + + Args: + counts_matrix: Path to the input count matrix file in CSV format. + The first column should contain gene names, and the header should contain cell names. + ids_file: Path to a single-column file containing group IDs (e.g., cluster or sample IDs) for each cell. + The order of IDs must match the order of columns (cells) in the counts_matrix. + output_aggregated_matrix: Path to save the output aggregated matrix in CSV format. + use_assay_type: The name of the assay in the SingleCellExperiment object to use for aggregation. + Defaults to "counts". + """ + # Input validation + if not counts_matrix.is_file(): + raise FileNotFoundError(f"Input counts matrix not found at {counts_matrix}") + if not ids_file.is_file(): + raise FileNotFoundError(f"IDs file not found at {ids_file}") + + r_script_content = f""" + library(scuttle) + library(SingleCellExperiment) + + # Read the counts matrix + counts <- as.matrix(read.csv("{counts_matrix.resolve()}", row.names=1, check.names=FALSE)) + sce <- SingleCellExperiment(assays = list(counts = counts)) + + # Read the IDs + ids <- read.table("{ids_file.resolve()}", header=FALSE, stringsAsFactors=TRUE) + ids_vector <- ids[,1] + + # Check if dimensions match + if (length(ids_vector) != ncol(sce)) {{ + stop(paste0("Number of IDs (", length(ids_vector), ") does not match the number of cells (", ncol(sce), ") in the count matrix.")) + }} + + # Perform aggregation + aggregated_sce <- aggregateAcrossCells(sce, ids=ids_vector, use.assay.type="{use_assay_type}") + + # Write the output + # The output assay from aggregateAcrossCells is named 'counts' by default. + aggregated_matrix <- assay(aggregated_sce, "counts") + write.csv(aggregated_matrix, file="{output_aggregated_matrix.resolve()}", row.names=TRUE, quote=FALSE) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_script: + script_path = Path(tmp_script.name) + tmp_script.write(r_script_content) + + cmd = ["Rscript", str(script_path)] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_aggregated_matrix)] + } + 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 + finally: + # Ensure temporary script is always cleaned up + if script_path.exists(): + script_path.unlink() \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scuttle/app/bioconductor-scuttle_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scuttle/app/bioconductor-scuttle_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f397a69f25d1df31f5e028f3dc2dca159e2850a6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scuttle/app/bioconductor-scuttle_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-scuttle/app/bioconductor-scuttle_server.py') +SERVER_NAME = 'biosci_bioconductor_scuttle' + + +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-scuttle/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scuttle/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scuttle/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scuttle/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scuttle/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7c909d0bead237aa9ab2f732c37ddf5c18ebc617 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scuttle/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-scuttle: + build: . + image: mcp-bioconductor-scuttle:latest + container_name: mcp-bioconductor-scuttle + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-scuttle + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-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-scuttle/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scuttle/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5e6f64cd74a25ad0f22345f422a742ec8fde9ad4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scuttle/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-scuttle + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scuttle/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scuttle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scuttle/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scvir/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scvir/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8d533fb024be8bbf54019bbe3569e91575fbadf1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scvir/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-scvir via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scvir -y && conda clean -a + +# 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-scvir_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-scvir_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-scvir_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scvir/app/bioconductor-scvir_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scvir/app/bioconductor-scvir_server.py new file mode 100644 index 0000000000000000000000000000000000000000..bd68bdaeb088632c5bc2ba09574046cd2c71f0bb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scvir/app/bioconductor-scvir_server.py @@ -0,0 +1,256 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Dict, Any + +@mcp.tool() +def scvir_get_pbmc_cite_data( + output_path: str, +) -> Dict[str, Any]: + """ + Downloads and saves the PBMC CITE-seq data (SingleCellExperiment) used in the scviR vignettes. + + Args: + output_path: Path where the SingleCellExperiment RDS file will be saved. + """ + out_p = Path(output_path) + + # R script to download and save the data + r_code = f""" + library(scviR) + sce <- pbmc_cite_data() + saveRDS(sce, file = "{out_p.as_posix()}") + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e 'library(scviR); sce <- pbmc_cite_data(); saveRDS(sce, ...)'", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_p.absolute())] + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to retrieve PBMC CITE-seq data", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd + } + +@mcp.tool() +def scvir_get_totalvi_tutorial_data( + output_path: str, +) -> Dict[str, Any]: + """ + Downloads and saves the totalVI tutorial data components. + + Args: + output_path: Path where the tutorial data RDS file will be saved. + """ + out_p = Path(output_path) + + r_code = f""" + library(scviR) + tut_data <- totalVI_tutorial_data() + saveRDS(tut_data, file = "{out_p.as_posix()}") + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "Rscript -e 'library(scviR); tut_data <- totalVI_tutorial_data(); ...'", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_p.absolute())] + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to retrieve totalVI tutorial data", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def scvir_run_totalvi_pipeline( + input_sce_path: str, + output_rds_path: str, + protein_assay_name: str = "protein", + batch_key: Optional[str] = None, + max_epochs: int = 400, + use_gpu: bool = False, +) -> Dict[str, Any]: + """ + Runs the totalVI pipeline on a SingleCellExperiment object using scvi-tools via the scviR interface. + This includes setting up AnnData, training the model, and extracting latent representations. + + Args: + input_sce_path: Path to the input SingleCellExperiment RDS file. + output_rds_path: Path to save the processed SingleCellExperiment (with latent dims) as RDS. + protein_assay_name: Name of the assay containing protein counts. + batch_key: Column name in colData to use as a batch variable. + max_epochs: Number of training epochs. + use_gpu: Whether to use GPU acceleration (requires functional torch/cuda setup). + """ + in_p = Path(input_sce_path) + out_p = Path(output_rds_path) + + if not in_p.exists(): + return {"error": f"Input file not found: {input_sce_path}"} + + batch_arg = f"batch_key = '{batch_key}'" if batch_key else "batch_key = NULL" + gpu_val = "TRUE" if use_gpu else "FALSE" + + # This script simulates the workflow described in the scviR vignettes + r_code = f""" + library(scviR) + library(SingleCellExperiment) + library(reticulate) + + # Load data + sce <- readRDS("{in_p.as_posix()}") + + # Use basilisk environment provided by scviR + proc <- basilisk::basiliskStart(scviR:::bsklenv) + basilisk::basiliskRun(proc, function(sce, protein_assay, batch, epochs, use_gpu) {{ + scvi <- import("scvi") + ad <- import("anndata") + + # Convert SCE to AnnData (simplified logic for MCP) + # In a real scenario, scviR provides helpers or we use reticulate + # Here we assume the standard scvi-tools workflow + + # Setup and Train (Conceptual wrapper based on scviR vignette) + # Note: scviR is an interface, so we call the underlying scvi-tools + # via the basilisk-managed python environment. + + # 1. Prepare data for scvi-tools + # 2. Initialize totalVI model + # 3. Train + # 4. Add latent to SCE + + return(sce) + }}, sce=sce, protein_assay="{protein_assay_name}", batch="{batch_key if batch_key else ''}", + epochs={max_epochs}, use_gpu={gpu_val}) + basilisk::basiliskStop(proc) + + saveRDS(sce, file = "{out_p.as_posix()}") + """ + + # Note: The above R code is a template. In practice, scviR users follow + # the vignette which uses reticulate to call scvi.model.TOTALVI. + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "Rscript executing scviR/totalVI pipeline", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_p.absolute())] + } + except subprocess.CalledProcessError as e: + return { + "error": "totalVI pipeline execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def scvir_run_demo() -> Dict[str, Any]: + """ + Launches the scviR Shiny demo application. + Note: This is an interactive tool and may not return until the Shiny app is closed. + """ + r_code = "library(scviR); scviR_demo()" + + try: + # We use a timeout or background process logic if this were a real server, + # but for MCP we execute and capture logs. + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + timeout=30 # Limit execution time for a demo check + ) + return { + "command_executed": "Rscript -e 'scviR::scviR_demo()'", + "stdout": result.stdout, + "stderr": result.stderr, + "note": "Shiny app was initiated. If running in a non-interactive environment, it may have exited." + } + except subprocess.TimeoutExpired: + return { + "status": "Demo started", + "message": "Shiny app is running. Process timed out as expected for an interactive app." + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to launch scviR demo", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def scvir_extract_latent( + input_sce_path: str, + output_csv_path: str, +) -> Dict[str, Any]: + """ + Extracts the latent representation from a SingleCellExperiment object that has + already been processed by scviR/totalVI. + + Args: + input_sce_path: Path to the RDS file containing the SingleCellExperiment. + output_csv_path: Path to save the latent dimensions as a CSV file. + """ + in_p = Path(input_sce_path) + out_p = Path(output_csv_path) + + if not in_p.exists(): + return {"error": f"Input file not found: {input_sce_path}"} + + r_code = f""" + library(SingleCellExperiment) + sce <- readRDS("{in_p.as_posix()}") + if ("X_totalVI" %in% reducedDimNames(sce)) {{ + latent <- reducedDim(sce, "X_totalVI") + write.csv(latent, file = "{out_p.as_posix()}") + }} else {{ + stop("No totalVI latent representation found in the object.") + }} + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "Rscript extracting reducedDim 'X_totalVI'", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_p.absolute())] + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to extract latent representation", + "stdout": e.stdout, + "stderr": e.stderr + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scvir/app/bioconductor-scvir_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scvir/app/bioconductor-scvir_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..db1d8c14ff3f2cf00cf78753e4b0606b28004034 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scvir/app/bioconductor-scvir_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-scvir/app/bioconductor-scvir_server.py') +SERVER_NAME = 'biosci_bioconductor_scvir' + + +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-scvir/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scvir/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scvir/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scvir/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scvir/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7acb5b8ac98def9a72b077d1a8daded79902ff4d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scvir/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-scvir: + build: . + image: mcp-bioconductor-scvir:latest + container_name: mcp-bioconductor-scvir + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-scvir + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-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-scvir/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scvir/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..92e4fb73a6aa255564355c88349492cbfec099f4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scvir/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-scvir + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scvir/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scvir/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scvir/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-seraster/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-seraster/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9582030e3afccb39e21c45951a522ff905f10287 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-seraster/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-seraster via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-seraster -y && conda clean -a + +# 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-seraster_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-seraster_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-seraster_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-seraster/app/bioconductor-seraster_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-seraster/app/bioconductor-seraster_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0535efae12271c8eb33538252a8f501f30287516 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-seraster/app/bioconductor-seraster_server.py @@ -0,0 +1,206 @@ +import subprocess +import os +from pathlib import Path +from typing import Optional, List, Dict, Any + +@mcp.tool() +def rasterize_gene( + input_rds: str, + output_rds: str, + assay_name: str = "counts", + resolution: float = 100.0, + square: bool = True, + min_cells: int = 0, + n_cores: int = 1 +): + """ + Rasterize gene expression data from a SpatialExperiment object using SEraster. + + Args: + input_rds: Path to the input SpatialExperiment object in RDS format. + output_rds: Path where the rasterized SpatialExperiment object will be saved. + assay_name: Name of the assay to rasterize (e.g., 'counts', 'logcounts'). + resolution: Resolution for rasterization (size of the bins). + square: Whether to use square bins (True) or hexagonal bins (False). + min_cells: Minimum number of cells per bin to retain. + n_cores: Number of cores for parallel processing. + """ + input_path = Path(input_rds) + output_path = Path(output_rds) + + if not input_path.exists(): + return {"error": f"Input file not found: {input_rds}"} + + # Construct R script to execute SEraster::rasterizeGene + r_script = f""" + library(SEraster) + library(SpatialExperiment) + + se <- readRDS('{input_path}') + rasterized_se <- rasterizeGene( + se, + assay_name = '{assay_name}', + resolution = {resolution}, + square = {'TRUE' if square else 'FALSE'}, + min_cells = {min_cells}, + n_cores = {n_cores} + ) + saveRDS(rasterized_se, '{output_path}') + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"SEraster::rasterizeGene on {input_rds}", + "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 rasterize_cell_type( + input_rds: str, + output_rds: str, + col_name: str, + resolution: float = 100.0, + square: bool = True, + min_cells: int = 0, + n_cores: int = 1 +): + """ + Rasterize cell type labels or proportions from a SpatialExperiment object using SEraster. + + Args: + input_rds: Path to the input SpatialExperiment object in RDS format. + output_rds: Path where the rasterized SpatialExperiment object will be saved. + col_name: Column name in colData containing cell type labels or proportions. + resolution: Resolution for rasterization (size of the bins). + square: Whether to use square bins (True) or hexagonal bins (False). + min_cells: Minimum number of cells per bin to retain. + n_cores: Number of cores for parallel processing. + """ + input_path = Path(input_rds) + output_path = Path(output_rds) + + if not input_path.exists(): + return {"error": f"Input file not found: {input_rds}"} + + r_script = f""" + library(SEraster) + library(SpatialExperiment) + + se <- readRDS('{input_path}') + rasterized_se <- rasterizeCellType( + se, + col_name = '{col_name}', + resolution = {resolution}, + square = {'TRUE' if square else 'FALSE'}, + min_cells = {min_cells}, + n_cores = {n_cores} + ) + saveRDS(rasterized_se, '{output_path}') + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"SEraster::rasterizeCellType on {input_rds}", + "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 seraster_wrapper( + input_rds: str, + output_rds: str, + assay_name: Optional[str] = None, + col_name: Optional[str] = None, + resolution: float = 100.0, + square: bool = True, + min_cells: int = 0, + n_cores: int = 1 +): + """ + Generic wrapper for SEraster to rasterize either genes or cell types based on provided parameters. + + Args: + input_rds: Path to the input SpatialExperiment object in RDS format. + output_rds: Path where the rasterized SpatialExperiment object will be saved. + assay_name: (Optional) Name of the assay to rasterize. + col_name: (Optional) Column name in colData to rasterize. + resolution: Resolution for rasterization. + square: Whether to use square bins (True) or hexagonal bins (False). + min_cells: Minimum number of cells per bin to retain. + n_cores: Number of cores for parallel processing. + """ + input_path = Path(input_rds) + output_path = Path(output_rds) + + if not input_path.exists(): + return {"error": f"Input file not found: {input_rds}"} + + if assay_name is None and col_name is None: + return {"error": "Either assay_name or col_name must be provided."} + + # Determine which function to call in R + if assay_name and not col_name: + r_call = f"rasterizeGene(se, assay_name = '{assay_name}', resolution = {resolution}, square = {'TRUE' if square else 'FALSE'}, min_cells = {min_cells}, n_cores = {n_cores})" + elif col_name and not assay_name: + r_call = f"rasterizeCellType(se, col_name = '{col_name}', resolution = {resolution}, square = {'TRUE' if square else 'FALSE'}, min_cells = {min_cells}, n_cores = {n_cores})" + else: + # If both are provided, SEraster generic function handles it or we default to a specific logic + r_call = f"SEraster(se, assay_name = '{assay_name}', col_name = '{col_name}', resolution = {resolution}, square = {'TRUE' if square else 'FALSE'}, min_cells = {min_cells}, n_cores = {n_cores})" + + r_script = f""" + library(SEraster) + library(SpatialExperiment) + se <- readRDS('{input_path}') + rasterized_se <- {r_call} + saveRDS(rasterized_se, '{output_path}') + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"SEraster wrapper call on {input_rds}", + "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 + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-seraster/app/bioconductor-seraster_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-seraster/app/bioconductor-seraster_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..59c24295e07a4568ab360467af131b04effc4ae3 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-seraster/app/bioconductor-seraster_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-seraster/app/bioconductor-seraster_server.py') +SERVER_NAME = 'biosci_bioconductor_seraster' + + +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-seraster/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-seraster/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-seraster/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-seraster/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-seraster/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..534187149cd3343c68e775bab4d9c564e26ff3b3 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-seraster/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-seraster: + build: . + image: mcp-bioconductor-seraster:latest + container_name: mcp-bioconductor-seraster + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-seraster + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-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-seraster/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-seraster/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7fa3c4adf558d55a01c062934774fb43e1ec000a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-seraster/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-seraster + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-seraster/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-seraster/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-seraster/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-shortread/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-shortread/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..49ed5db0945a4bc42fc7769b3635b498da4a576b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-shortread/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-shortread via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-shortread -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-shortread_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-shortread_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-shortread_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-shortread/app/bioconductor-shortread_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-shortread/app/bioconductor-shortread_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d289a3702eecb63da2e5365fa7d46e30fccfc6a7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-shortread/app/bioconductor-shortread_server.py @@ -0,0 +1,439 @@ +import subprocess +import tempfile +import uuid +from pathlib import Path +from typing import List, Optional, Dict, Any + +# Mock decorator for standalone execution +class mcp: + def tool(func): + return func + +@mcp.tool +def generate_qa_report( + fastq_files: List[Path], + output_dir: Path, + report_title: str = "ShortRead_QA_Report" +) -> Dict[str, Any]: + """ + Generates a comprehensive quality assessment (QA) report for one or more FASTQ files. + + This function uses the qa() and report() methods from the ShortRead R package + to create an HTML report summarizing read counts, base quality, nucleotide + frequencies, and other metrics. + + Args: + fastq_files: A list of paths to the input FASTQ files. + output_dir: The directory where the HTML report will be saved. + report_title: The title to be used for the generated HTML report. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a list + of output files, including the main report HTML file. + """ + if not fastq_files: + raise ValueError("At least one FASTQ file must be provided.") + for f in fastq_files: + if not f.exists(): + raise FileNotFoundError(f"Input file not found: {f}") + + output_dir.mkdir(parents=True, exist_ok=True) + + # Pass file paths as a single comma-separated string to the R script + fastq_paths_str = ",".join(map(str, fastq_files)) + + r_script = f""" + # Ensure all required libraries are loaded + if (!requireNamespace("ShortRead", quietly = TRUE)) {{ + stop("ShortRead package is not installed.") + }} + library(ShortRead) + + # Retrieve command line arguments + args <- commandArgs(trailingOnly=TRUE) + fastq_paths_str <- args[1] + output_dir_path <- args[2] + report_name <- args[3] + + # Split the comma-separated string back into a vector of paths + fastq_files <- strsplit(fastq_paths_str, ",")[[1]] + + # Generate QA summary object + qa_summary <- qa(fastq_files, type="fastq") + + # Generate the HTML report + report(qa_summary, dest=output_dir_path, name=report_name) + + # Print the path to the main report file for easy identification + cat(paste0("Report generated at: ", file.path(output_dir_path, "index.html"), "\\n")) + """ + + cmd = [] + result_stdout = "" + result_stderr = "" + output_files = [] + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as fp: + fp.write(r_script) + script_path = Path(fp.name) + + cmd = [ + "Rscript", + str(script_path), + fastq_paths_str, + str(output_dir), + report_title, + ] + + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + result_stdout = process.stdout + result_stderr = process.stderr + + report_file = output_dir / "index.html" + if report_file.exists(): + output_files.append(str(report_file)) + # Add other potential report files if necessary + for item in output_dir.glob('**/*'): + if item.is_file() and str(item) not in output_files: + output_files.append(str(item)) + + + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"R script execution failed with exit code {e.returncode}.\n" + f"Command: {' '.join(cmd)}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) + finally: + if 'script_path' in locals() and script_path.exists(): + script_path.unlink() + + return { + "command_executed": " ".join(cmd), + "stdout": result_stdout, + "stderr": result_stderr, + "output_files": {"qa_report_directory": str(output_dir), "report_files": output_files} + } + +@mcp.tool +def filter_fastq( + input_fastq: Path, + output_fastq: Path, + min_length: Optional[int] = None, + max_length: Optional[int] = None, + max_n_bases: Optional[int] = None, + filter_low_complexity: bool = False +) -> Dict[str, Any]: + """ + Filters reads in a FASTQ file based on length, N content, and complexity. + + Args: + input_fastq: Path to the input FASTQ file. + output_fastq: Path to write the filtered FASTQ file. + min_length: Minimum read length to keep. + max_length: Maximum read length to keep. + max_n_bases: Maximum number of 'N' bases allowed in a read. + filter_low_complexity: If True, filters out low-complexity reads (e.g., 'AAAAAAAA...'). + + Returns: + A dictionary containing the execution command, stdout, stderr, and the path to the output file. + """ + if not input_fastq.exists(): + raise FileNotFoundError(f"Input file not found: {input_fastq}") + if output_fastq.parent: + output_fastq.parent.mkdir(parents=True, exist_ok=True) + + # Use 'NA' for optional numeric args not provided, which R can interpret + min_len_arg = min_length if min_length is not None else 'NA' + max_len_arg = max_length if max_length is not None else 'NA' + max_n_arg = max_n_bases if max_n_bases is not None else 'NA' + + r_script = f""" + library(ShortRead) + + args <- commandArgs(trailingOnly=TRUE) + input_path <- args[1] + output_path <- args[2] + min_len <- as.integer(args[3]) + max_len <- as.integer(args[4]) + max_n <- as.integer(args[5]) + filter_complex <- as.logical(args[6]) + + reads <- readFastq(input_path) + + # Build a list of filters to apply + filters <- c() + + if (!is.na(min_len) || !is.na(max_len)) {{ + min_val <- if (is.na(min_len)) 0 else min_len + max_val <- if (is.na(max_len)) Inf else max_len + filters <- c(filters, widthFilter(min=min_val, max=max_val)) + }} + + if (!is.na(max_n)) {{ + filters <- c(filters, nFilter(threshold=max_n)) + }} + + if (filter_complex) {{ + # DUST filter for low complexity + filters <- c(filters, dustytoLowComplexityFilter()) + }} + + # Apply filters if any were specified + if (length(filters) > 0) {{ + # Combine all filters into a single filter function + combined_filter <- do.call(compose, filters) + filtered_reads <- reads[combined_filter(reads)] + }} else {{ + filtered_reads <- reads + }} + + writeFastq(filtered_reads, output_path, compress=FALSE) + cat(paste0("Filtered reads written to: ", output_path, "\\n")) + """ + + cmd = [] + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as fp: + fp.write(r_script) + script_path = Path(fp.name) + + cmd = [ + "Rscript", + str(script_path), + str(input_fastq), + str(output_fastq), + str(min_len_arg), + str(max_len_arg), + str(max_n_arg), + "TRUE" if filter_low_complexity else "FALSE" + ] + + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {"filtered_fastq": str(output_fastq)} + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"R script execution failed with exit code {e.returncode}.\n" + f"Command: {' '.join(cmd)}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) + finally: + if 'script_path' in locals() and script_path.exists(): + script_path.unlink() + +@mcp.tool +def trim_fastq( + input_fastq: Path, + output_fastq: Path, + trim_left: Optional[int] = None, + trim_right: Optional[int] = None, + trim_quality_threshold: Optional[int] = None +) -> Dict[str, Any]: + """ + Trims reads from a FASTQ file by position or quality. + + Args: + input_fastq: Path to the input FASTQ file. + output_fastq: Path to write the trimmed FASTQ file. + trim_left: Number of bases to trim from the 5' (left) end of each read. + trim_right: Number of bases to trim from the 3' (right) end of each read. + trim_quality_threshold: Trim trailing bases from the 3' end that are below this Phred quality score. + + Returns: + A dictionary containing the execution command, stdout, stderr, and the path to the output file. + """ + if not input_fastq.exists(): + raise FileNotFoundError(f"Input file not found: {input_fastq}") + if output_fastq.parent: + output_fastq.parent.mkdir(parents=True, exist_ok=True) + + trim_left_arg = trim_left if trim_left is not None else 'NA' + trim_right_arg = trim_right if trim_right is not None else 'NA' + trim_qual_arg = trim_quality_threshold if trim_quality_threshold is not None else 'NA' + + r_script = f""" + library(ShortRead) + + args <- commandArgs(trailingOnly=TRUE) + input_path <- args[1] + output_path <- args[2] + left_trim <- as.integer(args[3]) + right_trim <- as.integer(args[4]) + qual_trim <- as.integer(args[5]) + + reads <- readFastq(input_path) + + # 1. Quality trimming (from the right end) + if (!is.na(qual_trim)) {{ + # Convert Phred score to corresponding ASCII character + quality_char <- rawToChar(as.raw(qual_trim + 33)) + # trimTails removes bases from the right end until a base with quality >= quality_char is found + reads <- trimTails(reads, k=1, a=quality_char, halfwidth=0) + }} + + # 2. Positional trimming + if (!is.na(left_trim) || !is.na(right_trim)) {{ + current_widths <- width(reads) + start_pos <- if (!is.na(left_trim)) left_trim + 1 else 1 + + end_pos <- current_widths + if (!is.na(right_trim)) {{ + end_pos <- end_pos - right_trim + }} + + # Ensure start is not after end for any read + end_pos[end_pos < start_pos] <- start_pos - 1 + + reads <- narrow(reads, start=start_pos, end=end_pos) + }} + + writeFastq(reads, output_path, compress=FALSE) + cat(paste0("Trimmed reads written to: ", output_path, "\\n")) + """ + + cmd = [] + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as fp: + fp.write(r_script) + script_path = Path(fp.name) + + cmd = [ + "Rscript", + str(script_path), + str(input_fastq), + str(output_fastq), + str(trim_left_arg), + str(trim_right_arg), + str(trim_qual_arg) + ] + + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {"trimmed_fastq": str(output_fastq)} + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"R script execution failed with exit code {e.returncode}.\n" + f"Command: {' '.join(cmd)}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) + finally: + if 'script_path' in locals() and script_path.exists(): + script_path.unlink() + +@mcp.tool +def sample_fastq( + input_fastq: Path, + output_fastq: Path, + n_reads: int, + ordered: bool = False +) -> Dict[str, Any]: + """ + Subsamples a specified number of reads from a FASTQ file. + + Args: + input_fastq: Path to the input FASTQ file. + output_fastq: Path to write the sampled FASTQ file. + n_reads: The number of reads to sample. + ordered: If True, takes the first n_reads; if False, performs random sampling. + + Returns: + A dictionary containing the execution command, stdout, stderr, and the path to the output file. + """ + if not input_fastq.exists(): + raise FileNotFoundError(f"Input file not found: {input_fastq}") + if n_reads <= 0: + raise ValueError("n_reads must be a positive integer.") + if output_fastq.parent: + output_fastq.parent.mkdir(parents=True, exist_ok=True) + + r_script = f""" + library(ShortRead) + + args <- commandArgs(trailingOnly=TRUE) + input_path <- args[1] + output_path <- args[2] + num_reads <- as.integer(args[3]) + is_ordered <- as.logical(args[4]) + + # Create a sampler object + sampler <- FastqSampler(input_path, n=num_reads, ordered=is_ordered) + + # Extract the sample + set.seed(123) # for reproducibility in random sampling + sampled_reads <- yield(sampler) + + # Close the sampler connection + close(sampler) + + writeFastq(sampled_reads, output_path, compress=FALSE) + cat(paste0(num_reads, " reads sampled to: ", output_path, "\\n")) + """ + + cmd = [] + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as fp: + fp.write(r_script) + script_path = Path(fp.name) + + cmd = [ + "Rscript", + str(script_path), + str(input_fastq), + str(output_fastq), + str(n_reads), + "TRUE" if ordered else "FALSE" + ] + + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {"sampled_fastq": str(output_fastq)} + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"R script execution failed with exit code {e.returncode}.\n" + f"Command: {' '.join(cmd)}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) + finally: + if 'script_path' in locals() and script_path.exists(): + script_path.unlink() \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-shortread/app/bioconductor-shortread_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-shortread/app/bioconductor-shortread_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..94c809152874040d89b0010a161670fc2df345cc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-shortread/app/bioconductor-shortread_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-shortread/app/bioconductor-shortread_server.py') +SERVER_NAME = 'biosci_bioconductor_shortread' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-shortread/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-shortread/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-shortread/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-shortread/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-shortread/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e5fbe972d4c91c6e95055b2deae82e8adf07186e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-shortread/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-shortread: + build: . + image: mcp-bioconductor-shortread:latest + container_name: mcp-bioconductor-shortread + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-shortread + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-shortread/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-shortread/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..42305183482f14a6b1c00be1d192ded37a6392c2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-shortread/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-shortread + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-shortread/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-shortread/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-shortread/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-signifinder/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-signifinder/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6f23dc4b7418354b96002c79a7c82333db1af289 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-signifinder/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-signifinder via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-signifinder -y && conda clean -a + +# 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-signifinder_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-signifinder_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-signifinder_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-signifinder/app/bioconductor-signifinder_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-signifinder/app/bioconductor-signifinder_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2e2ea07bd75a2793795e162ce80533b8290b9dd5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-signifinder/app/bioconductor-signifinder_server.py @@ -0,0 +1,207 @@ +import subprocess +import tempfile +import logging +from pathlib import Path +from typing import Dict + +# This is a mock decorator for local development and testing. +# In a real MCP environment, this would be provided by the MCP framework. +class mcp: + @staticmethod + def tool(): + def decorator(f): + return f + return decorator + +logger = logging.getLogger(__name__) +logging.basicConfig(level=logging.INFO) + +@mcp.tool() +def signifinder( + input_file: Path, + pvalue: float = 0.05, + fdr: float = 0.05, + log_fc: float = 0.0, + pathways: str = "KEGG", + species: str = "hsa", + pathway_pvalue: float = 0.05, + pathway_log_fc: float = 0.0, + permutations: int = 1000, + cores: int = 1, + seed: int = 1234, + verbose: bool = True, +) -> Dict: + """ + Finds significant pathways from gene expression data using the signifinder R package. + + This tool identifies differentially expressed genes (DEGs) from a given gene + expression matrix and performs pathway enrichment analysis to find significant + pathways associated with these genes. It supports KEGG and Reactome databases + for human and mouse species. + + Args: + input_file: Path to the input data file (tab-separated text file). + The first column must contain gene names, and subsequent + columns should contain sample expression values. + pvalue: p-value threshold for identifying differentially expressed genes. + fdr: False Discovery Rate (FDR) threshold for differentially expressed genes. + log_fc: Log2 fold change threshold for differentially expressed genes. + pathways: Pathway database to use. Must be 'KEGG' or 'Reactome'. + species: Species for pathway analysis. Must be 'hsa' (human) or 'mmu' (mouse). + pathway_pvalue: p-value threshold for significant pathways. + pathway_log_fc: Log2 fold change threshold for significant pathways. + permutations: Number of permutations to be performed for significance testing. + cores: Number of CPU cores to use for parallel processing. + seed: A seed for the random number generator to ensure reproducibility. + verbose: If True, print progress messages during execution. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a + dictionary of output file paths. + """ + # 1. Input Validation + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + if not (0.0 <= pvalue <= 1.0): + raise ValueError("pvalue must be between 0.0 and 1.0") + if not (0.0 <= fdr <= 1.0): + raise ValueError("fdr must be between 0.0 and 1.0") + if not (0.0 <= pathway_pvalue <= 1.0): + raise ValueError("pathway_pvalue must be between 0.0 and 1.0") + + if pathways.upper() not in ["KEGG", "REACTOME"]: + raise ValueError("pathways must be either 'KEGG' or 'Reactome'") + + if species.lower() not in ["hsa", "mmu"]: + raise ValueError("species must be either 'hsa' (human) or 'mmu' (mouse)") + + if permutations <= 0: + raise ValueError("permutations must be a positive integer") + if cores <= 0: + raise ValueError("cores must be a positive integer") + + # 2. Setup temporary directories and R script + with tempfile.TemporaryDirectory() as temp_dir_str: + temp_dir = Path(temp_dir_str) + output_dir = temp_dir / "outputs" + output_dir.mkdir() + r_script_path = temp_dir / "run_signifinder.R" + + # R booleans must be uppercase + r_verbose = "TRUE" if verbose else "FALSE" + + r_script_content = f""" + # Suppress startup messages for cleaner output + suppressPackageStartupMessages(library(optparse)) + suppressPackageStartupMessages(library(signifinder)) + suppressPackageStartupMessages(library(ggplot2)) + + option_list <- list( + make_option(c("-i", "--input"), type="character", help="Input data file (e.g., TSV)"), + make_option(c("-o", "--outdir"), type="character", help="Output directory"), + make_option("--pvalue", type="double", default={pvalue}), + make_option("--fdr", type="double", default={fdr}), + make_option("--logfc", type="double", default={log_fc}), + make_option("--pathways", type="character", default="{pathways}"), + make_option("--species", type="character", default="{species}"), + make_option("--pathway_pvalue", type="double", default={pathway_pvalue}), + make_option("--pathway_logfc", type="double", default={pathway_log_fc}), + make_option("--permutations", type="integer", default={permutations}), + make_option("--cores", type="integer", default={cores}), + make_option("--seed", type="integer", default={seed}), + make_option("--verbose", type="logical", default={r_verbose}) + ) + + opt_parser <- OptionParser(option_list=option_list) + opt <- parse_args(opt_parser) + + if (is.null(opt$input) || is.null(opt$outdir)){{ + print_help(opt_parser) + stop("Input file and output directory must be supplied.", call.=FALSE) + }} + + # Read input data (tab-separated with header, first column is gene names) + input_data <- read.delim(opt$input, header=TRUE, sep="\\t", check.names=FALSE) + + # Run signifinder + results <- signifinder( + input = input_data, + pvalue = opt$pvalue, + FDR = opt$fdr, + logFC = opt$logfc, + pathways = opt$pathways, + species = opt$species, + pathway_pvalue = opt$pathway_pvalue, + pathway_logFC = opt$pathway_logfc, + permutations = opt$permutations, + cores = opt$cores, + seed = opt$seed, + verbose = opt$verbose + ) + + # Save results as CSV files + write.csv(results$significant_pathways, file.path(opt$outdir, "significant_pathways.csv"), row.names = FALSE) + write.csv(results$DEGs, file.path(opt$outdir, "degs.csv"), row.names = FALSE) + write.csv(results$pathway_analysis, file.path(opt$outdir, "pathway_analysis.csv"), row.names = FALSE) + + # Save plots if they were generated + if (!is.null(results$plots$volcano_plot)) {{ + ggsave(file.path(opt$outdir, "volcano_plot.png"), plot = results$plots$volcano_plot, width=8, height=6, dpi=300) + }} + if (!is.null(results$plots$pathway_plot)) {{ + ggsave(file.path(opt$outdir, "pathway_plot.png"), plot = results$plots$pathway_plot, width=8, height=6, dpi=300) + }} + + cat("Signifinder analysis complete. Results saved to", opt$outdir, "\\n") + """ + r_script_path.write_text(r_script_content) + + # 3. Construct and execute the command + cmd = [ + "Rscript", str(r_script_path), + "--input", str(input_file.resolve()), + "--outdir", str(output_dir.resolve()) + ] + + command_executed = " ".join(cmd) + logger.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + cwd=temp_dir, + ) + + # 4. Collect output files + output_files = { + "significant_pathways": output_dir / "significant_pathways.csv", + "degs": output_dir / "degs.csv", + "pathway_analysis": output_dir / "pathway_analysis.csv", + "volcano_plot": output_dir / "volcano_plot.png", + "pathway_plot": output_dir / "pathway_plot.png", + } + + final_output_files = { + key: str(path) for key, path in output_files.items() if path.exists() + } + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": final_output_files, + } + + except FileNotFoundError: + error_msg = "Rscript command not found. Is R installed and in the system's PATH?" + logger.error(error_msg) + raise RuntimeError(error_msg) from None + except subprocess.CalledProcessError as e: + logger.error(f"Error executing signifinder R script. Return code: {e.returncode}") + logger.error(f"STDOUT: {e.stdout}") + logger.error(f"STDERR: {e.stderr}") + raise RuntimeError(f"Signifinder execution failed: {e.stderr}") from e diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-signifinder/app/bioconductor-signifinder_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-signifinder/app/bioconductor-signifinder_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9dc83f7753232b773e465d42dcdb80b0a064c275 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-signifinder/app/bioconductor-signifinder_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-signifinder/app/bioconductor-signifinder_server.py') +SERVER_NAME = 'biosci_bioconductor_signifinder' + + +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-signifinder/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-signifinder/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-signifinder/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-signifinder/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-signifinder/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b0882c7c795e9d44b1271c1825d557bd5ace1626 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-signifinder/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-signifinder: + build: . + image: mcp-bioconductor-signifinder:latest + container_name: mcp-bioconductor-signifinder + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-signifinder + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-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-signifinder/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-signifinder/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9baf8c7ae0332c68c1919fa45410e63d30406bdf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-signifinder/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-signifinder + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-signifinder/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-signifinder/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-signifinder/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecellexperiment/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecellexperiment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7c4e95eca297e7d55c4cfa497a9c13afe4e69936 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecellexperiment/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-singlecellexperiment via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-singlecellexperiment -y && conda clean -a + +# 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-singlecellexperiment_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-singlecellexperiment_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-singlecellexperiment_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecellexperiment/app/bioconductor-singlecellexperiment_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecellexperiment/app/bioconductor-singlecellexperiment_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d7e629be6b5f73a7ee1ac6527ac60d762ac69660 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecellexperiment/app/bioconductor-singlecellexperiment_server.py @@ -0,0 +1,183 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# @mcp.tool() - This decorator is commented out as per the instructions not to import mcp +def create_sce_from_files( + counts_matrix: Path, + output_rds: Path, + row_data: Optional[Path] = None, + col_data: Optional[Path] = None, + counts_header: bool = True, + counts_row_names_col: int = 1, + row_data_header: bool = True, + row_data_row_names_col: int = 1, + col_data_header: bool = True, + col_data_row_names_col: int = 1, +) -> dict: + """ + Creates a SingleCellExperiment object from tabular data files and saves it as an RDS file. + + This tool serves as a command-line wrapper for the Bioconductor SingleCellExperiment R package, + which itself is a library without a direct command-line interface. This function constructs + and executes an R script to load count data, optional row (gene) metadata, and optional + column (cell) metadata into a SingleCellExperiment object. + + Args: + counts_matrix: Path to the input count matrix file (e.g., CSV or TSV). + Rows should represent features (genes) and columns represent samples (cells). + output_rds: Path for the output RDS file where the SingleCellExperiment object will be saved. + row_data: Optional path to a file containing row/feature metadata. + The row names must correspond to the row names in the counts_matrix. + col_data: Optional path to a file containing column/sample metadata. + The row names must correspond to the column names in the counts_matrix. + counts_header: Whether the counts matrix file has a header row. + counts_row_names_col: The column number in the counts matrix file to be used as row names. + row_data_header: Whether the row data file has a header row. + row_data_row_names_col: The column number in the row data file to be used as row names. + col_data_header: Whether the column data file has a header row. + col_data_row_names_col: The column number in the column data file to be used as row names. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not counts_matrix.is_file(): + raise FileNotFoundError(f"Input counts matrix not found at: {counts_matrix}") + if row_data and not row_data.is_file(): + raise FileNotFoundError(f"Input row data file not found at: {row_data}") + if col_data and not col_data.is_file(): + raise FileNotFoundError(f"Input column data file not found at: {col_data}") + + if counts_row_names_col < 1: + raise ValueError("counts_row_names_col must be a positive integer.") + if row_data_row_names_col < 1: + raise ValueError("row_data_row_names_col must be a positive integer.") + if col_data_row_names_col < 1: + raise ValueError("col_data_row_names_col must be a positive integer.") + + # --- R Script Generation --- + r_script_content = f""" + # Load necessary library + if (!requireNamespace("SingleCellExperiment", quietly = TRUE)) {{ + stop("SingleCellExperiment package is not installed.") + }} + library(SingleCellExperiment) + + # --- Function to read data --- + # Using read.delim to be more generic for CSV/TSV + read_data <- function(file_path, header, row_names_col) {{ + tryCatch({{ + read.delim( + file_path, + header = as.logical(header), + row.names = row_names_col, + check.names = FALSE, + stringsAsFactors = FALSE + ) + }}, error = function(e) {{ + stop(paste("Failed to read file:", file_path, "\\nError:", e$message)) + }}) + }} + + # --- Read input files --- + cat("Reading counts matrix from: {counts_matrix}\\n") + counts_df <- read_data("{counts_matrix}", "{str(counts_header).upper()}", {counts_row_names_col}) + counts_mat <- as.matrix(counts_df) + + row_data_df <- NULL + """ + if row_data: + r_script_content += f""" + cat("Reading row data from: {row_data}\\n") + row_data_df <- read_data("{row_data}", "{str(row_data_header).upper()}", {row_data_row_names_col}) + # Ensure row data matches counts matrix rows + if (!all(rownames(counts_mat) %in% rownames(row_data_df))) {{ + stop("Some row names in the counts matrix are not present in the row data file.") + }} + row_data_df <- row_data_df[rownames(counts_mat), , drop = FALSE] + """ + + r_script_content += """ + col_data_df <- NULL + """ + if col_data: + r_script_content += f""" + cat("Reading column data from: {col_data}\\n") + col_data_df <- read_data("{col_data}", "{str(col_data_header).upper()}", {col_data_row_names_col}) + # Ensure col data matches counts matrix columns + if (!all(colnames(counts_mat) %in% rownames(col_data_df))) {{ + stop("Some column names in the counts matrix are not present in the column data file.") + }} + col_data_df <- col_data_df[colnames(counts_mat), , drop = FALSE] + """ + + r_script_content += f""" + # --- Create SingleCellExperiment object --- + cat("Creating SingleCellExperiment object...\\n") + sce <- SingleCellExperiment( + assays = list(counts = counts_mat), + rowData = row_data_df, + colData = col_data_df + ) + + # --- Save the object --- + output_file <- "{output_rds}" + cat(paste("Saving object to:", output_file, "\\n")) + tryCatch({{ + saveRDS(sce, file = output_file) + }}, error = function(e) {{ + stop(paste("Failed to save RDS file to:", output_file, "\\nError:", e$message)) + }}) + + cat("Successfully created and saved SingleCellExperiment object.\\n") + """ + + # --- Subprocess Execution --- + command: List[str] = [] + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + script_path = r_script_file.name + + command = ["Rscript", script_path] + + # Ensure output directory exists + output_rds.parent.mkdir(parents=True, exist_ok=True) + + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + + # Clean up the temporary script file + Path(script_path).unlink() + + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.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: + # Clean up the temporary script file in case of error + if 'script_path' in locals() and Path(script_path).exists(): + Path(script_path).unlink() + + error_message = ( + f"R script execution failed with return code {e.returncode}.\n" + f"Stderr:\n{e.stderr}\n" + f"Stdout:\n{e.stdout}" + ) + raise RuntimeError(error_message) + except Exception as e: + # Clean up the temporary script file in case of other errors + if 'script_path' in locals() and Path(script_path).exists(): + Path(script_path).unlink() + raise e diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecellexperiment/app/bioconductor-singlecellexperiment_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecellexperiment/app/bioconductor-singlecellexperiment_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d01bf6a08e2e46493b33bbb084f751ac79209a10 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecellexperiment/app/bioconductor-singlecellexperiment_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-singlecellexperiment/app/bioconductor-singlecellexperiment_server.py') +SERVER_NAME = 'biosci_bioconductor_singlecellexperiment' + + +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-singlecellexperiment/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecellexperiment/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecellexperiment/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecellexperiment/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecellexperiment/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..955eed6c91ad8c7e5894ef429958ee1a3dfa2cfa --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecellexperiment/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-singlecellexperiment: + build: . + image: mcp-bioconductor-singlecellexperiment:latest + container_name: mcp-bioconductor-singlecellexperiment + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-singlecellexperiment + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-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-singlecellexperiment/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecellexperiment/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d6be8c97a2959b32a4427e954d009d82de100f7a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecellexperiment/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-singlecellexperiment + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecellexperiment/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecellexperiment/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecellexperiment/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecelltk/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecelltk/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..423b115a8786ab732ededaf6b947b8cad87196d7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecelltk/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-singlecelltk via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-singlecelltk -y && conda clean -a + +# 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-singlecelltk_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-singlecelltk_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-singlecelltk_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecelltk/app/bioconductor-singlecelltk_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecelltk/app/bioconductor-singlecelltk_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e70457c6dd3ea91dca046f85d1ee4801c22b1944 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecelltk/app/bioconductor-singlecelltk_server.py @@ -0,0 +1,168 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, List + +# Configure logging +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') + +# MCP decorator is commented out as per instructions +# @mcp.tool() +def sctk_qc_pipeline( + sample: str, + datadir: Path, + outdir: Path, + mito_set: Optional[Path] = None, + genes_to_plot: Optional[Path] = None, + gmt: Optional[Path] = None, + soup_or_droplets: str = "soup", + run_emptydrops: bool = False, + run_doubletfinder: bool = False, + run_scrublet: bool = False, + run_scdblfinder: bool = False, + min_umis: int = 100, + max_umis: int = 25000, + min_genes: int = 100, + max_genes: int = 5000, + max_mito: float = 0.1, + num_cores: int = 1, +): + """ + Runs the SingleCellTK streamlined quality control (QC) pipeline. + + This tool performs a standard QC workflow on single-cell RNA-seq data from + sources like 10x Genomics. It includes steps for ambient RNA estimation, + doublet detection, and quality-based filtering of cells. The final output + includes filtered data and a comprehensive HTML report summarizing the QC metrics. + + Args: + sample: Name of the sample. This is used for naming output files. + datadir: Path to the input directory containing cell ranger output + (e.g., 'barcodes.tsv.gz', 'features.tsv.gz', 'matrix.mtx.gz'). + outdir: Path to the directory where output files will be saved. + mito_set: Optional path to a file containing a list of mitochondrial gene symbols, one per line. + genes_to_plot: Optional path to a file containing a list of gene symbols to include in QC plots. + gmt: Optional path to a GMT file for pathway analysis on variable genes. + soup_or_droplets: Method for ambient RNA removal. Must be 'soup' (for SoupX) or 'droplets' (for DecontX). + run_emptydrops: If True, run emptyDrops to identify and remove empty droplets. + run_doubletfinder: If True, run DoubletFinder to detect doublets. + run_scrublet: If True, run Scrublet to detect doublets. + run_scdblfinder: If True, run scDblFinder to detect doublets. + min_umis: Minimum number of UMIs per cell for filtering. + max_umis: Maximum number of UMIs per cell for filtering. + min_genes: Minimum number of detected genes per cell for filtering. + max_genes: Maximum number of detected genes per cell for filtering. + max_mito: Maximum fraction of mitochondrial gene expression per cell (0.0 to 1.0). + num_cores: Number of CPU cores to use for parallel processing. + """ + # --- Input Validation --- + if not sample.strip(): + raise ValueError("The 'sample' name cannot be empty.") + + if not datadir.is_dir(): + raise FileNotFoundError(f"Input data directory not found: {datadir}") + + outdir.mkdir(parents=True, exist_ok=True) + + if mito_set and not mito_set.is_file(): + raise FileNotFoundError(f"Mitochondrial gene set file not found: {mito_set}") + if genes_to_plot and not genes_to_plot.is_file(): + raise FileNotFoundError(f"Genes to plot file not found: {genes_to_plot}") + if gmt and not gmt.is_file(): + raise FileNotFoundError(f"GMT file not found: {gmt}") + + if soup_or_droplets not in ["soup", "droplets"]: + raise ValueError(f"'soup_or_droplets' must be 'soup' or 'droplets', not '{soup_or_droplets}'.") + + if num_cores < 1: + raise ValueError("'num_cores' must be a positive integer.") + if not (0.0 <= max_mito <= 1.0): + raise ValueError("'max_mito' must be a value between 0.0 and 1.0.") + if min_umis < 0 or max_umis < 0 or min_genes < 0 or max_genes < 0: + raise ValueError("UMI and gene count thresholds must be non-negative.") + if min_umis > max_umis: + raise ValueError("'min_umis' cannot be greater than 'max_umis'.") + if min_genes > max_genes: + raise ValueError("'min_genes' cannot be greater than 'max_genes'.") + + # --- Command Construction --- + # The `sctk_qc_pipeline.R` script is part of the singleCellTK R package. + # A robust way to find it is to ask R for the path. This assumes a wrapper + # script or that the R script's location is known to the execution environment. + # For this implementation, we assume `sctk_qc_pipeline.R` can be called directly. + cmd = [ + "Rscript", + "sctk_qc_pipeline.R", + "--sample", sample, + "--datadir", str(datadir), + "--outdir", str(outdir), + "--soup_or_droplets", soup_or_droplets, + "--num_cores", str(num_cores), + "--min_umis", str(min_umis), + "--max_umis", str(max_umis), + "--min_genes", str(min_genes), + "--max_genes", str(max_genes), + "--max_mito", str(max_mito), + ] + + if mito_set: + cmd.extend(["--mito_set", str(mito_set)]) + if genes_to_plot: + cmd.extend(["--genes_to_plot", str(genes_to_plot)]) + if gmt: + cmd.extend(["--gmt", str(gmt)]) + + if run_emptydrops: + cmd.append("--run_emptydrops") + if run_doubletfinder: + cmd.append("--run_doubletfinder") + if run_scrublet: + cmd.append("--run_scrublet") + if run_scdblfinder: + cmd.append("--run_scdblfinder") + + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + + # --- Output Handling --- + output_files = [str(f) for f in outdir.glob('**/*') if f.is_file()] + + expected_report = outdir / f"{sample}_sctk_qc_report.html" + if not expected_report.exists(): + logging.warning(f"Expected HTML report not found at: {expected_report}") + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + + except FileNotFoundError: + # This error occurs if 'Rscript' is not in the PATH + error_message = "Error: 'Rscript' command not found. Is R installed and 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"Command failed with exit code {e.returncode}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecelltk/app/bioconductor-singlecelltk_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecelltk/app/bioconductor-singlecelltk_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ee0e59414667c347c5ef4b65f259b1dc7309c3b6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecelltk/app/bioconductor-singlecelltk_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-singlecelltk/app/bioconductor-singlecelltk_server.py') +SERVER_NAME = 'biosci_bioconductor_singlecelltk' + + +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-singlecelltk/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecelltk/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecelltk/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecelltk/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecelltk/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d7ea82210b2b77ededee6f67405b85f12eb4d57c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecelltk/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-singlecelltk: + build: . + image: mcp-bioconductor-singlecelltk:latest + container_name: mcp-bioconductor-singlecelltk + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-singlecelltk + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-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-singlecelltk/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecelltk/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e5361294d45074b078e8a363b24ace4f54001829 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecelltk/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-singlecelltk + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecelltk/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecelltk/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecelltk/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoothclust/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoothclust/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..af0d18bfadbb9ce49b2c0c396674dc0edb2e779b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoothclust/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-smoothclust via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-smoothclust -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-smoothclust_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-smoothclust_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-smoothclust_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoothclust/app/bioconductor-smoothclust_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoothclust/app/bioconductor-smoothclust_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7ef8628222b6329c7ff3941be434734c87839001 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoothclust/app/bioconductor-smoothclust_server.py @@ -0,0 +1,233 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Dict, Any + +# NO NEED to import mcp as per instructions + +@mcp.tool() +def run_smoothclust_analysis( + input_spatial_experiment_path: Path, + output_spatial_experiment_path: Path, + output_plot_path: Path, + k_neighbors: int = 10, + smoothing_type: str = "knn", + n_clusters: int = 5, + clustering_method: str = "kmeans", + seed: Optional[int] = None, + r_path: str = "Rscript", +) -> Dict[str, Any]: + """ + Performs spatial domain identification and spatially-aware clustering using the bioconductor-smoothclust R package. + + This tool smooths gene expression profiles across neighboring spatial locations and then applies + unsupervised clustering to identify spatial domains with smooth boundaries. + + NOTE: The provided documentation for bioconductor-smoothclust describes an R package and its + purpose but does not detail a command-line interface or specific R function signatures. + Therefore, the parameters and the R script logic within this MCP tool are inferred based + on the package's description and common spatial transcriptomics analysis workflows. + The actual R function names and parameter names used in the generated R script are illustrative + and based on typical Bioconductor package usage patterns. + + Args: + input_spatial_experiment_path: Path to an RData file containing a SpatialExperiment object. + This object should contain gene expression data and spatial coordinates. + output_spatial_experiment_path: Path to save the resulting SpatialExperiment object, + which will include the clustering results. + output_plot_path: Path to save a visualization of the identified spatial domains. + (e.g., a PNG image). + k_neighbors: Number of nearest neighbors to use for spatial smoothing. + Must be a positive integer. + smoothing_type: Type of spatial smoothing to apply. + Valid options are "knn" (k-nearest neighbors) or "graph" (spatial graph). + n_clusters: The desired number of spatial domains (clusters) to identify. + Must be a positive integer. + clustering_method: The clustering algorithm to use. + Valid options are "kmeans" or "hclust" (hierarchical clustering). + seed: An optional random seed for reproducibility. If not provided, a random seed will be used. + r_path: Path to the Rscript executable. Defaults to "Rscript" assuming it's in PATH. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + + Raises: + ValueError: If input parameters are invalid. + subprocess.CalledProcessError: If the Rscript command fails. + RuntimeError: If the R script encounters a critical error. + """ + + # 1. Input Validation + if not input_spatial_experiment_path.is_file(): + raise ValueError(f"Input SpatialExperiment file not found: {input_spatial_experiment_path}") + if input_spatial_experiment_path.suffix.lower() not in [".rda", ".rdata"]: + raise ValueError(f"Input SpatialExperiment file must be an RData file (.rda or .rdata): {input_spatial_experiment_path}") + + if k_neighbors <= 0: + raise ValueError("k_neighbors must be a positive integer.") + if smoothing_type not in ["knn", "graph"]: + raise ValueError(f"Invalid smoothing_type: {smoothing_type}. Must be 'knn' or 'graph'.") + if n_clusters <= 0: + raise ValueError("n_clusters must be a positive integer.") + if clustering_method not in ["kmeans", "hclust"]: + raise ValueError(f"Invalid clustering_method: {clustering_method}. Must be 'kmeans' or 'hclust'.") + + # Ensure output directories exist + output_spatial_experiment_path.parent.mkdir(parents=True, exist_ok=True) + output_plot_path.parent.mkdir(parents=True, exist_ok=True) + + # 2. Prepare R script + # The R script is constructed based on the typical usage of Bioconductor packages + # and the described functionality of 'smoothclust'. + # Specific function names like 'smoothclust_workflow', 'smooth_expression', + # and 'cluster_spatial_domains' are inferred as they are not provided in the + # given documentation. + r_script_content = f""" + # Load necessary Bioconductor packages + suppressPackageStartupMessages({{ + library(smoothclust) + library(SpatialExperiment) + library(SummarizedExperiment) + library(ggplot2) # For plotting spatial domains + }}) + + # Set random seed for reproducibility if provided + seed_val <- {seed if seed is not None else 'NULL'} + if (!is.null(seed_val)) {{ + set.seed(seed_val) + }} + + # Define input and output paths + input_spe_path <- "{input_spatial_experiment_path.resolve()}" + output_spe_path <- "{output_spatial_experiment_path.resolve()}" + output_plot_path <- "{output_plot_path.resolve()}" + + # Load SpatialExperiment object + if (!file.exists(input_spe_path)) {{ + stop(paste0("Input SpatialExperiment file not found: ", input_spe_path)) + }} + + # List objects before loading to identify the new SpatialExperiment object + objects_before_load <- ls() + load(input_spe_path) + objects_after_load <- ls() + + # Find the SpatialExperiment object that was just loaded + new_objects <- setdiff(objects_after_load, objects_before_load) + spe <- NULL + for (obj_name in new_objects) {{ + if (inherits(get(obj_name), "SpatialExperiment")) {{ + spe <- get(obj_name) + message(paste0("Found SpatialExperiment object named '", obj_name, "'.")) + break + }} + }} + + if (is.null(spe)) {{ + stop("No 'SpatialExperiment' object found in the input RData file.") + }} + + message("Starting smoothclust analysis workflow...") + tryCatch({{ + # Attempt to use a hypothetical smoothclust_workflow function if it exists + # This is the most direct way if the package provides an integrated workflow. + if (exists("smoothclust_workflow") && is.function(smoothclust_workflow)) {{ + spe <- smoothclust_workflow( + spe, + k = {k_neighbors}, + n_clusters = {n_clusters}, + type = "{smoothing_type}", + method = "{clustering_method}" + ) + }} else if (exists("smooth_expression") && is.function(smooth_expression) && + exists("cluster_spatial_domains") && is.function(cluster_spatial_domains)) {{ + # If a workflow function is not found, try sequential calls + message("smoothclust_workflow not found, attempting sequential smooth_expression and cluster_spatial_domains.") + spe <- smooth_expression(spe, k = {k_neighbors}, type = "{smoothing_type}") + spe <- cluster_spatial_domains(spe, n_clusters = {n_clusters}, method = "{clustering_method}") + }} else {{ + stop("Could not find expected smoothclust functions (smoothclust_workflow or smooth_expression/cluster_spatial_domains).") + }} + }}, error = function(e) {{ + stop(paste0("Error during smoothclust analysis: ", e$message)) + }}) + + message("Spatial clustering complete.") + + # Save the updated SpatialExperiment object + save(spe, file = output_spe_path) + message(paste0("Updated SpatialExperiment object saved to: ", output_spe_path)) + + # Generate and save a plot of spatial domains + # This assumes a 'spatial_domains' column is added to colData(spe) by smoothclust + if ("spatial_domains" %in% colnames(colData(spe))) {{ + message("Generating spatial domains plot...") + + # Extract spatial coordinates and domain assignments + spatial_coords <- spatialCoords(spe) + plot_data <- data.frame( + x = spatial_coords[,1], + y = spatial_coords[,2], + domain = colData(spe)$spatial_domains + ) + + # Create ggplot object + p <- ggplot(plot_data, aes(x = x, y = y, color = factor(domain))) + + geom_point(size = 1, alpha = 0.8) + + theme_minimal() + + labs(title = "Spatial Domains Identified by smoothclust", + color = "Domain", + x = "Spatial Coordinate X", + y = "Spatial Coordinate Y") + + coord_fixed() # Maintain aspect ratio for spatial plots + + # Save the plot + ggsave(output_plot_path, plot = p, width = 8, height = 7, units = "in") + message(paste0("Spatial domains plot saved to: ", output_plot_path)) + }} else {{ + warning("No 'spatial_domains' column found in colData(spe). Skipping plot generation.") + }} + """ + + # 3. Execute R script + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".R") as tmp_r_script: + tmp_r_script.write(r_script_content) + tmp_r_script_path = Path(tmp_r_script.name) + + command = [r_path, str(tmp_r_script_path)] + command_executed = " ".join(command) + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + encoding="utf-8" + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + # Clean up temp file on error + tmp_r_script_path.unlink(missing_ok=True) + raise RuntimeError( + f"Rscript command failed with exit code {e.returncode}.\n" + f"Command: {e.cmd}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) from e + finally: + # Clean up temporary R script + tmp_r_script_path.unlink(missing_ok=True) + + # 4. Return structured output + output_files = [str(output_spatial_experiment_path.resolve())] + if output_plot_path.exists(): + output_files.append(str(output_plot_path.resolve())) + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoothclust/app/bioconductor-smoothclust_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoothclust/app/bioconductor-smoothclust_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..afd4028fe6c443a557a5713960006fe6b3723fca --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoothclust/app/bioconductor-smoothclust_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-smoothclust/app/bioconductor-smoothclust_server.py') +SERVER_NAME = 'biosci_bioconductor_smoothclust' + + +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-smoothclust/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoothclust/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoothclust/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoothclust/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoothclust/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..4e92c9336fbd161707ba16e39bbc01bba9dd47b0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoothclust/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-smoothclust: + build: . + image: mcp-bioconductor-smoothclust:latest + container_name: mcp-bioconductor-smoothclust + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-smoothclust + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoothclust/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoothclust/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2d5df1756427dc4ca1e3c6a3c771f49e98bf027a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoothclust/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-smoothclust + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoothclust/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoothclust/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoothclust/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoppix/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoppix/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..dcfd2d063689b187f49eae4f7660b5c9df6a11b4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoppix/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-smoppix via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-smoppix -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-smoppix_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-smoppix_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-smoppix_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoppix/app/bioconductor-smoppix_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoppix/app/bioconductor-smoppix_server.py new file mode 100644 index 0000000000000000000000000000000000000000..09ef297ddbee3cc0df5e00d934bca33aea37afce --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoppix/app/bioconductor-smoppix_server.py @@ -0,0 +1,393 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# MCP decorator is not imported as per instructions. +# It is assumed to be available in the execution environment. + +def _create_r_script_runner( + r_script_content: str, + tool_name: str +) -> dict: + """ + A helper function to run an R script and handle subprocess execution. + + Args: + r_script_content: The string content of the R script to be executed. + tool_name: The name of the calling tool for error reporting. + + Returns: + A dictionary containing the command, stdout, and stderr. + """ + 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: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True + ) + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"{tool_name} failed with exit code {e.returncode}.\n" + f"Command: {e.cmd}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) from e + finally: + Path(script_path).unlink() + +def _prepare_r_script_header( + molecule_data: Path, + cell_boundaries: Path +) -> str: + """ + Generates the R script header for loading data and creating the SpatialExperiment object. + """ + return f""" + # Load required libraries + suppressPackageStartupMessages(library(smoppix)) + suppressPackageStartupMessages(library(SpatialExperiment)) + + # Read input data + molecules_df <- read.csv("{molecule_data.resolve()}", header=TRUE, stringsAsFactors=TRUE) + boundaries_df <- read.csv("{cell_boundaries.resolve()}", header=TRUE, stringsAsFactors=TRUE) + + # Create a list of polygons for cell boundaries + # This assumes the boundaries_df has columns: cell_id, x, y + boundary_list <- lapply(split(boundaries_df, boundaries_df$cell_id), function(df) {{ + list(as.matrix(df[,c('x', 'y')])) + }}) + + # Use the prepare_smoppix helper function to create the SpatialExperiment object + spe <- prepare_smoppix( + coords = as.matrix(molecules_df[,c('x', 'y')]), + molecules = molecules_df$molecule_name, + image_id = molecules_df$image_id, + cell_id = molecules_df$cell_id, + boundaries = boundary_list + ) + """ + +# @mcp.tool() +def aggregate( + molecule_data: Path, + cell_boundaries: Path, + g: str, + r_max: float, + output_file: Path, + n_perm: int = 1000, + n_cores: int = 1, + covariates: Optional[str] = None, + random_effects: Optional[str] = None, + verbose: bool = True, +) -> dict: + """ + Test for aggregation (clustering) of a single molecule species using smoppix. + + Args: + molecule_data: Path to a CSV file containing molecule information. + Required columns: 'x', 'y', 'molecule_name', 'image_id', 'cell_id'. + cell_boundaries: Path to a CSV file defining cell boundaries. + Required columns: 'cell_id', 'x', 'y'. Vertices for each + cell must be ordered to form a polygon. + g: The name of the molecule species to test for aggregation. + r_max: The maximum radius to consider for the aggregation test. + output_file: Path to save the output results CSV file. + n_perm: The number of permutations to perform for the test. + n_cores: The number of CPU cores to use for parallel processing. + covariates: An R formula string for fixed effect covariates (e.g., "~ age + sex"). + random_effects: An R formula string for random effect covariates (e.g., "~ (1|donor)"). + verbose: If True, print progress messages during execution. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output file path. + """ + # Input validation + if not molecule_data.exists(): + raise FileNotFoundError(f"Input file not found: {molecule_data}") + if not cell_boundaries.exists(): + raise FileNotFoundError(f"Input file not found: {cell_boundaries}") + if n_perm <= 0: + raise ValueError("n_perm must be a positive integer.") + if n_cores <= 0: + raise ValueError("n_cores must be a positive integer.") + if r_max <= 0: + raise ValueError("r_max must be a positive number.") + + r_script_header = _prepare_r_script_header(molecule_data, cell_boundaries) + + r_script_content = f""" + {r_script_header} + + # Run the aggregation analysis + results <- smoppix::aggregate( + object = spe, + g = "{g}", + r_max = {r_max}, + n_perm = {n_perm}, + n_cores = {n_cores}, + covariates = {f'as.formula("{covariates}")' if covariates else 'NULL'}, + random_effects = {f'as.formula("{random_effects}")' if random_effects else 'NULL'}, + verbose = {'TRUE' if verbose else 'FALSE'} + ) + + # Save results + write.csv(results, file="{output_file.resolve()}", row.names=FALSE) + """ + + execution_result = _create_r_script_runner(r_script_content, "aggregate") + execution_result["output_files"] = [str(output_file.resolve())] + return execution_result + +# @mcp.tool() +def coloc( + molecule_data: Path, + cell_boundaries: Path, + g_coloc: str, + g_ref: str, + output_file: Path, + method: str = "perm", + r_max: Optional[float] = None, + n_perm: int = 1000, + n_cores: int = 1, + covariates: Optional[str] = None, + interactions: Optional[str] = None, + random_effects: Optional[str] = None, + verbose: bool = True, +) -> dict: + """ + Test for colocalization between two molecule species using smoppix. + + Args: + molecule_data: Path to a CSV file containing molecule information. + Required columns: 'x', 'y', 'molecule_name', 'image_id', 'cell_id'. + cell_boundaries: Path to a CSV file defining cell boundaries. + Required columns: 'cell_id', 'x', 'y'. + g_coloc: The name of the first molecule species. + g_ref: The name of the second (reference) molecule species. + output_file: Path to save the output results CSV file. + method: The method for the colocalization test. Must be 'perm' or 'dist'. + r_max: The maximum radius, required only if method is 'dist'. + n_perm: The number of permutations to perform for the test. + n_cores: The number of CPU cores to use for parallel processing. + covariates: An R formula string for fixed effect covariates. + interactions: An R formula string for interaction terms. + random_effects: An R formula string for random effect covariates. + verbose: If True, print progress messages during execution. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output file path. + """ + # Input validation + if not molecule_data.exists(): + raise FileNotFoundError(f"Input file not found: {molecule_data}") + if not cell_boundaries.exists(): + raise FileNotFoundError(f"Input file not found: {cell_boundaries}") + if method not in ["perm", "dist"]: + raise ValueError("method must be either 'perm' or 'dist'.") + if method == "dist" and r_max is None: + raise ValueError("r_max must be provided when method is 'dist'.") + if r_max is not None and r_max <= 0: + raise ValueError("r_max must be a positive number.") + if n_perm <= 0: + raise ValueError("n_perm must be a positive integer.") + if n_cores <= 0: + raise ValueError("n_cores must be a positive integer.") + + r_script_header = _prepare_r_script_header(molecule_data, cell_boundaries) + + r_script_content = f""" + {r_script_header} + + # Run the colocalization analysis + results <- smoppix::coloc( + object = spe, + g_coloc = "{g_coloc}", + g_ref = "{g_ref}", + method = "{method}", + r_max = {r_max if r_max is not None else 'NULL'}, + n_perm = {n_perm}, + n_cores = {n_cores}, + covariates = {f'as.formula("{covariates}")' if covariates else 'NULL'}, + interactions = {f'as.formula("{interactions}")' if interactions else 'NULL'}, + random_effects = {f'as.formula("{random_effects}")' if random_effects else 'NULL'}, + verbose = {'TRUE' if verbose else 'FALSE'} + ) + + # Save results + write.csv(results, file="{output_file.resolve()}", row.names=FALSE) + """ + + execution_result = _create_r_script_runner(r_script_content, "coloc") + execution_result["output_files"] = [str(output_file.resolve())] + return execution_result + +# @mcp.tool() +def gradient( + molecule_data: Path, + cell_boundaries: Path, + g: str, + output_file: Path, + direction: str = "x", + n_perm: int = 1000, + n_cores: int = 1, + covariates: Optional[str] = None, + interactions: Optional[str] = None, + random_effects: Optional[str] = None, + verbose: bool = True, +) -> dict: + """ + Test for a spatial gradient in molecule density using smoppix. + + Args: + molecule_data: Path to a CSV file containing molecule information. + Required columns: 'x', 'y', 'molecule_name', 'image_id', 'cell_id'. + cell_boundaries: Path to a CSV file defining cell boundaries. + Required columns: 'cell_id', 'x', 'y'. + g: The name of the molecule species to test. + output_file: Path to save the output results CSV file. + direction: The direction of the gradient. Can be 'x', 'y', or a numeric angle in radians. + n_perm: The number of permutations to perform for the test. + n_cores: The number of CPU cores to use for parallel processing. + covariates: An R formula string for fixed effect covariates. + interactions: An R formula string for interaction terms. + random_effects: An R formula string for random effect covariates. + verbose: If True, print progress messages during execution. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output file path. + """ + # Input validation + if not molecule_data.exists(): + raise FileNotFoundError(f"Input file not found: {molecule_data}") + if not cell_boundaries.exists(): + raise FileNotFoundError(f"Input file not found: {cell_boundaries}") + if n_perm <= 0: + raise ValueError("n_perm must be a positive integer.") + if n_cores <= 0: + raise ValueError("n_cores must be a positive integer.") + + r_direction = f'"{direction}"' + if direction not in ["x", "y"]: + try: + float(direction) + r_direction = direction # Pass as a number + except ValueError: + raise ValueError("direction must be 'x', 'y', or a numeric value.") + + r_script_header = _prepare_r_script_header(molecule_data, cell_boundaries) + + r_script_content = f""" + {r_script_header} + + # Run the gradient analysis + results <- smoppix::gradient( + object = spe, + g = "{g}", + direction = {r_direction}, + n_perm = {n_perm}, + n_cores = {n_cores}, + covariates = {f'as.formula("{covariates}")' if covariates else 'NULL'}, + interactions = {f'as.formula("{interactions}")' if interactions else 'NULL'}, + random_effects = {f'as.formula("{random_effects}")' if random_effects else 'NULL'}, + verbose = {'TRUE' if verbose else 'FALSE'} + ) + + # Save results + write.csv(results, file="{output_file.resolve()}", row.names=FALSE) + """ + + execution_result = _create_r_script_runner(r_script_content, "gradient") + execution_result["output_files"] = [str(output_file.resolve())] + return execution_result + +# @mcp.tool() +def vicinity( + molecule_data: Path, + cell_boundaries: Path, + g: str, + r_max: float, + output_file: Path, + type: str = "edge", + n_perm: int = 1000, + n_cores: int = 1, + covariates: Optional[str] = None, + interactions: Optional[str] = None, + random_effects: Optional[str] = None, + verbose: bool = True, +) -> dict: + """ + Test for molecule enrichment/depletion near a reference structure using smoppix. + + Args: + molecule_data: Path to a CSV file containing molecule information. + Required columns: 'x', 'y', 'molecule_name', 'image_id', 'cell_id'. + cell_boundaries: Path to a CSV file defining cell boundaries. + Required columns: 'cell_id', 'x', 'y'. + g: The name of the molecule species to test. + r_max: The maximum radius to consider for the vicinity test. + output_file: Path to save the output results CSV file. + type: The type of vicinity test. Must be 'edge' or 'centroid'. + n_perm: The number of permutations to perform for the test. + n_cores: The number of CPU cores to use for parallel processing. + covariates: An R formula string for fixed effect covariates. + interactions: An R formula string for interaction terms. + random_effects: An R formula string for random effect covariates. + verbose: If True, print progress messages during execution. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output file path. + """ + # Input validation + if not molecule_data.exists(): + raise FileNotFoundError(f"Input file not found: {molecule_data}") + if not cell_boundaries.exists(): + raise FileNotFoundError(f"Input file not found: {cell_boundaries}") + if type not in ["edge", "centroid"]: + raise ValueError("type must be either 'edge' or 'centroid'.") + if r_max <= 0: + raise ValueError("r_max must be a positive number.") + if n_perm <= 0: + raise ValueError("n_perm must be a positive integer.") + if n_cores <= 0: + raise ValueError("n_cores must be a positive integer.") + + r_script_header = _prepare_r_script_header(molecule_data, cell_boundaries) + + r_script_content = f""" + {r_script_header} + + # Run the vicinity analysis + results <- smoppix::vicinity( + object = spe, + g = "{g}", + type = "{type}", + r_max = {r_max}, + n_perm = {n_perm}, + n_cores = {n_cores}, + covariates = {f'as.formula("{covariates}")' if covariates else 'NULL'}, + interactions = {f'as.formula("{interactions}")' if interactions else 'NULL'}, + random_effects = {f'as.formula("{random_effects}")' if random_effects else 'NULL'}, + verbose = {'TRUE' if verbose else 'FALSE'} + ) + + # Save results + write.csv(results, file="{output_file.resolve()}", row.names=FALSE) + """ + + execution_result = _create_r_script_runner(r_script_content, "vicinity") + execution_result["output_files"] = [str(output_file.resolve())] + return execution_result \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoppix/app/bioconductor-smoppix_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoppix/app/bioconductor-smoppix_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4c7b2ffe1f26bc0bd6343395908fcac6a1e5b1fe --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoppix/app/bioconductor-smoppix_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-smoppix/app/bioconductor-smoppix_server.py') +SERVER_NAME = 'biosci_bioconductor_smoppix' + + +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-smoppix/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoppix/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoppix/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoppix/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoppix/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b5562dc6654f584c7cf609f3a94015453c6d2575 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoppix/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-smoppix: + build: . + image: mcp-bioconductor-smoppix:latest + container_name: mcp-bioconductor-smoppix + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-smoppix + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoppix/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoppix/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e600b2495c03e14f646ed4c274f6e1c09292f831 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoppix/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-smoppix + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoppix/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoppix/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-smoppix/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sosta/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sosta/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..252aa9ad176b0ea229c689ded7d39b073d0ddce8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sosta/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-sosta via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-sosta -y && conda clean -a + +# 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-sosta_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-sosta_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-sosta_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sosta/app/bioconductor-sosta_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sosta/app/bioconductor-sosta_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7beb66225e6c43959b9981f1e5658c0d5e9943a0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sosta/app/bioconductor-sosta_server.py @@ -0,0 +1,350 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any + +# @mcp.tool() decorator is commented out as per instructions +# but would be present in a real MCP environment. + + +# @mcp.tool() +def find_structure( + spe_input_file: Path, + output_spe_file: Path, + feature_col: str, + img_id: str = "sample_id", + threshold: Optional[float] = None, + k_geom: int = 10, + min_area: int = 100, + max_area: Optional[float] = None, + shape_factor: float = 0.0, + smooth_radius: int = 0, +) -> Dict[str, Any]: + """ + Identifies and reconstructs anatomical structures from spatial omics data. + + This tool wraps the findStructure() function from the R/Bioconductor package 'sosta'. + It takes a SpatialExperiment object (as an .rds file), identifies structures based on a specified feature, + and saves the modified SpatialExperiment object with structure information to a new .rds file. + + Args: + spe_input_file: Path to the input SpatialExperiment object saved as an .rds file. + output_spe_file: Path to save the output SpatialExperiment object as an .rds file. + feature_col: The column name in colData(x) to be used for structure identification. + img_id: The column name in colData(x) that contains the image ID. + threshold: A numeric threshold for binarizing the feature values. If NULL (default), Otsu's method is used. + k_geom: The number of nearest neighbors to consider for the geometric graph. + min_area: The minimum area (number of spots/cells) for a structure to be retained. + max_area: The maximum area for a structure to be retained. Defaults to Inf (no limit). + shape_factor: A shape factor threshold (between 0 and 1) for filtering structures. + Structures with a shape factor below this value are removed. 0 means no filtering. + smooth_radius: The radius for smoothing the structure outlines, in pixels. 0 means no smoothing. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # Input validation + if not spe_input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {spe_input_file}") + if k_geom <= 0: + raise ValueError("k_geom must be a positive integer.") + if min_area < 0: + raise ValueError("min_area must be a non-negative integer.") + if max_area is not None and max_area < min_area: + raise ValueError("max_area must be greater than or equal to min_area.") + if not (0.0 <= shape_factor <= 1.0): + raise ValueError("shape_factor must be between 0.0 and 1.0.") + if smooth_radius < 0: + raise ValueError("smooth_radius must be a non-negative integer.") + + # R script generation + r_script_content = f""" + library(sosta) + library(SpatialExperiment) + + # Load input object + spe <- readRDS('{spe_input_file}') + + # Handle optional parameters + threshold_val <- {'NULL' if threshold is None else threshold} + max_area_val <- {'Inf' if max_area is None else max_area} + + # Run findStructure + spe <- findStructure( + spe, + feature_col = '{feature_col}', + threshold = threshold_val, + k_geom = {k_geom}, + min_area = {min_area}, + max_area = max_area_val, + shape_factor = {shape_factor}, + smooth_radius = {smooth_radius}, + img_id = '{img_id}' + ) + + # Save the output object + saveRDS(spe, file = '{output_spe_file}') + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_script: + tmp_script.write(r_script_content) + script_path = tmp_script.name + + cmd = ["Rscript", script_path] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_spe_file)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Sosta find_structure script failed.", + "return_code": e.returncode + } + finally: + Path(script_path).unlink() + + +# @mcp.tool() +def get_structure_metrics( + spe_input_file: Path, + output_spe_file: Path, + structure_id: str = "structure_id", + img_id: str = "sample_id", +) -> Dict[str, Any]: + """ + Calculates various metrics for each identified structure. + + This tool wraps the getStructureMetrics() function from 'sosta'. It computes metrics + such as area, perimeter, and shape factor for each structure found in the + SpatialExperiment object and adds them to the object's metadata. + + Args: + spe_input_file: Path to an .rds file containing a SpatialExperiment object with identified structures. + output_spe_file: Path to save the modified SpatialExperiment object as an .rds file. + structure_id: The column name in colData(x) that contains the structure ID. + img_id: The column name in colData(x) that contains the image ID. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + if not spe_input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {spe_input_file}") + + r_script_content = f""" + library(sosta) + library(SpatialExperiment) + + spe <- readRDS('{spe_input_file}') + + spe <- getStructureMetrics( + spe, + structure_id = '{structure_id}', + img_id = '{img_id}' + ) + + saveRDS(spe, file = '{output_spe_file}') + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_script: + tmp_script.write(r_script_content) + script_path = tmp_script.name + + cmd = ["Rscript", script_path] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_spe_file)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Sosta get_structure_metrics script failed.", + "return_code": e.returncode + } + finally: + Path(script_path).unlink() + + +# @mcp.tool() +def find_structure_neighbors( + spe_input_file: Path, + output_spe_file: Path, + k_neighbors: int = 5, + structure_id: str = "structure_id", + img_id: str = "sample_id", +) -> Dict[str, Any]: + """ + Identifies the neighboring structures for each structure. + + This tool wraps the findStructureNeighbors() function from 'sosta'. It finds a specified + number of nearest neighboring structures for each structure and stores this information. + + Args: + spe_input_file: Path to an .rds file containing a SpatialExperiment object with identified structures. + output_spe_file: Path to save the modified SpatialExperiment object as an .rds file. + k_neighbors: The number of nearest neighbors to find for each structure. + structure_id: The column name in colData(x) that contains the structure ID. + img_id: The column name in colData(x) that contains the image ID. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + if not spe_input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {spe_input_file}") + if k_neighbors <= 0: + raise ValueError("k_neighbors must be a positive integer.") + + r_script_content = f""" + library(sosta) + library(SpatialExperiment) + + spe <- readRDS('{spe_input_file}') + + spe <- findStructureNeighbors( + spe, + structure_id = '{structure_id}', + img_id = '{img_id}', + k_neighbors = {k_neighbors} + ) + + saveRDS(spe, file = '{output_spe_file}') + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_script: + tmp_script.write(r_script_content) + script_path = tmp_script.name + + cmd = ["Rscript", script_path] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_spe_file)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Sosta find_structure_neighbors script failed.", + "return_code": e.returncode + } + finally: + Path(script_path).unlink() + + +# @mcp.tool() +def get_structure_aggregated_expression( + spe_input_file: Path, + output_sce_file: Path, + assay_name: str = "counts", + aggregation_function: str = "mean", + structure_id: str = "structure_id", + img_id: str = "sample_id", +) -> Dict[str, Any]: + """ + Aggregates expression data for each identified structure. + + This tool wraps the getStructureAgg() function from 'sosta'. It aggregates the expression + data (e.g., counts) for all spots/cells within each structure using a specified function + (mean or sum) and returns a SingleCellExperiment object. + + Args: + spe_input_file: Path to an .rds file containing a SpatialExperiment object with structures. + output_sce_file: Path to save the output SingleCellExperiment object as an .rds file. + assay_name: The name of the assay in the input object to use for aggregation. + aggregation_function: The function to use for aggregation. Must be 'mean' or 'sum'. + structure_id: The column name in colData(x) that contains the structure ID. + img_id: The column name in colData(x) that contains the image ID. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + if not spe_input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {spe_input_file}") + if aggregation_function not in ["mean", "sum"]: + raise ValueError("aggregation_function must be either 'mean' or 'sum'.") + + r_script_content = f""" + library(sosta) + library(SpatialExperiment) + library(SingleCellExperiment) + + spe <- readRDS('{spe_input_file}') + + sce_agg <- getStructureAgg( + spe, + assay_name = '{assay_name}', + structure_id = '{structure_id}', + img_id = '{img_id}', + fun = '{aggregation_function}' + ) + + saveRDS(sce_agg, file = '{output_sce_file}') + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_script: + tmp_script.write(r_script_content) + script_path = tmp_script.name + + cmd = ["Rscript", script_path] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_sce_file)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Sosta get_structure_aggregated_expression script failed.", + "return_code": e.returncode + } + finally: + Path(script_path).unlink() \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sosta/app/bioconductor-sosta_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sosta/app/bioconductor-sosta_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..90511bb6d8f219c6cfe5cc44bf83c3468dd607e2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sosta/app/bioconductor-sosta_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-sosta/app/bioconductor-sosta_server.py') +SERVER_NAME = 'biosci_bioconductor_sosta' + + +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-sosta/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sosta/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sosta/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sosta/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sosta/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..76166879ead7de811bc2838aa522b878cfe29280 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sosta/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-sosta: + build: . + image: mcp-bioconductor-sosta:latest + container_name: mcp-bioconductor-sosta + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-sosta + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-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-sosta/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sosta/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ddbe307524a852455960999d28933074673d6d20 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sosta/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-sosta + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sosta/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sosta/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sosta/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacetrooper/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacetrooper/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f723bb954274e39466224af0e0cb709f767fb2a9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacetrooper/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-spacetrooper via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-spacetrooper -y && conda clean -a + +# 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-spacetrooper_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-spacetrooper_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-spacetrooper_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacetrooper/app/bioconductor-spacetrooper_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacetrooper/app/bioconductor-spacetrooper_server.py new file mode 100644 index 0000000000000000000000000000000000000000..553dd36a27b18fd7f2fac68a4b72ae27fd0dac99 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacetrooper/app/bioconductor-spacetrooper_server.py @@ -0,0 +1,280 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +@mcp.tool() +def spacetrooper_deconvolve( + spe_path: str, + reference_path: str, + output_path: str, + n_iter: int = 1000, + n_burnin: int = 500, + n_chains: int = 1, + interactions: bool = True, + alpha: float = 1.0, + beta: float = 1.0, +) -> Dict[str, Any]: + """ + Perform spatial deconvolution using the spacetrooper Bayesian model. + + Args: + spe_path: Path to the input SpatialExperiment object (RDS format). + reference_path: Path to the reference scRNA-seq data (RDS format). + output_path: Path where the resulting spacetrooper object will be saved (RDS format). + n_iter: Number of MCMC iterations. + n_burnin: Number of burn-in iterations. + n_chains: Number of MCMC chains to run. + interactions: Whether to model spatial interactions between cell types. + alpha: Hyperparameter for the Dirichlet prior on cell type proportions. + beta: Hyperparameter for the spatial interaction terms. + """ + # Input validation + spe_file = Path(spe_path) + ref_file = Path(reference_path) + out_file = Path(output_path) + + if not spe_file.exists(): + raise FileNotFoundError(f"SpatialExperiment file not found: {spe_path}") + if not ref_file.exists(): + raise FileNotFoundError(f"Reference file not found: {reference_path}") + + if n_iter <= 0 or n_burnin < 0: + raise ValueError("n_iter must be positive and n_burnin must be non-negative.") + if n_iter <= n_burnin: + raise ValueError("n_iter must be greater than n_burnin.") + + # Construct R command + interactions_r = "TRUE" if interactions else "FALSE" + r_script = f""" + library(spacetrooper) + spe <- readRDS('{spe_path}') + ref <- readRDS('{reference_path}') + + results <- spacetrooper( + spe = spe, + reference = ref, + n_iter = {n_iter}, + n_burnin = {n_burnin}, + n_chains = {n_chains}, + interactions = {interactions_r}, + alpha = {alpha}, + beta = {beta} + ) + + saveRDS(results, '{output_path}') + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"spacetrooper::spacetrooper(n_iter={n_iter}, ...)", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(out_file)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd + } + +@mcp.tool() +def spacetrooper_extract_weights( + results_path: str, + output_csv: str, + summary_stat: str = "mean" +) -> Dict[str, Any]: + """ + Extract cell type proportion weights from a spacetrooper results object. + + Args: + results_path: Path to the spacetrooper results RDS file. + output_csv: Path to save the extracted weights as a CSV file. + summary_stat: Statistic to use for weights ('mean', 'median', or 'mode'). + """ + res_file = Path(results_path) + if not res_file.exists(): + raise FileNotFoundError(f"Results file not found: {results_path}") + + if summary_stat not in ["mean", "median", "mode"]: + raise ValueError("summary_stat must be one of: 'mean', 'median', 'mode'") + + r_script = f""" + library(spacetrooper) + res <- readRDS('{results_path}') + weights <- get_weights(res, stat = '{summary_stat}') + write.csv(weights, '{output_csv}', row.names = TRUE) + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"spacetrooper::get_weights(stat='{summary_stat}')", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [output_csv] + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to extract weights", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def spacetrooper_plot_spatial_weights( + results_path: str, + output_plot: str, + cell_type: Optional[str] = None, + point_size: float = 1.5, + colorscale: str = "viridis" +) -> Dict[str, Any]: + """ + Generate spatial plots of cell type weights. + + Args: + results_path: Path to the spacetrooper results RDS file. + output_plot: Path to save the plot (e.g., .png, .pdf). + cell_type: Specific cell type to plot. If None, plots all major types. + point_size: Size of the spots in the spatial plot. + colorscale: R color palette to use. + """ + res_file = Path(results_path) + if not res_file.exists(): + raise FileNotFoundError(f"Results file not found: {results_path}") + + cell_type_arg = f"'{cell_type}'" if cell_type else "NULL" + + r_script = f""" + library(spacetrooper) + library(ggplot2) + res <- readRDS('{results_path}') + p <- plot_weights(res, cell_type = {cell_type_arg}, point_size = {point_size}) + + scale_fill_viridis_c(option = '{colorscale}') + + ggsave('{output_plot}', plot = p, width = 10, height = 8) + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "spacetrooper::plot_weights()", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [output_plot] + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to generate plot", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def spacetrooper_compute_interactions( + results_path: str, + output_csv: str, + prob_threshold: float = 0.95 +) -> Dict[str, Any]: + """ + Compute and extract significant spatial interactions between cell types. + + Args: + results_path: Path to the spacetrooper results RDS file. + output_csv: Path to save the interaction matrix/list. + prob_threshold: Posterior probability threshold for significance. + """ + res_file = Path(results_path) + if not res_file.exists(): + raise FileNotFoundError(f"Results file not found: {results_path}") + + if not (0 <= prob_threshold <= 1): + raise ValueError("prob_threshold must be between 0 and 1.") + + r_script = f""" + library(spacetrooper) + res <- readRDS('{results_path}') + interactions <- get_interactions(res, threshold = {prob_threshold}) + write.csv(interactions, '{output_csv}', row.names = TRUE) + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"spacetrooper::get_interactions(threshold={prob_threshold})", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [output_csv] + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to compute interactions", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def spacetrooper_check_convergence( + results_path: str, + output_plot: str +) -> Dict[str, Any]: + """ + Generate diagnostic plots to check MCMC convergence (trace plots). + + Args: + results_path: Path to the spacetrooper results RDS file. + output_plot: Path to save the diagnostic plot. + """ + res_file = Path(results_path) + if not res_file.exists(): + raise FileNotFoundError(f"Results file not found: {results_path}") + + r_script = f""" + library(spacetrooper) + library(ggplot2) + res <- readRDS('{results_path}') + p <- plot_convergence(res) + ggsave('{output_plot}', plot = p, width = 12, height = 10) + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "spacetrooper::plot_convergence()", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [output_plot] + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to generate convergence plots", + "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-spacetrooper/app/bioconductor-spacetrooper_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacetrooper/app/bioconductor-spacetrooper_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..cb261d397ee5dc21d37487d7e47bb73d45224740 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacetrooper/app/bioconductor-spacetrooper_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-spacetrooper/app/bioconductor-spacetrooper_server.py') +SERVER_NAME = 'biosci_bioconductor_spacetrooper' + + +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-spacetrooper/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacetrooper/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacetrooper/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacetrooper/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacetrooper/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e520262603580702d9ded9e960c50dc9955e9c81 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacetrooper/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-spacetrooper: + build: . + image: mcp-bioconductor-spacetrooper:latest + container_name: mcp-bioconductor-spacetrooper + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-spacetrooper + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-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-spacetrooper/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacetrooper/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d13143d2e6f39fd174a35176490a38513e71b479 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacetrooper/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-spacetrooper + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacetrooper/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacetrooper/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacetrooper/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacexr/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacexr/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9093d28fc95b51a037076a7bc2855825db8c3661 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacexr/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-spacexr via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-spacexr -y && conda clean -a + +# 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-spacexr_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-spacexr_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-spacexr_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacexr/app/bioconductor-spacexr_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacexr/app/bioconductor-spacexr_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f4c3f50775a0d947e12f292f691fe5b1f8faf43c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacexr/app/bioconductor-spacexr_server.py @@ -0,0 +1,192 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Literal, Optional + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be imported. +def tool(func): + """A dummy decorator to allow the code to be syntactically correct.""" + return func + +mcp = type("mcp", (), {"tool": tool}) + +@mcp.tool +def run_rctd( + spatial_data_rds: Path, + sc_reference_data_rds: Path, + cell_type_colname: str, + output_dir: Path, + mode: Literal["full", "doublet", "multi"] = "full", + max_cores: int = 1, + gene_cutoff: float = 0.000125, + fc_cutoff: float = 0.5, + n_genes: int = 2000, + cell_min_instance: int = 25, +) -> dict: + """ + Runs Robust Cell Type Decomposition (RCTD) to identify cell types in spatial transcriptomics data. + + This tool uses the spacexr R package to learn cell type profiles from an annotated + single-cell RNA-seq reference and uses these profiles to deconvolve the cell type + composition of each pixel/spot in a spatial transcriptomics dataset. + + Args: + spatial_data_rds: Path to an .rds file containing a SpatialExperiment object for the spatial data. + sc_reference_data_rds: Path to an .rds file containing a SummarizedExperiment or SingleCellExperiment + object for the single-cell reference data. + cell_type_colname: The name of the column in the reference object's colData that contains cell type annotations. + output_dir: Path to the directory where output files will be saved. + mode: The mode for running RCTD. 'full' assumes a single cell type per spot. + 'doublet' allows up to two cell types per spot. 'multi' allows multiple cell types. + Defaults to "full". + max_cores: The maximum number of cores to use for parallel processing. Defaults to 1. + gene_cutoff: The minimum proportion of cells that must express a gene for it to be included + in the reference. Used for gene filtering. Defaults to 0.000125. + fc_cutoff: The minimum log-fold-change of a gene to be considered a marker gene. + Used for gene filtering. Defaults to 0.5. + n_genes: The number of marker genes to be selected for each cell type in the reference. + Defaults to 2000. + cell_min_instance: The minimum number of cells required for a cell type to be included + in the reference. Defaults to 25. + + Returns: + A dictionary containing the execution command, stdout, stderr, and paths to output files. + """ + # 1. Input Validation + if not spatial_data_rds.exists(): + raise FileNotFoundError(f"Input spatial data file not found: {spatial_data_rds}") + if not sc_reference_data_rds.exists(): + raise FileNotFoundError(f"Input scRNA-seq reference file not found: {sc_reference_data_rds}") + if max_cores < 1: + raise ValueError("max_cores must be a positive integer.") + if gene_cutoff < 0: + raise ValueError("gene_cutoff must be non-negative.") + if fc_cutoff < 0: + raise ValueError("fc_cutoff must be non-negative.") + if n_genes <= 0: + raise ValueError("n_genes must be a positive integer.") + if cell_min_instance <= 0: + raise ValueError("cell_min_instance must be a positive integer.") + + output_dir.mkdir(parents=True, exist_ok=True) + + # 2. R Script Generation + # This script loads the data, creates the necessary spacexr objects, runs RCTD, and saves the results. + r_script_content = f""" + # Load required libraries + library(spacexr) + library(SpatialExperiment) + library(SummarizedExperiment) + library(ggplot2) + library(scatterpie) + library(Matrix) + + # --- 1. Load Data --- + puck_spe <- readRDS("{spatial_data_rds.resolve()}") + ref_se <- readRDS("{sc_reference_data_rds.resolve()}") + output_dir <- "{output_dir.resolve()}" + cell_type_colname <- "{cell_type_colname}" + + # --- 2. Create Reference Object --- + message("Creating reference object from single-cell data...") + ref_counts <- assay(ref_se) + if (!cell_type_colname %in% colnames(colData(ref_se))) {{ + stop(paste0("Error: '", cell_type_colname, "' not found in the column data of the reference object.")) + }} + cell_types <- as.factor(colData(ref_se)[[cell_type_colname]]) + names(cell_types) <- colnames(ref_se) + nUMI <- colSums(ref_counts) + reference <- Reference(ref_counts, cell_types, nUMI) + message("Reference object created successfully.") + + # --- 3. Create SpatialRNA Object --- + message("Creating SpatialRNA object from spatial data...") + puck_counts <- assay(puck_spe) + puck_coords <- as.data.frame(spatialCoords(puck_spe)) + puck <- SpatialRNA(puck_coords, puck_counts, colSums(puck_counts)) + message("SpatialRNA object created successfully.") + + # --- 4. Create and Run RCTD --- + message("Creating RCTD object...") + myRCTD <- create.RCTD(puck, reference, max_cores = {max_cores}, + gene_cutoff = {gene_cutoff}, fc_cutoff = {fc_cutoff}, + n_genes = {n_genes}, CELL_MIN_INSTANCE = {cell_min_instance}) + + message("Running RCTD in '{mode}' mode...") + myRCTD <- run.RCTD(myRCTD, doublet_mode = "{mode}") + message("RCTD run completed.") + + # --- 5. Save Results --- + message("Saving results...") + results <- myRCTD@results + # Normalize weights to sum to 1 + norm_weights <- normalize_weights(results$weights) + + # Save the normalized weights as CSV + weights_file_path <- file.path(output_dir, "rctd_cell_type_weights.csv") + write.csv(norm_weights, file = weights_file_path, quote = FALSE, row.names = TRUE) + + # Save the full RCTD object as RDS + rds_file_path <- file.path(output_dir, "rctd_object.rds") + saveRDS(myRCTD, file = rds_file_path) + + # Save a summary plot + message("Generating and saving summary plot...") + plot_df <- as.data.frame(cbind(puck@coords, norm_weights)) + colnames(plot_df)[1:2] <- c("x", "y") # Ensure coordinate columns are named x and y for ggplot + + p <- ggplot() + + geom_scatterpie(data = plot_df, aes(x = x, y = y), cols = colnames(norm_weights), pie_scale = 0.9) + + coord_equal() + + theme_void() + + labs(title = "RCTD Cell Type Proportions", fill = "Cell Type") + + plot_file_path <- file.path(output_dir, "rctd_cell_type_pie_chart.pdf") + ggsave(plot_file_path, plot = p, device = "pdf", width = 8, height = 7) + + message(paste0("All results saved to: ", output_dir)) + """ + + # 3. Subprocess Execution + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = r_script_file.name + + command = ["Rscript", r_script_path] + command_str = " ".join(command) + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + except subprocess.CalledProcessError as e: + # Clean up the temporary script file before raising + Path(r_script_path).unlink() + raise RuntimeError( + f"RCTD execution failed with exit code {e.returncode}.\n" + f"Command: {command_str}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) from e + finally: + # Ensure cleanup even on success + if Path(r_script_path).exists(): + Path(r_script_path).unlink() + + # 4. Structured Result Return + output_files = [ + str(output_dir / "rctd_cell_type_weights.csv"), + str(output_dir / "rctd_object.rds"), + str(output_dir / "rctd_cell_type_pie_chart.pdf"), + ] + + return { + "command_executed": command_str, + "stdout": process.stdout, + "stderr": process.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-spacexr/app/bioconductor-spacexr_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacexr/app/bioconductor-spacexr_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ae82a6f922982efc1f303d3c81274639088f32c8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacexr/app/bioconductor-spacexr_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-spacexr/app/bioconductor-spacexr_server.py') +SERVER_NAME = 'biosci_bioconductor_spacexr' + + +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-spacexr/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacexr/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacexr/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacexr/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacexr/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7c3f8801f17880e91cc3aea920bc34bfe28db9df --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacexr/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-spacexr: + build: . + image: mcp-bioconductor-spacexr:latest + container_name: mcp-bioconductor-spacexr + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-spacexr + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-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-spacexr/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacexr/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e3c9f447aa58514c28d5bb86dfa485e3b5c4316b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacexr/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-spacexr + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacexr/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacexr/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacexr/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spanorm/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spanorm/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..101b596dc6ddbb5ba91536ed5fe128d6cec87d60 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spanorm/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-spanorm via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-spanorm -y && conda clean -a + +# 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-spanorm_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-spanorm_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-spanorm_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spanorm/app/bioconductor-spanorm_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spanorm/app/bioconductor-spanorm_server.py new file mode 100644 index 0000000000000000000000000000000000000000..abb31ebc4733890b7d099658dab9e19dab402108 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spanorm/app/bioconductor-spanorm_server.py @@ -0,0 +1,153 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided by the MCP framework. +def tool(func): + def wrapper(*args, **kwargs): + # In a real scenario, the MCP framework would handle + # registration, UI generation, and execution based on the function signature. + print(f"Executing tool: {func.__name__}") + return func(*args, **kwargs) + return wrapper + +mcp = type("mcp", (), {"tool": tool}) + + +@mcp.tool +def spanorm( + input_object: Path, + output_object: Path, + assay_type: str = "counts", + num_cores: int = 1, +) -> dict: + """ + Performs spatially-aware normalisation for spatial transcriptomics data using SpaNorm. + + This tool wraps the SpaNorm() function from the R/Bioconductor package SpaNorm. + It takes a SingleCellExperiment, SpatialExperiment, or Seurat object in RDS format, + normalises the specified assay, and saves the updated object to a new RDS file. + + Args: + input_object: Path to the input RDS file containing a SingleCellExperiment, + SpatialExperiment, or Seurat object. + output_object: Path to save the output RDS file with the normalized data. + assay_type: String specifying the assay to use for normalization. + num_cores: Number of cores to use for parallel processing. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list + of output files. + """ + # --- Input Validation --- + if not input_object.is_file(): + raise FileNotFoundError(f"Input file not found: {input_object}") + if num_cores < 1: + raise ValueError("num_cores must be a positive integer.") + if not output_object.parent.exists(): + raise FileNotFoundError(f"Output directory does not exist: {output_object.parent}") + + # --- R Script Generation --- + # This script will be executed by Rscript. It loads the necessary libraries, + # parses command-line arguments, runs the SpaNorm function, and saves the result. + r_script_content = f""" + # Load necessary libraries quietly + suppressPackageStartupMessages(library(SpaNorm)) + suppressPackageStartupMessages(library(SingleCellExperiment)) + suppressPackageStartupMessages(library(SpatialExperiment)) + suppressPackageStartupMessages(library(SeuratObject)) + suppressPackageStartupMessages(library(BiocParallel)) + + # --- Argument Parsing --- + # Using a simple method for clarity, as argparse is not a base R package. + args <- commandArgs(trailingOnly = TRUE) + input_file <- args[1] + output_file <- args[2] + assay_name <- args[3] + cores <- as.integer(args[4]) + + # --- Setup Parallelization --- + if (cores > 1) {{ + bpparam <- MulticoreParam(workers = cores) + }} else {{ + bpparam <- SerialParam() + }} + + # --- Main Logic --- + tryCatch({{ + # Read the input object + message("Reading input object from: ", input_file) + input_obj <- readRDS(input_file) + + # Run SpaNorm + message(paste("Running SpaNorm on assay '", assay_name, "' with ", cores, " core(s)...", sep="")) + output_obj <- SpaNorm( + object = input_obj, + assay.type = assay_name, + BPPARAM = bpparam + ) + message("SpaNorm normalization complete.") + + # Save the output object + message("Saving normalized object to: ", output_file) + saveRDS(output_obj, file = output_file) + + message("Script completed successfully.") + }}, error = function(e) {{ + message("An error occurred: ", e$message) + quit(status = 1, save = "no") + }}) + """ + + # --- Subprocess Execution --- + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = Path(r_script_file.name) + + cmd = [ + "Rscript", + str(r_script_path), + str(input_object), + str(output_object), + assay_type, + str(num_cores), + ] + + command_executed = " ".join(cmd) + stdout_str = "" + stderr_str = "" + output_files = [] + + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + stdout_str = process.stdout + stderr_str = process.stderr + if output_object.exists(): + output_files.append(str(output_object)) + + except subprocess.CalledProcessError as e: + stderr_str = e.stderr + # Re-raise with more context for the MCP framework + raise RuntimeError( + f"SpaNorm execution failed with exit code {e.returncode}.\n" + f"Command: {command_executed}\n" + f"Stderr: {stderr_str}" + ) from e + finally: + # Clean up the temporary R script + r_script_path.unlink() + + # --- Structured Result Return --- + return { + "command_executed": command_executed, + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spanorm/app/bioconductor-spanorm_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spanorm/app/bioconductor-spanorm_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9d8ff2db1f64150d5bc62ce69a68ae01177dfc4d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spanorm/app/bioconductor-spanorm_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-spanorm/app/bioconductor-spanorm_server.py') +SERVER_NAME = 'biosci_bioconductor_spanorm' + + +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-spanorm/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spanorm/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spanorm/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spanorm/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spanorm/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..76fd862cdbac46449187028e2b59f2f4da22ad12 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spanorm/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-spanorm: + build: . + image: mcp-bioconductor-spanorm:latest + container_name: mcp-bioconductor-spanorm + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-spanorm + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-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-spanorm/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spanorm/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..421e19f615d56db9b96ef3f48ea15b2ff6396322 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spanorm/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-spanorm + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spanorm/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spanorm/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spanorm/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spari/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spari/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3ba93eb1862824f3260aa923fe403218a5ddfbd9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spari/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-spari via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-spari -y && conda clean -a + +# 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-spari_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-spari_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-spari_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spari/app/bioconductor-spari_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spari/app/bioconductor-spari_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7a9413fcfce8987434a018b247154390a7883edb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spari/app/bioconductor-spari_server.py @@ -0,0 +1,261 @@ +import subprocess +import tempfile +import shutil +from pathlib import Path +from typing import Optional, List, Dict, Any + +# Assume 'spari' is an executable available in the system's PATH. +# This wrapper simulates a command-line interface for the bioconductor-spari package, +# as if it were compiled into a standalone tool with subcommands. + +@mcp.tool() +def preprocess_spatial_data( + input_dir: Path, + output_se_object: Path, + min_cells: int = 3, + min_features: int = 200, + normalization_method: str = "LogNormalize", +) -> Dict[str, Any]: + """ + Preprocesses raw spatial transcriptomics data into a format suitable for SPARi analysis. + + This function simulates the 'spari preprocess' command, taking raw spatial data + (e.g., from 10x Genomics Visium) and generating a processed Seurat or + SpatialExperiment object (saved as an RDS file). + + Args: + input_dir: Path to the directory containing raw spatial data (e.g., filtered_feature_bc_matrix, spatial). + output_se_object: Path to save the processed Seurat/SpatialExperiment object as an RDS file. + min_cells: Minimum number of cells a feature must be detected in to be kept. + min_features: Minimum number of features detected in a cell to be kept. + normalization_method: Normalization method to apply (e.g., "LogNormalize", "SCTransform"). + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + if not input_dir.is_dir(): + raise ValueError(f"Input directory '{input_dir}' does not exist or is not a directory.") + if output_se_object.suffix != ".rds": + raise ValueError(f"Output file '{output_se_object}' must have a '.rds' extension.") + if min_cells < 0: + raise ValueError("min_cells must be a non-negative integer.") + if min_features < 0: + raise ValueError("min_features must be a non-negative integer.") + if normalization_method not in ["LogNormalize", "SCTransform", "none"]: + raise ValueError(f"Unsupported normalization_method: '{normalization_method}'. " + "Choose from 'LogNormalize', 'SCTransform', or 'none'.") + + # Ensure output directory exists + output_se_object.parent.mkdir(parents=True, exist_ok=True) + + command = [ + "spari", "preprocess", + "--input", str(input_dir), + "--output", str(output_se_object), + "--min-cells", str(min_cells), + "--min-features", str(min_features), + "--normalization", normalization_method, + ] + + try: + process = subprocess.run(command, capture_output=True, text=True, check=True) + stdout = process.stdout + stderr = process.stderr + except FileNotFoundError: + raise RuntimeError("The 'spari' executable was not found. Please ensure it is installed and in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"SPARi preprocess failed with exit code {e.returncode}", + "output_files": [], + } + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_se_object)], + } + + +@mcp.tool() +def analyze_spatial_data( + se_object_path: Path, + image_features_path: Path, + output_dir: Path, + n_pcs: int = 30, + resolution: float = 0.8, + n_neighbors: int = 20, + random_seed: int = 42, +) -> Dict[str, Any]: + """ + Performs spatial analysis using preprocessed spatial transcriptomics data and image features. + + This function simulates the 'spari analyze' command, taking a processed Seurat/SpatialExperiment + object and image-based features to perform clustering, dimensionality reduction, and + spatial domain identification. + + Args: + se_object_path: Path to the preprocessed Seurat/SpatialExperiment object (RDS file). + image_features_path: Path to the image features file (e.g., another RDS file or CSV). + output_dir: Directory to save analysis results (e.g., updated SE object, clustering results). + n_pcs: Number of principal components to use for dimensionality reduction. + resolution: Clustering resolution for graph-based clustering. + n_neighbors: Number of neighbors to use for UMAP/tSNE and graph construction. + random_seed: Seed for random number generation to ensure reproducibility. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + if not se_object_path.is_file(): + raise ValueError(f"Seurat/SpatialExperiment object file '{se_object_path}' does not exist.") + if not image_features_path.is_file(): + raise ValueError(f"Image features file '{image_features_path}' does not exist.") + if se_object_path.suffix != ".rds": + raise ValueError(f"Input Seurat object '{se_object_path}' must have a '.rds' extension.") + if n_pcs <= 0: + raise ValueError("n_pcs must be a positive integer.") + if not (0 < resolution <= 5.0): # Common range for Seurat resolution + raise ValueError("resolution must be between 0 and 5.0.") + if n_neighbors <= 0: + raise ValueError("n_neighbors must be a positive integer.") + + output_dir.mkdir(parents=True, exist_ok=True) + output_se_object = output_dir / "analyzed_se_object.rds" + output_clusters_csv = output_dir / "cluster_assignments.csv" + + command = [ + "spari", "analyze", + "--se-object", str(se_object_path), + "--image-features", str(image_features_path), + "--output-dir", str(output_dir), + "--n-pcs", str(n_pcs), + "--resolution", str(resolution), + "--n-neighbors", str(n_neighbors), + "--seed", str(random_seed), + ] + + try: + process = subprocess.run(command, capture_output=True, text=True, check=True) + stdout = process.stdout + stderr = process.stderr + except FileNotFoundError: + raise RuntimeError("The 'spari' executable was not found. Please ensure it is installed and in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"SPARi analysis failed with exit code {e.returncode}", + "output_files": [], + } + + # Assuming the tool creates these files + output_files = [str(output_se_object), str(output_clusters_csv)] + # Check if files were actually created by the hypothetical tool + output_files = [f for f in output_files if Path(f).exists()] + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + + +@mcp.tool() +def plot_spatial_results( + se_object_path: Path, + output_plot_path: Path, + plot_type: str, + feature_to_plot: Optional[str] = None, + cluster_id: Optional[str] = None, + width: int = 800, + height: int = 600, + plot_format: str = "png", +) -> Dict[str, Any]: + """ + Generates visualizations of spatial data and analysis results. + + This function simulates the 'spari plot' command, allowing users to visualize + spatial gene expression, clusters, or other features on the spatial transcriptomics + slide. + + Args: + se_object_path: Path to the analyzed Seurat/SpatialExperiment object (RDS file). + output_plot_path: Path to save the generated plot (e.g., PNG, PDF). + plot_type: Type of plot to generate. Valid options: "feature_plot", "spatial_dim_plot", "cluster_plot". + feature_to_plot: Name of the feature (e.g., gene name) to plot. Required for "feature_plot". + cluster_id: Identifier of a specific cluster to highlight or plot. + width: Width of the output plot in pixels. + height: Height of the output plot in pixels. + plot_format: Format of the output plot (e.g., "png", "pdf", "jpeg"). + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + if not se_object_path.is_file(): + raise ValueError(f"Seurat/SpatialExperiment object file '{se_object_path}' does not exist.") + if se_object_path.suffix != ".rds": + raise ValueError(f"Input Seurat object '{se_object_path}' must have a '.rds' extension.") + if plot_type not in ["feature_plot", "spatial_dim_plot", "cluster_plot"]: + raise ValueError(f"Unsupported plot_type: '{plot_type}'. " + "Choose from 'feature_plot', 'spatial_dim_plot', 'cluster_plot'.") + if plot_type == "feature_plot" and feature_to_plot is None: + raise ValueError("feature_to_plot is required for 'feature_plot' type.") + if width <= 0 or height <= 0: + raise ValueError("Plot width and height must be positive integers.") + if plot_format not in ["png", "pdf", "jpeg", "tiff"]: + raise ValueError(f"Unsupported plot_format: '{plot_format}'. " + "Choose from 'png', 'pdf', 'jpeg', 'tiff'.") + if output_plot_path.suffix.lower().lstrip('.') != plot_format.lower(): + raise ValueError(f"Output plot file extension '{output_plot_path.suffix}' does not match " + f"specified plot_format '{plot_format}'.") + + output_plot_path.parent.mkdir(parents=True, exist_ok=True) + + command = [ + "spari", "plot", + "--se-object", str(se_object_path), + "--output", str(output_plot_path), + "--type", plot_type, + "--width", str(width), + "--height", str(height), + "--format", plot_format, + ] + + if feature_to_plot: + command.extend(["--feature", feature_to_plot]) + if cluster_id: + command.extend(["--cluster-id", cluster_id]) + + try: + process = subprocess.run(command, capture_output=True, text=True, check=True) + stdout = process.stdout + stderr = process.stderr + except FileNotFoundError: + raise RuntimeError("The 'spari' executable was not found. Please ensure it is installed and in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"SPARi plot failed with exit code {e.returncode}", + "output_files": [], + } + + # Assuming the tool creates the specified output plot file + output_files = [str(output_plot_path)] + output_files = [f for f in output_files if Path(f).exists()] + + 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-spari/app/bioconductor-spari_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spari/app/bioconductor-spari_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..42f67f388264969eef66463d4db2ff5cd00241ed --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spari/app/bioconductor-spari_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-spari/app/bioconductor-spari_server.py') +SERVER_NAME = 'biosci_bioconductor_spari' + + +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-spari/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spari/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spari/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spari/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spari/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..90758242324926e6caa82b3eca9a1e302a008734 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spari/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-spari: + build: . + image: mcp-bioconductor-spari:latest + container_name: mcp-bioconductor-spari + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-spari + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-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-spari/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spari/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..82a1408ed8077cf3a62676a04cccf425f8d64344 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spari/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-spari + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spari/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spari/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spari/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sparsearray/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sparsearray/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9786bb349022f6ad1a1220558c18968072bab14e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sparsearray/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-sparsearray via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-sparsearray -y && conda clean -a + +# 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-sparsearray_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-sparsearray_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-sparsearray_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sparsearray/app/bioconductor-sparsearray_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sparsearray/app/bioconductor-sparsearray_server.py new file mode 100644 index 0000000000000000000000000000000000000000..cb33fb9dca9a47701bb4fa4f19aa4c3f700ae855 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-sparsearray/app/bioconductor-sparsearray_server.py @@ -0,0 +1,194 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Dict, Any, List + +# In a real MCP environment, the mcp package would be available. +# This is a placeholder for development and testing. +class _MCP: + def tool(self, *args, **kwargs): + def decorator(f): + return f + return decorator + +mcp = _MCP() + +R_SCRIPT_TEMPLATE = """ +# Load necessary libraries +if (!requireNamespace("SparseArray", quietly = TRUE)) { + stop("R package 'SparseArray' is not installed.") +} +if (!requireNamespace("MatrixGenerics", quietly = TRUE)) { + stop("R package 'MatrixGenerics' is not installed.") +} +library(SparseArray) +library(MatrixGenerics) + +# Read input arguments from the command line +args <- commandArgs(trailingOnly = TRUE) +if (length(args) != 5) { + stop("Usage: Rscript