diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bactopia/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bactopia/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e5911ad2d88b853011ea7cd0ab63108fd1b5fad0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bactopia/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bactopia via conda (e.g., from bioconda) +RUN conda install -c bioconda bactopia -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bactopia_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bactopia_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bactopia_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bactopia/app/bactopia_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bactopia/app/bactopia_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9c3d4652bd864077539725a2eb530213c9022a35 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bactopia/app/bactopia_server.py @@ -0,0 +1,279 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Union +import os + +@mcp.tool() +def bactopia_run( + sample: str, + outdir: str, + datasets: str, + r1: Optional[str] = None, + r2: Optional[str] = None, + se: Optional[str] = None, + fastqs: Optional[str] = None, + accession: Optional[str] = None, + accessions: Optional[str] = None, + profile: str = "conda", + cpus: int = 2, + max_memory: int = 8, + resume: bool = False, +) -> dict: + """ + Run the main Bactopia analysis pipeline for a bacterial genome. + + Args: + sample: Name of the sample. + outdir: Directory to store output results. + datasets: Path to the Bactopia datasets directory. + r1: Path to forward reads (Paired-end). + r2: Path to reverse reads (Paired-end). + se: Path to single-end reads. + fastqs: Path to a FOFN (file-of-filenames) for multiple samples. + accession: A single ENA/SRA accession (e.g., SRX000000). + accessions: A file containing a list of ENA/SRA accessions. + profile: Nextflow profile to use (e.g., conda, docker, singularity). + cpus: Number of CPUs to allocate. + max_memory: Maximum memory in GB to allocate. + resume: Whether to resume a previous run. + """ + # Input validation + out_path = Path(outdir) + ds_path = Path(datasets) + + if not ds_path.exists(): + return {"error": f"Datasets directory not found at {datasets}"} + + cmd = ["bactopia", "--sample", sample, "--outdir", str(out_path), "--datasets", str(ds_path)] + + # Input source logic + if r1 and r2: + if not Path(r1).exists() or not Path(r2).exists(): + return {"error": "R1 or R2 file does not exist"} + cmd += ["--R1", r1, "--R2", r2] + elif se: + if not Path(se).exists(): + return {"error": "Single-end file does not exist"} + cmd += ["--SE", se] + elif fastqs: + if not Path(fastqs).exists(): + return {"error": "Fastqs list file does not exist"} + cmd += ["--fastqs", fastqs] + elif accession: + cmd += ["--accession", accession] + elif accessions: + if not Path(accessions).exists(): + return {"error": "Accessions list file does not exist"} + cmd += ["--accessions", accessions] + else: + return {"error": "No input source provided (R1/R2, SE, fastqs, accession, or accessions required)"} + + # Performance and Nextflow options + cmd += ["-profile", profile] + cmd += ["--max_cpus", str(cpus)] + cmd += ["--max_memory", f"{max_memory}.GB"] + + if resume: + cmd.append("-resume") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_directory": str(out_path.absolute()) + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def bactopia_prepare( + path: str, + recursive: bool = False, + extension: str = ".fastq.gz", + output_file: Optional[str] = None +) -> dict: + """ + Prepare a FASTQ list (FOFN) for Bactopia from a directory of sequencing files. + + Args: + path: Directory containing FASTQ files. + recursive: Search for FASTQs in subdirectories. + extension: File extension to look for. + output_file: Optional path to save the generated list. + """ + input_path = Path(path) + if not input_path.is_dir(): + return {"error": f"Path {path} is not a directory"} + + cmd = ["bactopia", "prepare", str(input_path), "--extension", extension] + if recursive: + cmd.append("--recursive") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + if output_file: + out_p = Path(output_file) + out_p.write_text(result.stdout) + return { + "command_executed": " ".join(cmd), + "stdout": "File list generated and saved.", + "output_file": str(out_p.absolute()) + } + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def bactopia_search( + query: str, + limit: int = 10, + output_file: Optional[str] = None +) -> dict: + """ + Search for bacterial genome accessions in ENA/SRA. + + Args: + query: Search query (e.g., "Staphylococcus aureus"). + limit: Maximum number of results to return. + output_file: Optional path to save the accession list. + """ + cmd = ["bactopia", "search", query, "--limit", str(limit)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + if output_file: + out_p = Path(output_file) + out_p.write_text(result.stdout) + return { + "command_executed": " ".join(cmd), + "stdout": f"Search results saved to {output_file}", + "output_file": str(out_p.absolute()) + } + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def bactopia_datasets( + outdir: str, + species: Optional[str] = None, + include_genus: bool = False, + limit: int = 100 +) -> dict: + """ + Download and setup Bactopia datasets/databases. + + Args: + outdir: Directory to save the datasets. + species: Optional species name to download specific datasets (e.g., "Salmonella enterica"). + include_genus: Include genus-level datasets. + limit: Limit the number of genomes used for building datasets. + """ + out_path = Path(outdir) + cmd = ["bactopia", "datasets", "--outdir", str(out_path)] + + if species: + cmd += ["--species", species] + if include_genus: + cmd.append("--include_genus") + cmd += ["--limit", str(limit)] + + try: + # This can be a long-running process + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "datasets_path": str(out_path.absolute()) + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def bactopia_tool( + tool_name: str, + bactopia_dir: str, + outdir: str, + profile: str = "conda", + cpus: int = 2, + extra_params: Optional[List[str]] = None +) -> dict: + """ + Run a Bactopia Tool (comparative analysis) on existing Bactopia outputs. + Common tools include: pangenome, roary, iqtree, pirate, summary, etc. + + Args: + tool_name: Name of the Bactopia Tool to run. + bactopia_dir: Directory containing previous Bactopia results. + outdir: Directory to store tool results. + profile: Nextflow profile to use. + cpus: Number of CPUs to allocate. + extra_params: List of additional command line arguments for the specific tool. + """ + b_path = Path(bactopia_dir) + o_path = Path(outdir) + + if not b_path.exists(): + return {"error": f"Bactopia results directory not found at {bactopia_dir}"} + + cmd = [ + "bactopia", tool_name, + "--bactopia", str(b_path), + "--outdir", str(o_path), + "-profile", profile, + "--max_cpus", str(cpus) + ] + + if extra_params: + cmd.extend(extra_params) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_directory": str(o_path.absolute()) + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bactopia/app/bactopia_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bactopia/app/bactopia_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d2f8e3ca639c01ff8f15c17a9f2a642562a8e17e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bactopia/app/bactopia_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_bactopia/app/bactopia_server.py') +SERVER_NAME = 'biosci_bactopia' + + +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_bactopia/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bactopia/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bactopia/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bactopia/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bactopia/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7a04d950e41fdad191ac66dc0500c2e96c5f67b4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bactopia/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bactopia: + build: . + image: mcp-bactopia:latest + container_name: mcp-bactopia + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bactopia + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bactopia/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bactopia/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9ca9e2ebbc38669cf74f285464c2bddc36a6ebe0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bactopia/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bactopia + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bactopia/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bactopia/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bactopia/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_barrnap/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_barrnap/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ea6fbd530245c85ba9bce7c9fb9fbfde679a175d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_barrnap/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install barrnap via conda (e.g., from bioconda) +RUN conda install -c bioconda barrnap -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/barrnap_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/barrnap_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/barrnap_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_barrnap/app/barrnap_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_barrnap/app/barrnap_server.py new file mode 100644 index 0000000000000000000000000000000000000000..04656c2d7249255f86bca4589227d673d0b64175 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_barrnap/app/barrnap_server.py @@ -0,0 +1,336 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# Helper function to execute barrnap commands and handle output. +# This function is internal and not exposed as an MCP tool. +def _run_barrnap_command( + command_args: List[str], + output_gff_path: Optional[Path] = None, + debug: bool = False, + quiet: bool = False, +) -> dict: + """ + Internal helper to execute barrnap commands. + Captures stdout, stderr, and handles CalledProcessError. + If output_gff_path is provided, stdout is written to that file. + """ + cmd = ["barrnap"] + command_args + + if debug: + cmd.append("--debug") + if quiet: + cmd.append("--quiet") + + stdout_capture = "" + stderr_capture = "" + output_files_generated = [] + + try: + # barrnap writes GFF to stdout by default. + # If output_gff_path is provided, we capture stdout and write it to the file. + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + stdout_capture = process.stdout + stderr_capture = process.stderr + + if output_gff_path: + output_gff_path.write_text(stdout_capture) + output_files_generated.append(str(output_gff_path)) + stdout_capture = f"GFF output written to {output_gff_path}" + + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "returncode": e.returncode, + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": "barrnap command not found. Please ensure barrnap is installed and in your PATH.", + "error": "barrnap not found", + "returncode": 127, + "output_files": [], + } + + return { + "command_executed": " ".join(cmd), + "stdout": stdout_capture, + "stderr": stderr_capture, + "output_files": output_files_generated, + } + +@mcp.tool() +def barrnap_annotate( + fasta_file: Path, + output_gff_file: Path, + kingdom: Optional[str] = "bac", + enable_all_rna: bool = False, + disable_rrna: bool = False, + enable_trna: bool = False, + enable_ncrna: bool = False, + enable_mrna: bool = False, + threads: int = 1, + fast: bool = False, + evalue: Optional[float] = None, + incseq: bool = False, + incseqreg: bool = False, + outseq_file: Optional[Path] = None, + add_ids: bool = False, + db_directory: Optional[Path] = None, + debug: bool = False, + quiet: bool = False, +) -> dict: + """ + Annotates RNA features (rRNA, tRNA, tmRNA, ncRNA, mRNA) in microbial genomes + (bacteria, archaea, fungi) from an input FASTA file. + Outputs results in GFF3 format to the specified output file. + + Args: + fasta_file: Path to the input FASTA file containing genomic sequences. + output_gff_file: Path to the output GFF3 file where annotations will be written. + kingdom: The database to use for annotation. Choices: "bac" (Bacteria), + "arc" (Archaea), "fun" (Fungi). Defaults to "bac". + enable_all_rna: If True, enables scanning for all RNA types (rRNA, tRNA, tmRNA, ncRNA, mRNA). + This is equivalent to `--all`. + disable_rrna: If True, disables rRNA scanning. This is equivalent to `--no-rrna`. + enable_trna: If True, enables tRNA scanning. This is equivalent to `--trna`. + enable_ncrna: If True, enables ncRNA scanning. This is equivalent to `--ncrna`. + enable_mrna: If True, enables mRNA scanning (including CDS, RBS, sig_pep, terminator). + This is equivalent to `--mrna`. + threads: Number of CPUs to use for the search. Must be at least 1. Defaults to 1. + fast: If True, uses simpler HMMs instead of CMs, which is faster but less accurate. + This is equivalent to `--fast`. + evalue: E-value cutoff for hits to keep. Must be greater than 0 if provided. + This is equivalent to `--evalue`. + incseq: If True, includes the full input sequences in the output GFF. + This is equivalent to `--incseq`. + incseqreg: If True, includes `##sequence-region` headers in the GFF. + This is equivalent to `--incseqreg`. + outseq_file: Path to a FASTA file where hit sequences will be written. + This is equivalent to `--outseq`. + add_ids: If True, adds unique ID= tags to each GFF3 feature. + This is equivalent to `--addids`. + db_directory: Path to a different database folder to use. + This is equivalent to `--dbdir`. + debug: If True, writes all temporary files to '.' and prints debug information. + This is equivalent to `--debug`. + quiet: If True, suppresses all messages to stderr. This is equivalent to `--quiet`. + + Returns: + A dictionary containing: + - "command_executed": The full command string executed. + - "stdout": Standard output from the tool. + - "stderr": Standard error from the tool. + - "output_files": A list of paths to generated output files (GFF3 and optional FASTA). + """ + # Input validation + if not fasta_file.is_file(): + raise ValueError(f"Input FASTA file not found: {fasta_file}") + if not output_gff_file.parent.is_dir(): + raise ValueError(f"Output GFF directory does not exist: {output_gff_file.parent}") + + valid_kingdoms = {"bac", "arc", "fun"} + if kingdom is not None and kingdom not in valid_kingdoms: + raise ValueError(f"Invalid kingdom: '{kingdom}'. Must be one of {', '.join(valid_kingdoms)}.") + + if threads < 1: + raise ValueError(f"Number of threads must be at least 1, got {threads}.") + + if evalue is not None and evalue <= 0: + raise ValueError(f"E-value cutoff must be greater than 0, got {evalue}.") + + if outseq_file and not outseq_file.parent.is_dir(): + raise ValueError(f"Output FASTA directory for hit sequences does not exist: {outseq_file.parent}") + + if db_directory and not db_directory.is_dir(): + raise ValueError(f"Database directory not found: {db_directory}") + + command_args = [str(fasta_file)] + + # Database management + if db_directory: + command_args.extend(["--dbdir", str(db_directory)]) + + # Search options + if kingdom: + command_args.extend(["--kingdom", kingdom]) + if enable_all_rna: + command_args.append("--all") + if disable_rrna: + command_args.append("--no-rrna") + if enable_trna: + command_args.append("--trna") + if enable_ncrna: + command_args.append("--ncrna") + if enable_mrna: + command_args.append("--mrna") + + # Speed options + if threads > 1: # barrnap default is 1 thread, so only add if > 1 + command_args.extend(["--threads", str(threads)]) + if fast: + command_args.append("--fast") + + # Filtering options + if evalue is not None: + command_args.extend(["--evalue", str(evalue)]) + + # Output options + if incseq: + command_args.append("--incseq") + if incseqreg: + command_args.append("--incseqreg") + if outseq_file: + command_args.extend(["--outseq", str(outseq_file)]) + if add_ids: + command_args.append("--addids") + + result = _run_barrnap_command( + command_args=command_args, + output_gff_path=output_gff_file, + debug=debug, + quiet=quiet, + ) + + # Add outseq_file to output_files if it was generated by barrnap + if outseq_file and outseq_file.exists() and str(outseq_file) not in result["output_files"]: + result["output_files"].append(str(outseq_file)) + + return result + +@mcp.tool() +def barrnap_list_databases( + db_directory: Optional[Path] = None, + debug: bool = False, + quiet: bool = False, +) -> dict: + """ + Lists the installed barrnap databases and their contents. + + Args: + db_directory: Path to a different database folder to use. + This is equivalent to `--dbdir`. + debug: If True, writes all temporary files to '.' and prints debug information. + This is equivalent to `--debug`. + quiet: If True, suppresses all messages to stderr. This is equivalent to `--quiet`. + + Returns: + A dictionary containing: + - "command_executed": The full command string executed. + - "stdout": Standard output from the tool, listing databases. + - "stderr": Standard error from the tool. + - "output_files": An empty list, as no files are generated. + """ + command_args = ["--listdb"] + + if db_directory: + if not db_directory.is_dir(): + raise ValueError(f"Database directory not found: {db_directory}") + command_args.extend(["--dbdir", str(db_directory)]) + + return _run_barrnap_command( + command_args=command_args, + debug=debug, + quiet=quiet, + ) + +@mcp.tool() +def barrnap_update_databases( + db_directory: Optional[Path] = None, + debug: bool = False, + quiet: bool = False, +) -> dict: + """ + Updates barrnap databases from the internet. + + Args: + db_directory: Path to a different database folder to use. + This is equivalent to `--dbdir`. + debug: If True, writes all temporary files to '.' and prints debug information. + This is equivalent to `--debug`. + quiet: If True, suppresses all messages to stderr. This is equivalent to `--quiet`. + + Returns: + A dictionary containing: + - "command_executed": The full command string executed. + - "stdout": Standard output from the tool, typically update messages. + - "stderr": Standard error from the tool. + - "output_files": An empty list, as no files are generated. + """ + command_args = ["--updatedb"] + + if db_directory: + if not db_directory.is_dir(): + raise ValueError(f"Database directory not found: {db_directory}") + command_args.extend(["--dbdir", str(db_directory)]) + + return _run_barrnap_command( + command_args=command_args, + debug=debug, + quiet=quiet, + ) + +@mcp.tool() +def barrnap_get_version( + debug: bool = False, + quiet: bool = False, +) -> dict: + """ + Prints the barrnap version in the format 'barrnap X.Y'. + + Args: + debug: If True, writes all temporary files to '.' and prints debug information. + This is equivalent to `--debug`. + quiet: If True, suppresses all messages to stderr. This is equivalent to `--quiet`. + + Returns: + A dictionary containing: + - "command_executed": The full command string executed. + - "stdout": Standard output from the tool, containing the version string. + - "stderr": Standard error from the tool. + - "output_files": An empty list, as no files are generated. + """ + command_args = ["--version"] + return _run_barrnap_command( + command_args=command_args, + debug=debug, + quiet=quiet, + ) + +@mcp.tool() +def barrnap_get_citation( + debug: bool = False, + quiet: bool = False, +) -> dict: + """ + Prints the barrnap citation information. + + Args: + debug: If True, writes all temporary files to '.' and prints debug information. + This is equivalent to `--debug`. + quiet: If True, suppresses all messages to stderr. This is equivalent to `--quiet`. + + Returns: + A dictionary containing: + - "command_executed": The full command string executed. + - "stdout": Standard output from the tool, containing the citation. + - "stderr": Standard error from the tool. + - "output_files": An empty list, as no files are generated. + """ + command_args = ["--citation"] + return _run_barrnap_command( + command_args=command_args, + debug=debug, + quiet=quiet, + ) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_barrnap/app/barrnap_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_barrnap/app/barrnap_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a5e94f41063e1d955c341e93b430484db7bef809 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_barrnap/app/barrnap_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_barrnap/app/barrnap_server.py') +SERVER_NAME = 'biosci_barrnap' + + +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_barrnap/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_barrnap/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_barrnap/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_barrnap/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_barrnap/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..02c3e28e1c54228dcf0d8b743b2f15fcde7a0c1c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_barrnap/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-barrnap: + build: . + image: mcp-barrnap:latest + container_name: mcp-barrnap + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=barrnap + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-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_barrnap/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_barrnap/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eda56f8ba60811468f2c9d2f53a2ff421f7837b6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_barrnap/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - barrnap + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_barrnap/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_barrnap/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_barrnap/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-gff/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-gff/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a5da6a6ffc37bc287f6a2adff8c6f74bc1fcd648 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-gff/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bcbio-gff via conda (e.g., from bioconda) +RUN conda install -c bioconda bcbio-gff -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bcbio-gff_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bcbio-gff_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bcbio-gff_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-gff/app/bcbio-gff_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-gff/app/bcbio-gff_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3a26c3397daa77ce97a50ebe18e43c1745ac0382 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-gff/app/bcbio-gff_server.py @@ -0,0 +1,192 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Dict + +# Note: The 'bcbio-gff' package is primarily a Python library. It also +# installs several command-line utility scripts. The documentation provided +# did not include the '--help' output for these scripts. The following MCP +# tools are based on inferred, common-sense arguments for these utilities. +# The actual command-line interface may differ. + +@mcp.tool() +def gff_to_bed( + gff_file: Path +) -> Dict: + """ + Converts a GFF file to a BED file using `gff_to_bed.py`. + + This tool assumes the script takes a single GFF file as input and prints + the resulting BED formatted data to standard output. + """ + if not gff_file.is_file(): + raise FileNotFoundError(f"Input GFF file not found: {gff_file}") + + cmd = ["gff_to_bed.py", str(gff_file)] + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + + with tempfile.NamedTemporaryFile( + mode="w", delete=False, suffix=".bed", prefix="output_" + ) as tmp_out: + tmp_out.write(result.stdout) + output_path = tmp_out.name + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_path] + } + except FileNotFoundError: + raise RuntimeError("gff_to_bed.py not found. Ensure bcbio-gff scripts are in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": "Tool execution failed." + } + +@mcp.tool() +def gff_filter_by_attribute( + gff_file: Path, + attribute_key: str, + attribute_value: str +) -> Dict: + """ + Filters a GFF file by a given attribute key-value pair using `gff_filter_by_attribute.py`. + + This tool assumes the script takes an attribute key, an attribute value, and an + input GFF file as arguments, and prints the filtered GFF to standard output. + """ + if not gff_file.is_file(): + raise FileNotFoundError(f"Input GFF file not found: {gff_file}") + + cmd = ["gff_filter_by_attribute.py", attribute_key, attribute_value, str(gff_file)] + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + + with tempfile.NamedTemporaryFile( + mode="w", delete=False, suffix=".gff", prefix="filtered_" + ) as tmp_out: + tmp_out.write(result.stdout) + output_path = tmp_out.name + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_path] + } + except FileNotFoundError: + raise RuntimeError("gff_filter_by_attribute.py not found. Ensure bcbio-gff scripts are in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": "Tool execution failed." + } + +@mcp.tool() +def gff_filter_by_type( + gff_file: Path, + feature_type: str +) -> Dict: + """ + Filters a GFF file by a feature type (e.g., 'gene', 'mRNA') using `gff_filter_by_type.py`. + + This tool assumes the script takes an input GFF file and a feature type as + arguments, and prints the filtered GFF to standard output. + """ + if not gff_file.is_file(): + raise FileNotFoundError(f"Input GFF file not found: {gff_file}") + + cmd = ["gff_filter_by_type.py", str(gff_file), feature_type] + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + + with tempfile.NamedTemporaryFile( + mode="w", delete=False, suffix=".gff", prefix="filtered_type_" + ) as tmp_out: + tmp_out.write(result.stdout) + output_path = tmp_out.name + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_path] + } + except FileNotFoundError: + raise RuntimeError("gff_filter_by_type.py not found. Ensure bcbio-gff scripts are in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": "Tool execution failed." + } + +@mcp.tool() +def gff_stats( + gff_file: Path +) -> Dict: + """ + Calculates statistics on features in a GFF file using `gff_stats.py`. + + This tool assumes the script takes a single GFF file as input and prints + statistics to standard output. + """ + if not gff_file.is_file(): + raise FileNotFoundError(f"Input GFF file not found: {gff_file}") + + cmd = ["gff_stats.py", str(gff_file)] + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + + # The output is statistics text, not a structured file, so we return it directly. + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + raise RuntimeError("gff_stats.py not found. Ensure bcbio-gff scripts are in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": "Tool execution failed." + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-gff/app/bcbio-gff_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-gff/app/bcbio-gff_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..298e4a9e9532774638e7d7b663f759bba5162116 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-gff/app/bcbio-gff_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_bcbio-gff/app/bcbio-gff_server.py') +SERVER_NAME = 'biosci_bcbio_gff' + + +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_bcbio-gff/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-gff/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-gff/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-gff/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-gff/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..740633fb606c1695aeed663fe9f2e979047229e8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-gff/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bcbio-gff: + build: . + image: mcp-bcbio-gff:latest + container_name: mcp-bcbio-gff + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bcbio-gff + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-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_bcbio-gff/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-gff/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0dc26fcaad742380f0390b243547758b129f568d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-gff/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bcbio-gff + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-gff/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-gff/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-gff/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-nextgen/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-nextgen/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c3ee4e16c686152423e96c94fbde9fd5e62b1bfc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-nextgen/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bcbio-nextgen via conda (e.g., from bioconda) +RUN conda install -c bioconda bcbio-nextgen -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bcbio-nextgen_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bcbio-nextgen_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bcbio-nextgen_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-nextgen/app/bcbio-nextgen_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-nextgen/app/bcbio-nextgen_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4e5dae30404f8d153893383bce5087353708b16d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-nextgen/app/bcbio-nextgen_server.py @@ -0,0 +1,268 @@ +from typing import List, Optional, Dict, Any +import subprocess +from pathlib import Path +import os + +@mcp.tool() +def bcbio_nextgen_run( + config_file: str, + num_cores: int = 1, + parallel_type: str = "local", + scheduler: Optional[str] = None, + queue: Optional[str] = None, + resources: Optional[str] = None, + tag: Optional[str] = None, + workdir: Optional[str] = None, + timeout: int = 15, + retries: int = 0, +) -> Dict[str, Any]: + """ + Run a bcbio-nextgen analysis pipeline using a provided configuration file. + + Args: + config_file: Path to the YAML configuration file defining the analysis. + num_cores: Number of local cores to use for parallel execution. + parallel_type: Type of parallel execution (local, ipython, cluster, etc.). + scheduler: Scheduler for cluster execution (e.g., sge, slurm, torque, pbspro, lsf). + queue: Queue to submit jobs to on a cluster. + resources: Specific resource requirements for the scheduler (e.g., 'mem=16,vmem=20'). + tag: Optional tag to identify this specific run. + workdir: Directory to use for processing (defaults to current directory). + timeout: Time in minutes to wait for ipython cluster startup. + retries: Number of times to retry failed steps. + """ + config_path = Path(config_file) + if not config_path.exists(): + return {"error": f"Configuration file not found: {config_file}"} + + cmd = ["bcbio_nextgen.py", str(config_path.absolute())] + + cmd.extend(["-n", str(num_cores)]) + cmd.extend(["-t", parallel_type]) + + if scheduler: + cmd.extend(["-s", scheduler]) + if queue: + cmd.extend(["-q", queue]) + if resources: + cmd.extend(["-r", resources]) + if tag: + cmd.extend(["--tag", tag]) + if timeout != 15: + cmd.extend(["--timeout", str(timeout)]) + if retries > 0: + cmd.extend(["--retries", str(retries)]) + + # Handle working directory + original_dir = os.getcwd() + if workdir: + work_path = Path(workdir) + if not work_path.exists(): + work_path.mkdir(parents=True, exist_ok=True) + os.chdir(work_path) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "failed" + } + finally: + os.chdir(original_dir) + +@mcp.tool() +def bcbio_nextgen_template( + template_name: str, + metadata_csv: str, + input_files: List[str], + out_dir: Optional[str] = None, +) -> Dict[str, Any]: + """ + Create a bcbio-nextgen processing description from a template and input files. + + Args: + template_name: Name of the template to use (e.g., 'freebayes-variant', 'gatk-variant'). + metadata_csv: Path to a CSV file containing sample metadata. + input_files: List of paths to input BAM or FASTQ files. + out_dir: Directory to write the generated configuration (defaults to current directory). + """ + metadata_path = Path(metadata_csv) + if not metadata_path.exists(): + return {"error": f"Metadata file not found: {metadata_csv}"} + + # Validate input files + valid_inputs = [] + for f in input_files: + p = Path(f) + if p.exists(): + valid_inputs.append(str(p.absolute())) + else: + return {"error": f"Input file not found: {f}"} + + cmd = ["bcbio_nextgen.py", "-w", "template", template_name, str(metadata_path.absolute())] + cmd.extend(valid_inputs) + + # Handle output directory + original_dir = os.getcwd() + if out_dir: + out_path = Path(out_dir) + if not out_path.exists(): + out_path.mkdir(parents=True, exist_ok=True) + os.chdir(out_path) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success", + "info": "Configuration files generated in the output directory." + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "failed" + } + finally: + os.chdir(original_dir) + +@mcp.tool() +def bcbio_nextgen_upgrade( + tooldir: Optional[str] = None, + tools: bool = False, + data: bool = False, + genomes: Optional[List[str]] = None, + aligners: Optional[List[str]] = None, + cores: int = 1, +) -> Dict[str, Any]: + """ + Upgrade bcbio-nextgen software, third-party tools, or genome data. + + Args: + tooldir: Directory where tools are installed. + tools: If True, upgrade third-party software tools. + data: If True, upgrade/install genome data. + genomes: List of genome builds to install/upgrade (e.g., ['hg38', 'mm10']). + aligners: List of aligners to install data for (e.g., ['bwa', 'bowtie2']). + cores: Number of cores to use for data downloads and indexing. + """ + cmd = ["bcbio_nextgen.py", "upgrade"] + + if tooldir: + cmd.extend(["--tooldir", tooldir]) + if tools: + cmd.append("--tools") + if data: + cmd.append("--data") + + if genomes: + for g in genomes: + cmd.extend(["--genomes", g]) + + if aligners: + for a in aligners: + cmd.extend(["--aligners", a]) + + cmd.extend(["--cores", str(cores)]) + + try: + # Upgrades can take a long time, but we capture output + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "failed" + } + +@mcp.tool() +def bcbio_nextgen_install( + install_path: str, + tooldir: str, + genomes: List[str], + aligners: List[str], + nodata: bool = False, + isolate: bool = False, +) -> Dict[str, Any]: + """ + Run the bcbio-nextgen installer script to set up the environment. + + Args: + install_path: Path to install bcbio-nextgen data and code. + tooldir: Path to install third-party software tools. + genomes: List of genome builds to install (e.g., ['hg38']). + aligners: List of aligners to prepare (e.g., ['bwa']). + nodata: If True, do not install genome data. + isolate: If True, install into an isolated environment. + """ + # Note: This assumes bcbio_nextgen_install.py is in the PATH or current directory + # In a real environment, users might need to download it first. + cmd = ["python", "bcbio_nextgen_install.py", install_path, "--tooldir=" + tooldir] + + for g in genomes: + cmd.extend(["--genomes", g]) + for a in aligners: + cmd.extend(["--aligners", a]) + + if nodata: + cmd.append("--nodata") + if isolate: + cmd.append("--isolate") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "failed" + } + +@mcp.tool() +def bcbio_nextgen_version() -> Dict[str, Any]: + """ + Check the installed version of bcbio-nextgen. + """ + cmd = ["bcbio_nextgen.py", "--version"] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout.strip(), + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "status": "failed" + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-nextgen/app/bcbio-nextgen_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-nextgen/app/bcbio-nextgen_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9c94308f52018ca22b49aefdf03f2ef0c6e7c406 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-nextgen/app/bcbio-nextgen_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_bcbio-nextgen/app/bcbio-nextgen_server.py') +SERVER_NAME = 'biosci_bcbio_nextgen' + + +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_bcbio-nextgen/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-nextgen/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..67a946efd6f123ca05819a74532a97d4f84baeee --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-nextgen/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bcbio-nextgen: + build: . + image: mcp-bcbio-nextgen:latest + container_name: mcp-bcbio-nextgen + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bcbio-nextgen + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-nextgen/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-nextgen/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0fe9688f1cc6b35c7e0b9386c01415dc1e8fc3b1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-nextgen/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bcbio-nextgen + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-nextgen/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-nextgen/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bcbio-nextgen/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bedops/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bedops/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..565ae50155b78f1d8b26241027d43a56a2b50f5a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bedops/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bedops via conda (e.g., from bioconda) +RUN conda install -c bioconda bedops -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bedops_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bedops_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bedops_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bedops/app/bedops_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bedops/app/bedops_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6c5393c708ec1dfbbae98a9565d84343eb6820a8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bedops/app/bedops_server.py @@ -0,0 +1,450 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union +import os + +def _run_command(command: List[str]): + """Internal helper to execute subprocess commands safely.""" + try: + result = subprocess.run( + command, + check=True, + capture_output=True, + text=True + ) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "status": "error", + "exit_code": e.returncode + } + +@mcp.tool() +def bedops( + operation: str, + input_files: List[str], + chrom: Optional[str] = None, + ec: bool = False, + header: bool = False, + range_val: Optional[str] = None, + overlap_criteria: Optional[str] = None, + chop_bp: int = 0, + stagger: int = 0, + exclude: bool = False +): + """ + Perform set operations on BED or Starch files. + + Args: + operation: One of: 'complement' (-c), 'difference' (-d), 'element-of' (-e), 'intersect' (-i), 'merge' (-m), 'not-element-of' (-n), 'partition' (-p), 'symmdiff' (-s), 'everything' (-u), 'chop' (-w). + input_files: List of paths to sorted BED or Starch files. + chrom: Process data for given chromosome only. + ec: Enable error checking (slower). + header: Accept headers (VCF, GFF, SAM, BED, WIG) in input. + range_val: Add 'L:R' bp to coordinates or 'S' for symmetric padding. + overlap_criteria: For -e or -n, specify bp or percentage (e.g., '1' or '50%'). + chop_bp: For -w, specify window size in bp. + stagger: For -w, specify stagger distance in nt. + exclude: For -w, exclude original elements. + """ + # Map operation names to flags + op_map = { + "complement": "-c", "difference": "-d", "element-of": "-e", + "intersect": "-i", "merge": "-m", "not-element-of": "-n", + "partition": "-p", "symmdiff": "-s", "everything": "-u", "chop": "-w" + } + + if operation not in op_map: + raise ValueError(f"Invalid operation. Must be one of: {list(op_map.keys())}") + + cmd = ["bedops"] + + # Process Flags + if chrom: cmd.extend(["--chrom", chrom]) + if ec: cmd.append("--ec") + if header: cmd.append("--header") + if range_val: cmd.extend(["--range", range_val]) + + # Operation and its specific arguments + cmd.append(op_map[operation]) + + if operation in ["element-of", "not-element-of"] and overlap_criteria: + cmd.append(overlap_criteria) + + if operation == "chop": + if chop_bp > 0: cmd.append(str(chop_bp)) + if stagger > 0: cmd.extend(["--stagger", str(stagger)]) + if exclude: cmd.append("-x") + + # Validate and add files + for f in input_files: + path = Path(f) + if not path.exists(): + raise FileNotFoundError(f"Input file not found: {f}") + cmd.append(str(path.resolve())) + + return _run_command(cmd) + +@mcp.tool() +def bedmap( + reference_file: str, + map_file: str, + operations: List[str], + chrom: Optional[str] = None, + ec: bool = False, + header: bool = False, + range_val: Optional[str] = None, + bp_ovr: Optional[int] = None, + fraction_both: Optional[float] = None, + exact: bool = False, + faster: bool = False, + delim: str = "|", + echo: bool = False, + echo_map: bool = False, + indicator: bool = False +): + """ + Map overlapping BED elements and compute statistical operations. + + Args: + reference_file: The target regions. + map_file: The features to map onto reference regions. + operations: List of stats to compute (e.g., '--mean', '--max', '--min', '--count', '--sum'). + chrom: Process data for given chromosome only. + ec: Enable error checking. + header: Accept headers in input. + range_val: Add 'L:R' bp to reference coordinates. + bp_ovr: Require at least N bp overlap. + fraction_both: Require overlap of at least fraction of both elements. + exact: Require exact coordinate match. + faster: Use faster overlap detection (requires specific criteria). + delim: Delimiter for output columns. + echo: Echo reference element. + echo_map: Echo mapped elements. + indicator: Output 1 if overlap exists, 0 otherwise. + """ + cmd = ["bedmap"] + if chrom: cmd.extend(["--chrom", chrom]) + if ec: cmd.append("--ec") + if header: cmd.append("--header") + if range_val: cmd.extend(["--range", range_val]) + if bp_ovr is not None: cmd.extend(["--bp-ovr", str(bp_ovr)]) + if fraction_both is not None: cmd.extend(["--fraction-both", str(fraction_both)]) + if exact: cmd.append("--exact") + if faster: cmd.append("--faster") + cmd.extend(["--delim", delim]) + if echo: cmd.append("--echo") + if echo_map: cmd.append("--echo-map") + if indicator: cmd.append("--indicator") + + cmd.extend(operations) + + ref_path = Path(reference_file) + map_path = Path(map_file) + if not ref_path.exists() or not map_path.exists(): + raise FileNotFoundError("Reference or Map file not found.") + + cmd.extend([str(ref_path.resolve()), str(map_path.resolve())]) + return _run_command(cmd) + +@mcp.tool() +def sort_bed( + input_file: str, + max_mem: Optional[str] = None, + tmpdir: Optional[str] = None, + check_sort: bool = False +): + """ + Sort BED data lexicographically. Required for most BEDOPS tools. + + Args: + input_file: Path to the BED file to sort. + max_mem: Limit system memory (e.g., '2G'). + tmpdir: Custom temporary directory. + check_sort: Check if the file is already sorted. + """ + cmd = ["sort-bed"] + if max_mem: cmd.extend(["--max-mem", max_mem]) + if tmpdir: cmd.extend(["--tmpdir", tmpdir]) + if check_sort: cmd.append("--check") + + path = Path(input_file) + if not path.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + cmd.append(str(path.resolve())) + return _run_command(cmd) + +@mcp.tool() +def closest_features( + reference_file: str, + query_file: str, + chrom: Optional[str] = None, + ec: bool = False, + dist: bool = False, + closest: bool = False, + opp: bool = False +): + """ + Find nearest features between two BED files. + + Args: + reference_file: Reference BED file. + query_file: Query BED file. + chrom: Process data for given chromosome only. + ec: Enable error checking. + dist: Output signed distances. + closest: Output only the single closest feature. + opp: Find closest feature in opposite direction. + """ + cmd = ["closest-features"] + if chrom: cmd.extend(["--chrom", chrom]) + if ec: cmd.append("--ec") + if dist: cmd.append("--dist") + if closest: cmd.append("--closest") + if opp: cmd.append("--opp") + + ref_path = Path(reference_file) + query_path = Path(query_file) + if not ref_path.exists() or not query_path.exists(): + raise FileNotFoundError("Reference or Query file not found.") + + cmd.extend([str(ref_path.resolve()), str(query_path.resolve())]) + return _run_command(cmd) + +@mcp.tool() +def bedextract( + input_file: str, + chromosome: Optional[str] = None, + list_chromosomes: bool = False +): + """ + Efficiently extract features from a BED file. + + Args: + input_file: Path to sorted BED file. + chromosome: Extract features for this chromosome. + list_chromosomes: List all chromosomes in the file. + """ + cmd = ["bedextract"] + path = Path(input_file) + if not path.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + if list_chromosomes: + cmd.append("--list-chromosomes") + cmd.append(str(path.resolve())) + elif chromosome: + cmd.append(chromosome) + cmd.append(str(path.resolve())) + else: + raise ValueError("Must specify either a chromosome or list_chromosomes=True") + + return _run_command(cmd) + +@mcp.tool() +def starch( + input_file: str, + output_file: str, + bzip2: bool = False, + gzip: bool = False, + note: Optional[str] = None +): + """ + Compress BED data into Starch format. + + Args: + input_file: Path to sorted BED file. + output_file: Path to save the .starch file. + bzip2: Use bzip2 backend (default). + gzip: Use gzip backend. + note: Add a custom note to metadata. + """ + cmd = ["starch"] + if bzip2: cmd.append("--bzip2") + if gzip: cmd.append("--gzip") + if note: cmd.extend(["--note", note]) + + path = Path(input_file) + if not path.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + cmd.append(str(path.resolve())) + + # starch outputs to stdout, so we redirect in the shell or capture + result = _run_command(cmd) + if result["status"] == "success": + with open(output_file, "w") as f: + f.write(result["stdout"]) + result["output_files"] = [str(Path(output_file).resolve())] + return result + +@mcp.tool() +def unstarch( + starch_file: str, + chromosome: Optional[str] = None, + list_chromosomes: bool = False, + is_starch: bool = False, + metadata: bool = False +): + """ + Extract data or metadata from a Starch archive. + + Args: + starch_file: Path to .starch file. + chromosome: Extract data for specific chromosome. + list_chromosomes: List chromosomes in archive. + is_starch: Verify if file is a valid starch archive. + metadata: Show archive metadata. + """ + cmd = ["unstarch"] + if list_chromosomes: cmd.append("--list-chromosomes") + if is_starch: cmd.append("--is-starch") + if metadata: cmd.append("--metadata") + + path = Path(starch_file) + if not path.exists(): + raise FileNotFoundError(f"Starch file not found: {starch_file}") + + if chromosome and not (list_chromosomes or is_starch or metadata): + cmd.append(chromosome) + + cmd.append(str(path.resolve())) + return _run_command(cmd) + +@mcp.tool() +def vcf2bed(input_file: str, custom_variants: bool = False): + """Convert VCF to BED format.""" + cmd = ["vcf2bed"] + if custom_variants: cmd.append("--custom-variants") + + path = Path(input_file) + if not path.exists(): raise FileNotFoundError(f"File not found: {input_file}") + + # vcf2bed reads from stdin + with open(path, 'r') as f: + try: + result = subprocess.run(cmd, stdin=f, capture_output=True, text=True, check=True) + return {"command_executed": f"vcf2bed < {input_file}", "stdout": result.stdout, "stderr": result.stderr} + except subprocess.CalledProcessError as e: + return {"status": "error", "stderr": e.stderr} + +@mcp.tool() +def bam2bed(input_file: str, split: bool = False): + """Convert BAM to BED format.""" + cmd = ["bam2bed"] + if split: cmd.append("--split") + + path = Path(input_file) + if not path.exists(): raise FileNotFoundError(f"File not found: {input_file}") + + with open(path, 'rb') as f: + try: + result = subprocess.run(cmd, stdin=f, capture_output=True, text=True, check=True) + return {"command_executed": f"bam2bed < {input_file}", "stdout": result.stdout, "stderr": result.stderr} + except subprocess.CalledProcessError as e: + return {"status": "error", "stderr": e.stderr} + +@mcp.tool() +def gff2bed(input_file: str): + """Convert GFF to BED format.""" + path = Path(input_file) + if not path.exists(): raise FileNotFoundError(f"File not found: {input_file}") + with open(path, 'r') as f: + result = subprocess.run(["gff2bed"], stdin=f, capture_output=True, text=True, check=True) + return {"stdout": result.stdout, "stderr": result.stderr} + +@mcp.tool() +def gtf2bed(input_file: str): + """Convert GTF to BED format.""" + path = Path(input_file) + if not path.exists(): raise FileNotFoundError(f"File not found: {input_file}") + with open(path, 'r') as f: + result = subprocess.run(["gtf2bed"], stdin=f, capture_output=True, text=True, check=True) + return {"stdout": result.stdout, "stderr": result.stderr} + +@mcp.tool() +def sam2bed(input_file: str): + """Convert SAM to BED format.""" + path = Path(input_file) + if not path.exists(): raise FileNotFoundError(f"File not found: {input_file}") + with open(path, 'r') as f: + result = subprocess.run(["sam2bed"], stdin=f, capture_output=True, text=True, check=True) + return {"stdout": result.stdout, "stderr": result.stderr} + +@mcp.tool() +def wig2bed(input_file: str): + """Convert WIG to BED format.""" + path = Path(input_file) + if not path.exists(): raise FileNotFoundError(f"File not found: {input_file}") + with open(path, 'r') as f: + result = subprocess.run(["wig2bed"], stdin=f, capture_output=True, text=True, check=True) + return {"stdout": result.stdout, "stderr": result.stderr} + +@mcp.tool() +def starchcat( + input_starch_files: List[str], + output_file: str, + note: Optional[str] = None +): + """ + Merge multiple Starch archives into one. + + Args: + input_starch_files: List of .starch files to merge. + output_file: Path for the merged starch archive. + note: Custom note for metadata. + """ + cmd = ["starchcat"] + if note: cmd.extend(["--note", note]) + + for f in input_starch_files: + path = Path(f) + if not path.exists(): + raise FileNotFoundError(f"Input file not found: {f}") + cmd.append(str(path.resolve())) + + result = _run_command(cmd) + if result["status"] == "success": + with open(output_file, "w") as f: + f.write(result["stdout"]) + result["output_files"] = [str(Path(output_file).resolve())] + return result + +@mcp.tool() +def starchstrip( + starch_file: str, + output_file: str, + chromosomes: List[str] +): + """ + Filter a Starch archive to include only specific chromosomes. + + Args: + starch_file: Input .starch file. + output_file: Path for the stripped starch archive. + chromosomes: List of chromosomes to keep. + """ + cmd = ["starchstrip"] + for c in chromosomes: + cmd.extend(["--chrom", c]) + + path = Path(starch_file) + if not path.exists(): + raise FileNotFoundError(f"Starch file not found: {starch_file}") + cmd.append(str(path.resolve())) + + result = _run_command(cmd) + if result["status"] == "success": + with open(output_file, "w") as f: + f.write(result["stdout"]) + result["output_files"] = [str(Path(output_file).resolve())] + return result \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bedops/app/bedops_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bedops/app/bedops_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..265e774af15b415bb4effae67b46c27093392f95 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bedops/app/bedops_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_bedops/app/bedops_server.py') +SERVER_NAME = 'biosci_bedops' + + +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_bedops/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bedops/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bedops/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bedops/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bedops/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..91a34e4d62a9ab6c006b5be2741a5942d0c66a8b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bedops/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bedops: + build: . + image: mcp-bedops:latest + container_name: mcp-bedops + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bedops + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bedops/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bedops/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..11a313e56d9e8c3b984f027df03882228599fd59 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bedops/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bedops + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bedops/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bedops/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bedops/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bin2cell/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bin2cell/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a472346995a69a9ad4e37300bc0e533fc606e73a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bin2cell/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bin2cell via conda (e.g., from bioconda) +RUN conda install -c bioconda bin2cell -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bin2cell_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bin2cell_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bin2cell_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bin2cell/app/bin2cell_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bin2cell/app/bin2cell_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9c3468bfc6f56fc8083e0537920e6317cfd23b02 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bin2cell/app/bin2cell_server.py @@ -0,0 +1,278 @@ +import subprocess +from pathlib import Path +from typing import Optional, List + +@mcp.tool() +def bin2cell_prepare_bins( + input_dir: str, + output_h5ad: str, + bin_size: int = 2, + destripe: bool = True, +): + """ + Reads Visium HD data from a SpaceRanger output directory and optionally performs destriping + to correct for technical effects in 2um bin data. + + Args: + input_dir: Path to the SpaceRanger output directory (containing 'outs' folder). + output_h5ad: Path where the processed bin-level AnnData object will be saved. + bin_size: Resolution of bins to load (default is 2um). + destripe: Whether to apply the destriping correction for variable bin dimensions. + """ + # Input validation + input_path = Path(input_dir) + if not input_path.exists(): + return {"error": f"Input directory {input_dir} does not exist."} + + output_path = Path(output_h5ad) + if not output_path.parent.exists(): + output_path.parent.mkdir(parents=True, exist_ok=True) + + if bin_size <= 0: + return {"error": "bin_size must be a positive integer."} + + # Construct Python command + # We use a python script string to execute the library functions + destripe_cmd = "b2c.pp.destripe(adata)" if destripe else "pass" + python_script = f""" +import bin2cell as b2c +import scanpy as sc +import os + +try: + # Load Visium HD data + adata = b2c.pp.read_visium_hd_folder('{input_dir}', bin_size={bin_size}) + + # Perform destriping if requested + if {destripe}: + b2c.pp.destripe(adata) + + # Save the result + adata.write('{output_h5ad}') + print("Successfully prepared bin data.") +except Exception as e: + print(f"Error: {{str(e)}}") + exit(1) +""" + + try: + result = subprocess.run( + ["python", "-c", python_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"bin2cell.pp.read_visium_hd_folder and destripe={destripe}", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_h5ad] + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to prepare bin data", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd + } + +@mcp.tool() +def bin2cell_run_stardist( + image_path: str, + output_mask_path: str, + model_name: str = "2D_versatile_he", + prob_thresh: float = 0.5, + nms_thresh: float = 0.3, +): + """ + Performs cell segmentation on a morphology image using StarDist. + + Args: + image_path: Path to the high-resolution morphology image (e.g., tissue_hires_image.png). + output_mask_path: Path where the resulting segmentation mask (.tif) will be saved. + model_name: StarDist model to use (default: '2D_versatile_he'). + prob_thresh: Probability threshold for StarDist detection. + nms_thresh: Non-maximum suppression threshold for StarDist. + """ + # Input validation + img_path = Path(image_path) + if not img_path.exists(): + return {"error": f"Image file {image_path} does not exist."} + + out_mask = Path(output_mask_path) + if not out_mask.parent.exists(): + out_mask.parent.mkdir(parents=True, exist_ok=True) + + python_script = f""" +import bin2cell as b2c +import cv2 +import numpy as np + +try: + # Run StarDist segmentation via bin2cell wrapper + # Note: bin2cell.tl.stardist handles the model loading and prediction + b2c.tl.stardist( + '{image_path}', + '{output_mask_path}', + model='{model_name}', + prob_thresh={prob_thresh}, + nms_thresh={nms_thresh} + ) + print("Successfully generated segmentation mask.") +except Exception as e: + print(f"Error: {{str(e)}}") + exit(1) +""" + + try: + result = subprocess.run( + ["python", "-c", python_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"bin2cell.tl.stardist on {image_path}", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_mask_path] + } + except subprocess.CalledProcessError as e: + return { + "error": "StarDist segmentation failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd + } + +@mcp.tool() +def bin2cell_extract_cells( + bin_h5ad_path: str, + mask_path: str, + output_cell_h5ad_path: str, + qc_metrics: bool = True, +): + """ + Groups subcellular bins into cells based on a segmentation mask and generates a cell-level AnnData object. + + Args: + bin_h5ad_path: Path to the bin-level AnnData object (output from bin2cell_prepare_bins). + mask_path: Path to the segmentation mask file (output from bin2cell_run_stardist). + output_cell_h5ad_path: Path where the final cell-level AnnData object will be saved. + qc_metrics: Whether to calculate standard scanpy QC metrics for the new cell object. + """ + # Input validation + bin_path = Path(bin_h5ad_path) + if not bin_path.exists(): + return {"error": f"Bin h5ad file {bin_h5ad_path} does not exist."} + + m_path = Path(mask_path) + if not m_path.exists(): + return {"error": f"Mask file {mask_path} does not exist."} + + out_cell_path = Path(output_cell_h5ad_path) + if not out_cell_path.parent.exists(): + out_cell_path.parent.mkdir(parents=True, exist_ok=True) + + python_script = f""" +import bin2cell as b2c +import scanpy as sc + +try: + # Load the bin-level data + adata_bins = sc.read_h5ad('{bin_h5ad_path}') + + # Extract cells based on the mask + adata_cells = b2c.tl.extract_cells(adata_bins, '{mask_path}') + + # Calculate QC metrics if requested + if {qc_metrics}: + sc.pp.calculate_qc_metrics(adata_cells, inplace=True) + + # Save the cell-level object + adata_cells.write('{output_cell_h5ad_path}') + print("Successfully extracted cells from bins.") +except Exception as e: + print(f"Error: {{str(e)}}") + exit(1) +""" + + try: + result = subprocess.run( + ["python", "-c", python_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"bin2cell.tl.extract_cells using mask {mask_path}", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_cell_h5ad_path] + } + except subprocess.CalledProcessError as e: + return { + "error": "Cell extraction failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd + } + +@mcp.tool() +def bin2cell_visualize_segmentation( + bin_h5ad_path: str, + output_image_path: str, + basis: str = "spatial", +): + """ + Generates a visualization of the bin-to-cell assignments. + + Args: + bin_h5ad_path: Path to the bin-level AnnData object containing cell assignments. + output_image_path: Path to save the visualization plot (e.g., .png or .pdf). + basis: The coordinate system to use for plotting (default: 'spatial'). + """ + bin_path = Path(bin_h5ad_path) + if not bin_path.exists(): + return {"error": f"Bin h5ad file {bin_h5ad_path} does not exist."} + + python_script = f""" +import scanpy as sc +import matplotlib.pyplot as plt +import bin2cell as b2c + +try: + adata = sc.read_h5ad('{bin_h5ad_path}') + if 'cell_id' not in adata.obs.columns: + print("Error: cell_id not found in adata.obs. Run extract_cells first.") + exit(1) + + # Plotting logic + sc.pl.embedding(adata, basis='{basis}', color='cell_id', show=False) + plt.savefig('{output_image_path}') + print("Successfully saved visualization.") +except Exception as e: + print(f"Error: {{str(e)}}") + exit(1) +""" + + try: + result = subprocess.run( + ["python", "-c", python_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Visualization of cell_id on {basis}", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_image_path] + } + except subprocess.CalledProcessError as e: + return { + "error": "Visualization 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_bin2cell/app/bin2cell_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bin2cell/app/bin2cell_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0ae86fbd415d126785f1a48e243c53fa78ea77b3 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bin2cell/app/bin2cell_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_bin2cell/app/bin2cell_server.py') +SERVER_NAME = 'biosci_bin2cell' + + +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_bin2cell/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bin2cell/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bin2cell/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bin2cell/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bin2cell/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..098ceb799750eea4200969287a28a53212a12fc4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bin2cell/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bin2cell: + build: . + image: mcp-bin2cell:latest + container_name: mcp-bin2cell + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bin2cell + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-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_bin2cell/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bin2cell/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eb8ff7f84e83b73a3a12f8d25a0f5767d0133558 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bin2cell/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bin2cell + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bin2cell/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bin2cell/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bin2cell/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioawk/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioawk/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..26acb9706d6e3e8a943d4d9676b9eb014a983372 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioawk/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioawk via conda (e.g., from bioconda) +RUN conda install -c bioconda bioawk -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioawk_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioawk_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioawk_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioawk/app/bioawk_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioawk/app/bioawk_server.py new file mode 100644 index 0000000000000000000000000000000000000000..aa6fff3f8a61663d1375eedf06841e685f590554 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioawk/app/bioawk_server.py @@ -0,0 +1,120 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +# @mcp.tool() is a placeholder for the actual decorator. +# The user prompt says "NO NEED to import mcp". +def tool(*args, **kwargs): + def decorator(f): + return f + return decorator + +mcp = type("mcp", (), {"tool": tool}) + + +@mcp.tool() +def bioawk( + program: Optional[str] = None, + program_file: Optional[Path] = None, + input_files: Optional[List[Path]] = None, + format: Optional[str] = None, + tab_separator: bool = False, + retain_header: bool = False, + variables: Optional[List[str]] = None, + field_separator: Optional[str] = None, +) -> Dict[str, Any]: + """ + Executes the bioawk tool, a variant of awk for processing biological data formats. + + bioawk extends awk by understanding common bioinformatics formats, making it easy + to parse and manipulate files like FASTA, FASTQ, SAM, VCF, etc. + + Args: + program: The awk program script to execute, provided as a string. + program_file: A file containing the awk program script. + Exactly one of 'program' or 'program_file' must be provided. + input_files: A list of input files to process. If not provided, + bioawk will read from standard input. + format: The format of the input data. Supported formats include: + fasta, fastq, sam, vcf, bed, gff, gtf, psl, blast, hmmer, cigar. + If not specified, bioawk defaults to 'fasta'. + tab_separator: Use tab as the input and output field separator (-t). + retain_header: Retain the header in the output (-H). + variables: A list of variable assignments in 'var=value' format (-v). + field_separator: The input field separator, equivalent to awk's -F option. + + Returns: + A dictionary containing the executed command, stdout, and stderr. + """ + # 1. Input Validation + if not (program or program_file) or (program and program_file): + raise ValueError("Exactly one of 'program' or 'program_file' must be provided.") + + if program_file and not program_file.is_file(): + raise FileNotFoundError(f"Program file not found: {program_file}") + + if input_files: + for file_path in input_files: + if not file_path.is_file(): + raise FileNotFoundError(f"Input file not found: {file_path}") + + VALID_FORMATS = { + "fasta", "fastq", "sam", "vcf", "bed", "gff", + "gtf", "psl", "blast", "hmmer", "cigar" + } + if format and format.lower() not in VALID_FORMATS: + raise ValueError(f"Invalid format '{format}'. Must be one of {VALID_FORMATS}") + + if variables: + for var in variables: + if "=" not in var: + raise ValueError(f"Invalid variable assignment '{var}'. Must be in 'var=value' format.") + + # 2. Command Construction + cmd = ["bioawk"] + + if format: + cmd.extend(["-c", format]) + if tab_separator: + cmd.append("-t") + if retain_header: + cmd.append("-H") + if field_separator: + cmd.extend(["-F", field_separator]) + if variables: + for var in variables: + cmd.extend(["-v", var]) + + if program_file: + cmd.extend(["-f", str(program_file)]) + elif program: + cmd.append(program) + + if input_files: + cmd.extend([str(p) for p in input_files]) + + # 3. Subprocess Execution + command_executed = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + } + except FileNotFoundError: + # This error is raised if the 'bioawk' command itself is not found. + raise RuntimeError("bioawk command not found. Please ensure it is installed and in your PATH.") + except subprocess.CalledProcessError as e: + # This error is raised if bioawk returns a non-zero exit code. + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"bioawk failed with exit code {e.returncode}" + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioawk/app/bioawk_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioawk/app/bioawk_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..be27e408af29bfa8270c21c3af66fc7cd848d983 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioawk/app/bioawk_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_bioawk/app/bioawk_server.py') +SERVER_NAME = 'biosci_bioawk' + + +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_bioawk/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioawk/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioawk/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioawk/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioawk/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7225a96d51707881729bddfe8df7a8a8ad5a61bd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioawk/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioawk: + build: . + image: mcp-bioawk:latest + container_name: mcp-bioawk + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioawk + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-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_bioawk/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioawk/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d850d38d19bdb05c11c590472bc88660b4d32fef --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioawk/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioawk + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioawk/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioawk/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioawk/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_biobambam/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_biobambam/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d47f17c1c804642a5cab7ab14eee1ff11bbd3517 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_biobambam/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install biobambam via conda (e.g., from bioconda) +RUN conda install -c bioconda biobambam -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/biobambam_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/biobambam_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/biobambam_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_biobambam/app/biobambam_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_biobambam/app/biobambam_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3fe5c6abfb8e383b1451f1aad1f8b8413d8efdd7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_biobambam/app/biobambam_server.py @@ -0,0 +1,489 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union + +@mcp.tool() +def bamsort( + input_file: str, + output_file: str, + memory_limit: str = "1G", + tmp_prefix: Optional[str] = None, + create_index: bool = False, + index_filename: Optional[str] = None, + sort_order: str = "coordinate", + threads: int = 1, + compression_level: int = 1, + recalculate_md_nm: bool = False, + reference_file: Optional[str] = None, + verbose: bool = False, +) -> dict: + """ + Sorts BAM files by coordinate or query name using bamsort. + + Args: + input_file: Path to the input BAM file. + output_file: Path for the sorted output BAM file. + memory_limit: Main memory to use (e.g., '1G', '512M'). + tmp_prefix: Temporary file prefix. + create_index: Whether to create an index for the output BAM file. + index_filename: Name for the index file. + sort_order: Sort order ('coordinate' or 'queryname'). + threads: Number of threads to use. + compression_level: Compression level (0-9). + recalculate_md_nm: Recalculate MD and NM tags (requires reference). + reference_file: Reference FASTA file for MD/NM recalculation. + verbose: Enable verbose output. + """ + in_path = Path(input_file) + out_path = Path(output_file) + + if not in_path.exists(): + return {"error": f"Input file {input_file} does not exist"} + if sort_order not in ["coordinate", "queryname"]: + return {"error": "sort_order must be 'coordinate' or 'queryname'"} + if not (0 <= compression_level <= 9): + return {"error": "compression_level must be between 0 and 9"} + + cmd = ["bamsort", f"I={input_file}", f"O={output_file}"] + cmd.append(f"M={memory_limit}") + cmd.append(f"sortorder={sort_order}") + cmd.append(f"threads={threads}") + cmd.append(f"level={compression_level}") + + if tmp_prefix: cmd.append(f"T={tmp_prefix}") + if create_index: cmd.append("index=1") + if index_filename: cmd.append(f"indexfilename={index_filename}") + if recalculate_md_nm: + if not reference_file: + return {"error": "reference_file is required for recalculate_md_nm"} + cmd.append("calmd=1") + cmd.append(f"reference={reference_file}") + if verbose: cmd.append("verbose=1") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file] + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "command_executed": " ".join(cmd), "return_code": e.returncode} + +@mcp.tool() +def bammarkduplicates( + input_file: str, + output_file: str, + metrics_file: Optional[str] = None, + tmp_prefix: Optional[str] = None, + create_index: bool = False, + index_filename: Optional[str] = None, + remove_duplicates: bool = False, + compression_level: int = 1, + verbose: bool = False, +) -> dict: + """ + Marks or removes duplicate reads in a coordinate-sorted BAM file. + + Args: + input_file: Input BAM file (must be coordinate sorted). + output_file: Output BAM file with duplicates marked. + metrics_file: Path for the output metrics file. + tmp_prefix: Temporary file prefix. + create_index: Create index for output BAM. + index_filename: Name for the index file. + remove_duplicates: Remove duplicate reads instead of marking. + compression_level: Compression level (0-9). + verbose: Enable verbose output. + """ + if not Path(input_file).exists(): + return {"error": f"Input file {input_file} does not exist"} + + cmd = ["bammarkduplicates", f"I={input_file}", f"O={output_file}"] + cmd.append(f"level={compression_level}") + + if metrics_file: cmd.append(f"M={metrics_file}") + if tmp_prefix: cmd.append(f"T={tmp_prefix}") + if create_index: cmd.append("index=1") + if index_filename: cmd.append(f"indexfilename={index_filename}") + if remove_duplicates: cmd.append("rmdup=1") + if verbose: cmd.append("verbose=1") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + outputs = [output_file] + if metrics_file: outputs.append(metrics_file) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": outputs + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "command_executed": " ".join(cmd)} + +@mcp.tool() +def bamsormadup( + input_file: str, + output_file: str, + tmp_prefix: Optional[str] = None, + memory_limit: str = "1G", + threads: int = 1, + compression_level: int = 1, + create_index: bool = False, + index_filename: Optional[str] = None, + remove_duplicates: bool = False, + verbose: bool = False, +) -> dict: + """ + Combined sorting and duplicate marking in a single pass. + + Args: + input_file: Input BAM file. + output_file: Output BAM file. + tmp_prefix: Temporary file prefix. + memory_limit: Memory limit. + threads: Number of threads. + compression_level: Compression level (0-9). + create_index: Create index for output. + index_filename: Index filename. + remove_duplicates: Remove duplicates. + verbose: Enable verbose output. + """ + if not Path(input_file).exists(): + return {"error": f"Input file {input_file} does not exist"} + + cmd = ["bamsormadup", f"I={input_file}", f"O={output_file}"] + cmd.append(f"M={memory_limit}") + cmd.append(f"threads={threads}") + cmd.append(f"level={compression_level}") + + if tmp_prefix: cmd.append(f"T={tmp_prefix}") + if create_index: cmd.append("index=1") + if index_filename: cmd.append(f"indexfilename={index_filename}") + if remove_duplicates: cmd.append("rmdup=1") + if verbose: cmd.append("verbose=1") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file] + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "command_executed": " ".join(cmd)} + +@mcp.tool() +def bamtofastq( + input_file: str, + fastq_1: str, + fastq_2: Optional[str] = None, + singles: Optional[str] = None, + orphans_1: Optional[str] = None, + orphans_2: Optional[str] = None, + collate: bool = False, + gzip: bool = False, + compression_level: int = 1, + reads_per_file: int = 0, + verbose: bool = False, +) -> dict: + """ + Converts BAM files to FASTQ format. + + Args: + input_file: Input BAM file. + fastq_1: Output FASTQ file (Read 1). + fastq_2: Output FASTQ file (Read 2). + singles: Output FASTQ for single-end reads. + orphans_1: Output FASTQ for orphan Read 1. + orphans_2: Output FASTQ for orphan Read 2. + collate: Collate reads by name before conversion. + gzip: Compress output with gzip. + compression_level: Gzip compression level (1-9). + reads_per_file: Split output into files with N reads (0 = no split). + verbose: Enable verbose output. + """ + if not Path(input_file).exists(): + return {"error": f"Input file {input_file} does not exist"} + + cmd = ["bamtofastq", f"filename={input_file}", f"F={fastq_1}"] + outputs = [fastq_1] + + if fastq_2: + cmd.append(f"F2={fastq_2}") + outputs.append(fastq_2) + if singles: + cmd.append(f"S={singles}") + outputs.append(singles) + if orphans_1: + cmd.append(f"O={orphans_1}") + outputs.append(orphans_1) + if orphans_2: + cmd.append(f"O2={orphans_2}") + outputs.append(orphans_2) + if collate: cmd.append("collate=1") + if gzip: cmd.append("gz=1") + if compression_level != 1: cmd.append(f"level={compression_level}") + if reads_per_file > 0: cmd.append(f"readsperfile={reads_per_file}") + if verbose: cmd.append("verbose=1") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": outputs + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "command_executed": " ".join(cmd)} + +@mcp.tool() +def bamcollate2( + input_file: str, + output_file: str, + tmp_prefix: Optional[str] = None, + compression_level: int = 1, + verbose: bool = False, +) -> dict: + """ + Collates a BAM file by read name. + + Args: + input_file: Input BAM file. + output_file: Output collated BAM file. + tmp_prefix: Temporary file prefix. + compression_level: Compression level (0-9). + verbose: Enable verbose output. + """ + if not Path(input_file).exists(): + return {"error": f"Input file {input_file} does not exist"} + + cmd = ["bamcollate2", f"I={input_file}", f"O={output_file}"] + cmd.append(f"level={compression_level}") + if tmp_prefix: cmd.append(f"T={tmp_prefix}") + if verbose: cmd.append("verbose=1") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file] + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "command_executed": " ".join(cmd)} + +@mcp.tool() +def bamadapterclip( + input_file: str, + output_file: str, + threads: int = 1, + compression_level: int = 1, + verbose: bool = False, +) -> dict: + """ + Clips adapter sequences from reads in a BAM file. + + Args: + input_file: Input BAM file. + output_file: Output clipped BAM file. + threads: Number of threads. + compression_level: Compression level (0-9). + verbose: Enable verbose output. + """ + if not Path(input_file).exists(): + return {"error": f"Input file {input_file} does not exist"} + + cmd = ["bamadapterclip", f"I={input_file}", f"O={output_file}"] + cmd.append(f"threads={threads}") + cmd.append(f"level={compression_level}") + if verbose: cmd.append("verbose=1") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file] + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "command_executed": " ".join(cmd)} + +@mcp.tool() +def bamreset( + input_file: str, + output_file: str, + compression_level: int = 1, + reset_flags: bool = False, + verbose: bool = False, +) -> dict: + """ + Resets alignment information in a BAM file. + + Args: + input_file: Input BAM file. + output_file: Output reset BAM file. + compression_level: Compression level (0-9). + reset_flags: Reset flags to 0. + verbose: Enable verbose output. + """ + if not Path(input_file).exists(): + return {"error": f"Input file {input_file} does not exist"} + + cmd = ["bamreset", f"I={input_file}", f"O={output_file}"] + cmd.append(f"level={compression_level}") + if reset_flags: cmd.append("resetflags=1") + if verbose: cmd.append("verbose=1") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file] + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "command_executed": " ".join(cmd)} + +@mcp.tool() +def bamchecksort( + input_file: str, + verbose: bool = False, +) -> dict: + """ + Checks if a BAM file is sorted. + + Args: + input_file: Input BAM file. + verbose: Enable verbose output. + """ + if not Path(input_file).exists(): + return {"error": f"Input file {input_file} does not exist"} + + cmd = ["bamchecksort", f"I={input_file}"] + if verbose: cmd.append("verbose=1") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "is_sorted": "sorted" in result.stdout.lower() or result.returncode == 0 + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "command_executed": " ".join(cmd), "is_sorted": False} + +@mcp.tool() +def bamrecompress( + input_file: str, + output_file: str, + compression_level: int = 1, + threads: int = 1, + verbose: bool = False, +) -> dict: + """ + Recompresses a BAM file. + + Args: + input_file: Input BAM file. + output_file: Output recompressed BAM file. + compression_level: Compression level (0-9). + threads: Number of threads. + verbose: Enable verbose output. + """ + if not Path(input_file).exists(): + return {"error": f"Input file {input_file} does not exist"} + + cmd = ["bamrecompress", f"I={input_file}", f"O={output_file}"] + cmd.append(f"level={compression_level}") + cmd.append(f"threads={threads}") + if verbose: cmd.append("verbose=1") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file] + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "command_executed": " ".join(cmd)} + +@mcp.tool() +def bamfilterrg( + input_file: str, + output_file: str, + read_group: str, + compression_level: int = 1, + verbose: bool = False, +) -> dict: + """ + Filters a BAM file by read group. + + Args: + input_file: Input BAM file. + output_file: Output filtered BAM file. + read_group: Read group ID to keep. + compression_level: Compression level (0-9). + verbose: Enable verbose output. + """ + if not Path(input_file).exists(): + return {"error": f"Input file {input_file} does not exist"} + + cmd = ["bamfilterrg", f"I={input_file}", f"O={output_file}", f"rg={read_group}"] + cmd.append(f"level={compression_level}") + if verbose: cmd.append("verbose=1") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file] + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "command_executed": " ".join(cmd)} + +@mcp.tool() +def bamfillquery( + input_file: str, + output_file: str, + compression_level: int = 1, + verbose: bool = False, +) -> dict: + """ + Fills query information in a BAM file. + + Args: + input_file: Input BAM file. + output_file: Output BAM file. + compression_level: Compression level (0-9). + verbose: Enable verbose output. + """ + if not Path(input_file).exists(): + return {"error": f"Input file {input_file} does not exist"} + + cmd = ["bamfillquery", f"I={input_file}", f"O={output_file}"] + cmd.append(f"level={compression_level}") + if verbose: cmd.append("verbose=1") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file] + } + except subprocess.CalledProcessError as e: + return {"error": e.stderr, "command_executed": " ".join(cmd)} \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_biobambam/app/biobambam_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_biobambam/app/biobambam_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..96e5c5c4c7947ed3483b01d110b329ac943a1242 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_biobambam/app/biobambam_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_biobambam/app/biobambam_server.py') +SERVER_NAME = 'biosci_biobambam' + + +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_biobambam/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_biobambam/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_biobambam/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_biobambam/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_biobambam/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..8e560d0b9663f640ea501c160550b562e9866e2d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_biobambam/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-biobambam: + build: . + image: mcp-biobambam:latest + container_name: mcp-biobambam + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=biobambam + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_biobambam/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_biobambam/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5f8302421154c86eee3b610322b5b4017bb7a7ae --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_biobambam/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - biobambam + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_biobambam/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_biobambam/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_biobambam/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioblend/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioblend/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a56c4e8db6d655a1d5c38ba9521a8d959917697a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioblend/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioblend via conda (e.g., from bioconda) +RUN conda install -c bioconda bioblend -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioblend_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioblend_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioblend_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioblend/app/bioblend_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioblend/app/bioblend_server.py new file mode 100644 index 0000000000000000000000000000000000000000..86712809a85d950dab1c2687c64a6dd4ba4344d4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioblend/app/bioblend_server.py @@ -0,0 +1,111 @@ +import json +import subprocess +from pathlib import Path +from typing import Dict, List, Optional + +# In a real MCP environment, the 'mcp' object would be imported. +# For this standalone script, we define a dummy decorator. +class mcp: + @staticmethod + def tool(func): + return func + +# Since bioblend is a library, we will need to ensure it is installed +# in the execution environment. We can simulate a check for it. +try: + from bioblend.galaxy import GalaxyInstance + from bioblend.galaxy.client import Client + from bioblend.connection import BioBlendConnectionError +except ImportError: + raise ImportError("The 'bioblend' library is required to use this tool. Please install it via 'pip install bioblend'.") + + +@mcp.tool +def upload_to_galaxy( + galaxy_url: str, + api_key: str, + history_id: str, + file_path: Path, + file_type: str = "auto", + dbkey: str = "?", + to_posix_lines: bool = True, + space_to_tab: bool = False, +) -> Dict: + """ + Uploads a dataset to a specified Galaxy history using the bioblend library. + + This tool acts as a wrapper around the bioblend library's file upload + functionality, providing a way to programmatically add datasets to a + Galaxy server from the MCP framework. + + Args: + galaxy_url (str): The URL of the Galaxy instance (e.g., 'https://usegalaxy.org'). + api_key (str): Your Galaxy API key for authentication. + history_id (str): The ID of the history to which the file will be uploaded. + file_path (Path): The local path to the file to upload. + file_type (str): The Galaxy datatype for the uploaded file. Defaults to 'auto'. + dbkey (str): The genome build (dbkey) to associate with the dataset. Defaults to '?'. + to_posix_lines (bool): If True, convert line endings to POSIX standard. Defaults to True. + space_to_tab (bool): If True, convert all spaces to tabs in the uploaded file. Defaults to False. + + Returns: + Dict: A dictionary containing the execution details and results, including + the response from the Galaxy API upon successful upload. + """ + # --- Input Validation --- + if not galaxy_url: + raise ValueError("galaxy_url must be provided.") + if not api_key: + raise ValueError("api_key must be provided.") + if not history_id: + raise ValueError("history_id must be provided.") + + if not file_path.is_file(): + raise FileNotFoundError(f"Input file not found at: {file_path}") + + # This tool uses the bioblend library directly, not a command-line subprocess. + # The 'command_executed' will represent the library call for logging purposes. + command_executed = ( + f"bioblend.tools.upload_file(file_path='{file_path}', " + f"history_id='{history_id}', file_type='{file_type}', dbkey='{dbkey}', " + f"to_posix_lines={to_posix_lines}, space_to_tab={space_to_tab})" + ) + + stdout_str = "" + stderr_str = "" + output_data = {} + + try: + # --- Tool Execution --- + # Instantiate the Galaxy client + galaxy_instance = GalaxyInstance(url=galaxy_url, key=api_key) + + # Execute the file upload + upload_result = galaxy_instance.tools.upload_file( + str(file_path), + history_id, + file_type=file_type, + dbkey=dbkey, + to_posix_lines=to_posix_lines, + space_to_tab=space_to_tab, + ) + + # Format the successful output + stdout_str = json.dumps(upload_result, indent=2) + output_data = upload_result + + except BioBlendConnectionError as e: + stderr_str = f"Connection Error: Failed to connect to Galaxy at {galaxy_url}. Details: {e}" + raise RuntimeError(stderr_str) from e + except Exception as e: + # Catch other potential exceptions from the library call + stderr_str = f"An unexpected error occurred during the bioblend operation: {e}" + raise RuntimeError(stderr_str) from e + + return { + "command_executed": command_executed, + "stdout": stdout_str, + "stderr": stderr_str, + "output_data": output_data, + "output_files": [] # Output is on the remote Galaxy server, not a local file + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioblend/app/bioblend_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioblend/app/bioblend_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1226951231db4c8f4bce52c024edee67f79159d7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioblend/app/bioblend_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_bioblend/app/bioblend_server.py') +SERVER_NAME = 'biosci_bioblend' + + +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_bioblend/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioblend/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..f985e4c94e043520a83e16416a8e73e8e2426be6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioblend/app/requirements.txt @@ -0,0 +1 @@ +bioblend==1.9.0 diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioblend/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioblend/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..40f5f76242ec528d98b9a3b0aad72c6398fdd921 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioblend/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioblend: + build: . + image: mcp-bioblend:latest + container_name: mcp-bioblend + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioblend + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-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_bioblend/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioblend/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9fa8ac2cc2cc4af351edefd9202996694444df14 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioblend/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioblend + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioblend/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioblend/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc15635ee2cb05fa952cb12ad6bfbcc901077d81 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioblend/requirements.txt @@ -0,0 +1,3 @@ +bioblend==1.9.0 +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-repodata-patches/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-repodata-patches/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..65defc9b7b6edebc9c401da79cfd3b025c1340ae --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-repodata-patches/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconda-repodata-patches via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconda-repodata-patches -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY bioconda-repodata-patches_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconda-repodata-patches_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconda-repodata-patches_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-repodata-patches/app/bioconda-repodata-patches_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-repodata-patches/app/bioconda-repodata-patches_server.py new file mode 100644 index 0000000000000000000000000000000000000000..83bc5239f83e4d34209ebf36742a07369b52d2d6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-repodata-patches/app/bioconda-repodata-patches_server.py @@ -0,0 +1,91 @@ +import subprocess +from pathlib import Path +from typing import Dict, List, Any + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be imported. +def tool(*args, **kwargs): + def decorator(f): + return f + return decorator + +mcp = type("mcp", (), {"tool": tool}) + + +@mcp.tool() +def apply_repodata_patches( + repodata_json: Path, + patch_dir: Path, + output_json: Path, +) -> Dict[str, Any]: + """ + Applies patches from a directory to a conda repodata.json file. + + This tool is a wrapper for the 'bioconda-repodata-patches' command, which + is part of the bioconda-utils suite. It takes an existing repodata.json, + a directory of patch files, and generates a new, patched repodata.json file. + + Args: + repodata_json: Path to the input repodata.json file to be patched. + patch_dir: Path to the directory containing patch files. + output_json: Path to write the patched repodata.json file. + + Returns: + A dictionary containing the execution details and output file path. + """ + # 1. Input Validation + if not repodata_json.is_file(): + raise FileNotFoundError(f"Input repodata file not found: {repodata_json}") + if not patch_dir.is_dir(): + raise NotADirectoryError(f"Patch directory not found or is not a directory: {patch_dir}") + + # Ensure the output directory exists + output_json.parent.mkdir(parents=True, exist_ok=True) + + # 2. Command Construction + # The command is inferred from bioconda-utils source, as no direct help was provided. + # The executable is assumed to be `bioconda-repodata-patches`. + cmd = [ + "bioconda-repodata-patches", + "--patch-dir", str(patch_dir), + str(repodata_json), + str(output_json) + ] + command_executed = " ".join(cmd) + + # 3. Subprocess Execution and Error Handling + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + stdout = result.stdout + stderr = result.stderr + output_files = {"patched_repodata": str(output_json)} + + except FileNotFoundError: + # This error occurs if the command itself is not found in the system's PATH. + return { + "command_executed": command_executed, + "stdout": "", + "stderr": f"Error: The 'bioconda-repodata-patches' command was not found. Please ensure the tool is installed and in the system's PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + # This error occurs if the command returns a non-zero exit code. + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + # 4. Return Structured Output + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_json)] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-repodata-patches/app/bioconda-repodata-patches_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-repodata-patches/app/bioconda-repodata-patches_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c5c1d59cc878a824a325c292abd1270ec4b9c71e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-repodata-patches/app/bioconda-repodata-patches_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_bioconda-repodata-patches/app/bioconda-repodata-patches_server.py') +SERVER_NAME = 'biosci_bioconda_repodata_patches' + + +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_bioconda-repodata-patches/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-repodata-patches/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..df4c85fb358283e4e913a4551f715111612d89f4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-repodata-patches/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconda-repodata-patches: + build: . + image: mcp-bioconda-repodata-patches:latest + container_name: mcp-bioconda-repodata-patches + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconda-repodata-patches + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-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_bioconda-repodata-patches/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-repodata-patches/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e7fe0d75f341ae04741a6fd08405555a703f2bc5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-repodata-patches/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconda-repodata-patches + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-repodata-patches/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-repodata-patches/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-repodata-patches/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-utils/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-utils/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..63b05471ee99bb35ed53f24908ae6f938c8f6401 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-utils/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconda-utils via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconda-utils -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconda-utils_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconda-utils_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconda-utils_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-utils/app/bioconda-utils_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-utils/app/bioconda-utils_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b540318abe7e23666bc10e81a8aaaeaa9a344be5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-utils/app/bioconda-utils_server.py @@ -0,0 +1,490 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# @mcp.tool() decorator is assumed to be imported from a library like 'mcp' +# In this code, it is commented out as per the instructions. + +# @mcp.tool() +def bioconductor_skeleton( + packages: List[str], + recipes: Optional[Path] = None, + config: Optional[Path] = None, + recursive: bool = False, + skip_existing: bool = False, + skip_if_in_other_channels: bool = False, + output_dir: Optional[Path] = None, + pkg_version: Optional[str] = None, + bioc_version: Optional[str] = None, + force: bool = False, +): + """ + Creates skeleton recipes for one or more Bioconductor packages. + + Args: + packages: One or more Bioconductor package names to create skeletons for. + recipes: Path to the recipes folder. + config: Path to the bioconda-utils configuration file. + recursive: If True, create recipes for missing dependencies as well. + skip_existing: If True, skip recipes that already exist. + skip_if_in_other_channels: If True, skip recipes that exist in other channels. + output_dir: Directory to write the new recipes to. Defaults to the recipes folder. + pkg_version: Specific package version to create a skeleton for. + bioc_version: Specific Bioconductor version to use. + force: If True, force creation of a recipe even if it already exists. + """ + if not packages: + raise ValueError("At least one package name must be provided.") + + cmd = ["bioconda-utils", "bioconductor-skeleton"] + if recipes: + cmd.extend(["--recipes", str(recipes)]) + if config: + cmd.extend(["--config", str(config)]) + if recursive: + cmd.append("--recursive") + if skip_existing: + cmd.append("--skip-existing") + if skip_if_in_other_channels: + cmd.append("--skip-if-in-other-channels") + if output_dir: + output_dir.mkdir(parents=True, exist_ok=True) + cmd.extend(["--output-dir", str(output_dir)]) + if pkg_version: + cmd.extend(["--pkg-version", pkg_version]) + if bioc_version: + cmd.extend(["--bioc-version", bioc_version]) + if force: + cmd.append("--force") + + cmd.extend(packages) + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True, encoding="utf-8" + ) + output_files = [str(output_dir)] if output_dir else [] + 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"Command failed with exit code {e.returncode}", + "output_files": [], + } + + +# @mcp.tool() +def cran_skeleton( + packages: List[str], + recipes: Optional[Path] = None, + config: Optional[Path] = None, + recursive: bool = False, + skip_existing: bool = False, + skip_if_in_other_channels: bool = False, + output_dir: Optional[Path] = None, + pkg_version: Optional[str] = None, + force: bool = False, +): + """ + Creates skeleton recipes for one or more CRAN packages. + + Args: + packages: One or more CRAN package names to create skeletons for. + recipes: Path to the recipes folder. + config: Path to the bioconda-utils configuration file. + recursive: If True, create recipes for missing dependencies as well. + skip_existing: If True, skip recipes that already exist. + skip_if_in_other_channels: If True, skip recipes that exist in other channels. + output_dir: Directory to write the new recipes to. Defaults to the recipes folder. + pkg_version: Specific package version to create a skeleton for. + force: If True, force creation of a recipe even if it already exists. + """ + if not packages: + raise ValueError("At least one package name must be provided.") + + cmd = ["bioconda-utils", "cran-skeleton"] + if recipes: + cmd.extend(["--recipes", str(recipes)]) + if config: + cmd.extend(["--config", str(config)]) + if recursive: + cmd.append("--recursive") + if skip_existing: + cmd.append("--skip-existing") + if skip_if_in_other_channels: + cmd.append("--skip-if-in-other-channels") + if output_dir: + output_dir.mkdir(parents=True, exist_ok=True) + cmd.extend(["--output-dir", str(output_dir)]) + if pkg_version: + cmd.extend(["--pkg-version", pkg_version]) + if force: + cmd.append("--force") + + cmd.extend(packages) + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True, encoding="utf-8" + ) + output_files = [str(output_dir)] if output_dir else [] + 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"Command failed with exit code {e.returncode}", + "output_files": [], + } + + +# @mcp.tool() +def pypi_skeleton( + packages: List[str], + recipes: Optional[Path] = None, + config: Optional[Path] = None, + recursive: bool = False, + skip_existing: bool = False, + skip_if_in_other_channels: bool = False, + output_dir: Optional[Path] = None, + pkg_version: Optional[str] = None, + python_version: Optional[str] = None, + force: bool = False, +): + """ + Creates skeleton recipes for one or more PyPI packages. + + Args: + packages: One or more PyPI package names to create skeletons for. + recipes: Path to the recipes folder. + config: Path to the bioconda-utils configuration file. + recursive: If True, create recipes for missing dependencies as well. + skip_existing: If True, skip recipes that already exist. + skip_if_in_other_channels: If True, skip recipes that exist in other channels. + output_dir: Directory to write the new recipes to. Defaults to the recipes folder. + pkg_version: Specific package version to create a skeleton for. + python_version: Python version to use for the skeleton. + force: If True, force creation of a recipe even if it already exists. + """ + if not packages: + raise ValueError("At least one package name must be provided.") + + cmd = ["bioconda-utils", "pypi-skeleton"] + if recipes: + cmd.extend(["--recipes", str(recipes)]) + if config: + cmd.extend(["--config", str(config)]) + if recursive: + cmd.append("--recursive") + if skip_existing: + cmd.append("--skip-existing") + if skip_if_in_other_channels: + cmd.append("--skip-if-in-other-channels") + if output_dir: + output_dir.mkdir(parents=True, exist_ok=True) + cmd.extend(["--output-dir", str(output_dir)]) + if pkg_version: + cmd.extend(["--pkg-version", pkg_version]) + if python_version: + cmd.extend(["--python-version", python_version]) + if force: + cmd.append("--force") + + cmd.extend(packages) + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True, encoding="utf-8" + ) + output_files = [str(output_dir)] if output_dir else [] + 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"Command failed with exit code {e.returncode}", + "output_files": [], + } + + +# @mcp.tool() +def lint( + recipes_to_lint: Optional[List[str]] = None, + recipes_folder: Optional[Path] = None, + config: Optional[Path] = None, + fail_level: str = "error", + no_fail_on_error: bool = False, + report_file: Optional[Path] = None, + exclude: Optional[List[str]] = None, +): + """ + Lints bioconda recipes to check for common errors and style issues. + + Args: + recipes_to_lint: Specific recipes to lint. Can be paths, package names, or glob patterns. + recipes_folder: Path to the top-level recipes folder. + config: Path to the bioconda-utils configuration file. + fail_level: The linting level at which to fail ('error', 'warning', 'info'). + no_fail_on_error: If True, do not exit with an error code on linting failures. + report_file: File to write the linting report to. + exclude: A list of recipes to exclude from linting. + """ + fail_level_choices = ["error", "warning", "info"] + if fail_level not in fail_level_choices: + raise ValueError(f"fail_level must be one of {fail_level_choices}") + + cmd = ["bioconda-utils", "lint"] + if recipes_folder: + cmd.extend(["--recipes", str(recipes_folder)]) + if config: + cmd.extend(["--config", str(config)]) + cmd.extend(["--fail-level", fail_level]) + if no_fail_on_error: + cmd.append("--no-fail-on-error") + if report_file: + cmd.extend(["--report-file", str(report_file)]) + if exclude: + for item in exclude: + cmd.extend(["--exclude", item]) + if recipes_to_lint: + cmd.extend(recipes_to_lint) + + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True, encoding="utf-8" + ) + output_files = [str(report_file)] if report_file else [] + 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"Command failed with exit code {e.returncode}", + "output_files": [], + } + + +# @mcp.tool() +def build( + recipes_to_build: List[str], + recipes_folder: Optional[Path] = None, + config: Optional[Path] = None, + package_folder: Optional[Path] = None, + force: bool = False, + docker: bool = False, + mulled_test: Optional[bool] = None, + extra_channels: Optional[List[str]] = None, + anaconda_upload: bool = False, + anaconda_token: Optional[str] = None, + user: Optional[str] = None, + dry_run: bool = False, +): + """ + Builds one or more bioconda recipes. + + Args: + recipes_to_build: Recipes to build. Can be paths, package names, or glob patterns. + recipes_folder: Path to the top-level recipes folder. + config: Path to the bioconda-utils configuration file. + package_folder: Folder to store the built packages. + force: If True, force the build even if the package already exists. + docker: If True, build inside a Docker container. + mulled_test: Set to True to run mulled tests, False to disable them. Default is tool's default. + extra_channels: Additional channels to use during the build. + anaconda_upload: If True, upload the built package to anaconda.org. + anaconda_token: Anaconda token for uploading. + user: Anaconda user/organization to upload to. + dry_run: If True, show what would be done without executing. + """ + if not recipes_to_build: + raise ValueError("At least one recipe must be provided to build.") + + cmd = ["bioconda-utils", "build"] + if recipes_folder: + cmd.extend(["--recipes", str(recipes_folder)]) + if config: + cmd.extend(["--config", str(config)]) + if package_folder: + package_folder.mkdir(parents=True, exist_ok=True) + cmd.extend(["--package-folder", str(package_folder)]) + if force: + cmd.append("--force") + if docker: + cmd.append("--docker") + if mulled_test is True: + cmd.append("--mulled-test") + elif mulled_test is False: + cmd.append("--no-mulled-test") + if extra_channels: + for channel in extra_channels: + cmd.extend(["-c", channel]) + if not anaconda_upload: + cmd.append("--no-anaconda-upload") + if anaconda_token: + cmd.extend(["--anaconda-token", anaconda_token]) + if user: + cmd.extend(["--user", user]) + if dry_run: + cmd.append("--dry-run") + + cmd.extend(recipes_to_build) + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True, encoding="utf-8" + ) + output_files = [str(package_folder)] if package_folder else [] + 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"Command failed with exit code {e.returncode}", + "output_files": [], + } + + +# @mcp.tool() +def dag( + recipes_for_dag: Optional[List[str]] = None, + recipes_folder: Optional[Path] = None, + config: Optional[Path] = None, + file_out: Optional[Path] = None, + format: str = "gml", +): + """ + Generates a dependency graph (DAG) for recipes. + + Args: + recipes_for_dag: Recipes to include in the DAG. If None, all recipes are considered. + recipes_folder: Path to the top-level recipes folder. + config: Path to the bioconda-utils configuration file. + file_out: Path to write the output DAG file. + format: The output format for the DAG ('gml', 'dot', 'pdf'). + """ + format_choices = ["gml", "dot", "pdf"] + if format not in format_choices: + raise ValueError(f"format must be one of {format_choices}") + + cmd = ["bioconda-utils", "dag"] + if recipes_folder: + cmd.extend(["--recipes", str(recipes_folder)]) + if config: + cmd.extend(["--config", str(config)]) + if file_out: + cmd.extend(["--file-out", str(file_out)]) + cmd.extend(["--format", format]) + if recipes_for_dag: + cmd.extend(recipes_for_dag) + + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True, encoding="utf-8" + ) + output_files = [str(file_out)] if file_out else [] + 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"Command failed with exit code {e.returncode}", + "output_files": [], + } + + +# @mcp.tool() +def update_pinning( + recipes_folder: Optional[Path] = None, + config: Optional[Path] = None, + packages: Optional[str] = None, + no_pr: bool = False, + dry_run: bool = False, +): + """ + Updates pinning in recipes based on the global pinning file. + + Args: + recipes_folder: Path to the top-level recipes folder. + config: Path to the bioconda-utils configuration file. + packages: Comma-separated string of package names to update pinning for. + no_pr: If True, do not create a pull request with the changes. + dry_run: If True, show what would be done without executing. + """ + cmd = ["bioconda-utils", "update-pinning"] + if recipes_folder: + cmd.extend(["--recipes", str(recipes_folder)]) + if config: + cmd.extend(["--config", str(config)]) + if packages: + cmd.extend(["--packages", packages]) + if no_pr: + cmd.append("--no-pr") + if dry_run: + cmd.append("--dry-run") + + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True, encoding="utf-8" + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Command failed with exit code {e.returncode}", + "output_files": [], + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-utils/app/bioconda-utils_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-utils/app/bioconda-utils_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2cb5f796bd0b739ba4918a942df1c2ac40dbde62 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-utils/app/bioconda-utils_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_bioconda-utils/app/bioconda-utils_server.py') +SERVER_NAME = 'biosci_bioconda_utils' + + +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_bioconda-utils/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-utils/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-utils/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-utils/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-utils/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..59b2d040196d910e509b5d28eb596eb531952b43 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-utils/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconda-utils: + build: . + image: mcp-bioconda-utils:latest + container_name: mcp-bioconda-utils + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconda-utils + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-utils/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-utils/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a99a6fa55b5621020aa602bcbdcfe40d729496f7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-utils/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconda-utils + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-utils/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-utils/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconda-utils/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-affy/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-affy/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..76b7331378a46587517e9b754671c8ce4eda02ba --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-affy/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-affy via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-affy -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-affy_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-affy_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-affy_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-affy/app/bioconductor-affy_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-affy/app/bioconductor-affy_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e8e82b4691230816647bcdeb9564ec455cd332b6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-affy/app/bioconductor-affy_server.py @@ -0,0 +1,196 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, Dict, List + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided by the MCP framework. +def tool(func): + def wrapper(*args, **kwargs): + # In a real scenario, the MCP framework would handle + # registration and execution. + return func(*args, **kwargs) + return wrapper +mcp = type("mcp", (), {"tool": tool}) + + +@mcp.tool +def run_affy_analysis( + cel_files_dir: Path, + output_expression_file: Path, + method: str = "rma", + pheno_data_file: Optional[Path] = None, + generate_qc_plot: bool = False, + qc_plot_file: Optional[Path] = None, +) -> Dict: + """ + Performs exploratory analysis of Affymetrix oligonucleotide arrays. + + This tool reads raw Affymetrix data from .CEL files, performs background + correction, normalization, and probe summarization using either the RMA + (Robust Multi-array Average) or MAS 5.0 algorithm, and outputs a matrix + of expression values. + + Args: + cel_files_dir: Path to the directory containing the input .CEL files. + output_expression_file: Path to write the output expression matrix (tab-separated). + method: The processing method to use. Must be one of 'rma' or 'mas5'. + Defaults to 'rma'. + pheno_data_file: Optional path to a phenodata file describing the samples. + This should be a tab-delimited file with row names matching + the .CEL file names. + generate_qc_plot: If True, generate a quality control boxplot of the raw + probe intensities. Defaults to False. + qc_plot_file: Path to save the QC plot image (e.g., plot.png). + Required if generate_qc_plot is True. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a + list of output files. + """ + # 1. Input Validation + if not cel_files_dir.is_dir(): + raise ValueError(f"Input directory '{cel_files_dir}' does not exist or is not a directory.") + + if pheno_data_file and not pheno_data_file.is_file(): + raise FileNotFoundError(f"Phenodata file '{pheno_data_file}' not found.") + + method_lower = method.lower() + if method_lower not in ["rma", "mas5"]: + raise ValueError(f"Invalid method '{method}'. Must be 'rma' or 'mas5'.") + + if generate_qc_plot: + if qc_plot_file is None: + raise ValueError("qc_plot_file must be provided when generate_qc_plot is True.") + if not qc_plot_file.parent.exists(): + qc_plot_file.parent.mkdir(parents=True, exist_ok=True) + elif qc_plot_file is not None: + print(f"Warning: qc_plot_file '{qc_plot_file}' is specified but generate_qc_plot is False. The file will not be created.") + + if not output_expression_file.parent.exists(): + output_expression_file.parent.mkdir(parents=True, exist_ok=True) + + # 2. R Script Generation + # This script will be executed by Rscript to perform the analysis. + r_script_content = f""" + # Load necessary libraries + if (!requireNamespace("affy", quietly = TRUE)) {{ + stop("The 'affy' package is not installed. Please install it from Bioconductor.") + }} + library(affy) + + # Parse command-line arguments + args <- commandArgs(trailingOnly = TRUE) + if (length(args) < 3) {{ + stop("Usage: Rscript script.R [pheno_path_or_NA] [plot_path_or_NA]", call. = FALSE) + }} + + cel_dir <- args[1] + output_path <- args[2] + method <- args[3] + pheno_path <- if (length(args) >= 4 && args[4] != "NA") args[4] else NULL + plot_path <- if (length(args) >= 5 && args[5] != "NA") args[5] else NULL + + # --- Main Logic --- + tryCatch({{ + # Read the data + cat("Reading CEL files from:", cel_dir, "\\n") + if (!is.null(pheno_path)) {{ + cat("Using pheno data from:", pheno_path, "\\n") + # read.AnnotatedDataFrame is deprecated, using read.phenoData is more modern + pheno <- read.phenoData(pheno_path, header = TRUE, row.names = 1) + data <- ReadAffy(celfile.path = cel_dir, phenoData = pheno) + }} else {{ + data <- ReadAffy(celfile.path = cel_dir) + }} + cat("Finished reading data.\\n") + + # Process the data + cat("Processing data with method:", method, "\\n") + if (method == "rma") {{ + eset <- rma(data) + }} else if (method == "mas5") {{ + eset <- mas5(data) + }} else {{ + stop(paste("Invalid method specified:", method)) + }} + cat("Finished processing.\\n") + + # Extract and write expression values + cat("Writing expression matrix to:", output_path, "\\n") + expression_matrix <- exprs(eset) + write.table(expression_matrix, file = output_path, sep = "\\t", quote = FALSE, col.names = NA) + cat("Done writing expression matrix.\\n") + + # Generate QC plot if requested + if (!is.null(plot_path)) {{ + cat("Generating QC plot at:", plot_path, "\\n") + png(filename = plot_path, width = 800, height = 600) + boxplot(data, main = "Raw Probe Intensities", las = 2, col="lightblue") + dev.off() + cat("Done generating plot.\\n") + }} + + cat("Analysis complete.\\n") + }}, error = function(e) {{ + cat("An error occurred:\\n") + cat(conditionMessage(e), "\\n") + quit(status = 1) + }}) + """ + + # 3. Subprocess Execution + output_files = {"expression_matrix": str(output_expression_file)} + cmd = ["Rscript"] + + 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 + + # Prepare arguments for the R script + pheno_path_arg = str(pheno_data_file.resolve()) if pheno_data_file else "NA" + plot_path_arg = str(qc_plot_file.resolve()) if generate_qc_plot and qc_plot_file else "NA" + + cmd.extend([ + r_script_path, + str(cel_files_dir.resolve()), + str(output_expression_file.resolve()), + method_lower, + pheno_path_arg, + plot_path_arg + ]) + + # Execute the command + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True + ) + + if generate_qc_plot and qc_plot_file: + output_files["qc_plot"] = str(qc_plot_file) + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files + } + + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode, + "output_files": {} + } + except Exception as e: + raise e + finally: + # Clean up the temporary R script file + if 'r_script_path' in locals() and Path(r_script_path).exists(): + Path(r_script_path).unlink() diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-affy/app/bioconductor-affy_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-affy/app/bioconductor-affy_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6b0f6f2c7a65d117e0529aef4a655b94d46a8c4e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-affy/app/bioconductor-affy_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-affy/app/bioconductor-affy_server.py') +SERVER_NAME = 'biosci_bioconductor_affy' + + +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-affy/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-affy/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-affy/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-affy/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-affy/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..8057d8136a4f96e7df56fbec473bb152fc7ccbbd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-affy/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-affy: + build: . + image: mcp-bioconductor-affy:latest + container_name: mcp-bioconductor-affy + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-affy + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-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-affy/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-affy/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a27582848106e01be3508dca13631cac633c09f8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-affy/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-affy + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-affy/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-affy/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-affy/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-affyio/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-affyio/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-affyio/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.sfe/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.sfe/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4749f6b50ebfb67cffb861305a1aa7d0b9f9427e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.sfe/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-alabaster.sfe via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-alabaster.sfe -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-alabaster.sfe_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-alabaster.sfe_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-alabaster.sfe_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.sfe/app/bioconductor-alabaster.sfe_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.sfe/app/bioconductor-alabaster.sfe_server.py new file mode 100644 index 0000000000000000000000000000000000000000..efe55f83942e444d9cd73289a42fa2bba266e19e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.sfe/app/bioconductor-alabaster.sfe_server.py @@ -0,0 +1,213 @@ +import subprocess +import logging +from pathlib import Path +from typing import Dict, Any, Optional + +# It is assumed that the mcp decorator is available in the execution environment. +# from mcp import tool + +# Mock decorator for local testing, not to be included in the final deliverable +# if 'mcp' not in globals(): +# class mcp: +# @staticmethod +# def tool(): +# def decorator(func): +# return func +# return decorator + +logger = logging.getLogger(__name__) + +@mcp.tool() +def stage_sfe_object( + input_rds: Path, + output_dir: Path, + path: str = "sfe", +) -> Dict[str, Any]: + """ + Stages a SpatialFeatureExperiment (SFE) object from an RDS file into the alabaster format. + + This tool wraps the 'stageObject' function from the R package 'alabaster.sfe'. + It reads an SFE object from a specified RDS file and saves it into a structured + directory according to the alabaster specification. This serves as the primary + "save" or "serialize" function for SFE objects in the alabaster framework. + + Args: + input_rds: Path to the input RDS file containing the SpatialFeatureExperiment object. + output_dir: Path to the directory where the staged object assets will be stored. + path: The relative path within 'output_dir' to save the object. Defaults to "sfe". + + Returns: + A dictionary containing the execution details and the path to the main output metadata file. + """ + # 1. Input Validation + if not input_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found at: {input_rds}") + + if not path: + raise ValueError("'path' cannot be an empty string.") + + try: + output_dir.mkdir(parents=True, exist_ok=True) + except OSError as e: + raise OSError(f"Failed to create output directory {output_dir}: {e}") + + # 2. R script construction + r_script_content = f""" + suppressPackageStartupMessages(library(alabaster.sfe)) + suppressPackageStartupMessages(library(SpatialFeatureExperiment)) + + tryCatch({{ + sfe_object <- readRDS('{input_rds.resolve()}') + info <- alabaster.base::stageObject(sfe_object, dir = '{output_dir.resolve()}', path = '{path}') + cat(file.path('{output_dir.resolve()}', info$path, "object.json")) + }}, error = function(e) {{ + message("Error during R script execution: ", e$message) + quit(status = 1) + }}) + """ + + # 3. Subprocess Execution + cmd = ["Rscript", "-e", r_script_content] + command_executed = " ".join(map(str, cmd)) + logger.info(f"Executing command: {command_executed}") + + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + encoding='utf-8' + ) + + stdout = process.stdout.strip() + stderr = process.stderr.strip() + + main_output_file = Path(stdout) + if not main_output_file.is_file(): + raise FileNotFoundError( + f"Expected output file not created: {main_output_file}. R stderr: {stderr}" + ) + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": { + "staged_object_json": str(main_output_file) + } + } + + except FileNotFoundError: + error_msg = "Error: 'Rscript' command not found. Please ensure R is installed and in your system's PATH." + logger.error(error_msg) + raise RuntimeError(error_msg) from None + except subprocess.CalledProcessError as e: + logger.error(f"Command failed with exit code {e.returncode}") + logger.error(f"STDOUT: {e.stdout}") + logger.error(f"STDERR: {e.stderr}") + raise RuntimeError( + f"R script execution failed with exit code {e.returncode}.\n" + f"STDOUT: {e.stdout}\n" + f"STDERR: {e.stderr}" + ) from e + +@mcp.tool() +def load_sfe_object( + staged_dir: Path, + output_rds: Path, + path: str = "", +) -> Dict[str, Any]: + """ + Loads a SpatialFeatureExperiment (SFE) object from the alabaster format into an RDS file. + + This tool wraps the 'loadObject' function from the R package 'alabaster.base'. + It reads an SFE object from a staged directory, reconstructs it in memory, and + saves the complete object as a single RDS file. This is the "load" or "deserialize" + counterpart to the staging function. + + Args: + staged_dir: Path to the directory containing the staged object assets. + output_rds: Path for the output RDS file where the loaded SFE object will be saved. + path: The relative path within 'staged_dir' where the object's 'object.json' is located. + If empty, it's assumed to be at the root of 'staged_dir'. + + Returns: + A dictionary containing the execution details and the path to the output RDS file. + """ + # 1. Input Validation + if not staged_dir.is_dir(): + raise NotADirectoryError(f"Staged asset directory not found at: {staged_dir}") + + metadata_json_path = staged_dir.joinpath(path, "object.json") + if not metadata_json_path.is_file(): + raise FileNotFoundError(f"Metadata file 'object.json' not found at: {metadata_json_path}") + + try: + output_rds.parent.mkdir(parents=True, exist_ok=True) + except OSError as e: + raise OSError(f"Failed to create output directory {output_rds.parent}: {e}") + + # 2. R script construction + r_script_content = f""" + suppressPackageStartupMessages(library(alabaster.sfe)) + suppressPackageStartupMessages(library(SpatialFeatureExperiment)) + + tryCatch({{ + sfe_object <- alabaster.base::loadObject( + '{metadata_json_path.resolve()}', + project = '{staged_dir.resolve()}' + ) + saveRDS(sfe_object, file = '{output_rds.resolve()}') + cat('{output_rds.resolve()}') + }}, error = function(e) {{ + message("Error during R script execution: ", e$message) + quit(status = 1) + }}) + """ + + # 3. Subprocess Execution + cmd = ["Rscript", "-e", r_script_content] + command_executed = " ".join(map(str, cmd)) + logger.info(f"Executing command: {command_executed}") + + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + encoding='utf-8' + ) + + stdout = process.stdout.strip() + stderr = process.stderr.strip() + + output_file = Path(stdout) + if not output_file.is_file() or output_file != output_rds.resolve(): + raise FileNotFoundError( + f"Expected output RDS file not created at {output_rds}. R stderr: {stderr}" + ) + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": { + "output_rds": str(output_file) + } + } + + except FileNotFoundError: + error_msg = "Error: 'Rscript' command not found. Please ensure R is installed and in your system's PATH." + logger.error(error_msg) + raise RuntimeError(error_msg) from None + except subprocess.CalledProcessError as e: + logger.error(f"Command failed with exit code {e.returncode}") + logger.error(f"STDOUT: {e.stdout}") + logger.error(f"STDERR: {e.stderr}") + raise RuntimeError( + f"R script execution failed with exit code {e.returncode}.\n" + f"STDOUT: {e.stdout}\n" + f"STDERR: {e.stderr}" + ) from e \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.sfe/app/bioconductor-alabaster.sfe_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.sfe/app/bioconductor-alabaster.sfe_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3d742e5983c42c8a31081576ac54fccc13e1849f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.sfe/app/bioconductor-alabaster.sfe_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-alabaster.sfe/app/bioconductor-alabaster.sfe_server.py') +SERVER_NAME = 'biosci_bioconductor_alabaster_sfe' + + +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-alabaster.sfe/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.sfe/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.sfe/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.sfe/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.sfe/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..3284000038c5dc43daaf9459bdb8b4ce91a55a7b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.sfe/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-alabaster.sfe: + build: . + image: mcp-bioconductor-alabaster.sfe:latest + container_name: mcp-bioconductor-alabaster.sfe + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-alabaster.sfe + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.sfe/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.sfe/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eeed48ad69a70bf01f9b3ae9eb5e5a76284e7159 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.sfe/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-alabaster.sfe + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.sfe/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.sfe/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.sfe/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.spatial/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.spatial/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..40770fc4cf44910bbe4a77f31ad3f18c226c857b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.spatial/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-alabaster.spatial via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-alabaster.spatial -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-alabaster.spatial_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-alabaster.spatial_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-alabaster.spatial_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.spatial/app/bioconductor-alabaster.spatial_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.spatial/app/bioconductor-alabaster.spatial_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0a106270b1f6bae5b7a4069bdc49142f726df900 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.spatial/app/bioconductor-alabaster.spatial_server.py @@ -0,0 +1,289 @@ +import subprocess +import tempfile +import os +from pathlib import Path +from typing import Optional, List, Dict, Any + +# No need to import mcp as per instructions. + +def _run_r_script(script_content: str, cwd: Path) -> Dict[str, Any]: + """ + Executes an R script and captures its output. + + Args: + script_content: The R script as a string. + cwd: The current working directory for the R script execution. + + Returns: + A dictionary containing execution details, including command, stdout, stderr, + and an error message if the script fails. + """ + with tempfile.NamedTemporaryFile(mode="w", suffix=".R", delete=False) as r_script_file: + r_script_file.write(script_content) + r_script_path = Path(r_script_file.name) + + command = ["Rscript", str(r_script_path)] + + stdout = "" + stderr = "" + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + cwd=cwd # Run R script in the specified working directory + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed with exit code {e.returncode}", + "output_files": [], + } + finally: + os.remove(r_script_path) + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": [], # This will be populated by the calling function + } + +@mcp.tool() +def save_spatial_experiment( + input_spatial_experiment_rds: Path, + output_directory: Path, + precomputed: bool = True, + deferred: bool = False, + compression_level: Optional[int] = None, + compression_filter: Optional[str] = None, +) -> Dict[str, Any]: + """ + Saves a SpatialExperiment object and its images into file artifacts. + + This function serializes an R SpatialExperiment object (provided as an RDS file) + into a directory structure of file artifacts, offering a portable alternative + to direct RDS serialization. The `alabaster.spatial` package handles the + conversion and storage of the object and its associated images. + + Args: + input_spatial_experiment_rds: Path to an RDS file containing the SpatialExperiment object. + This file must exist. + output_directory: Path to the directory where the file artifacts will be saved. + This directory will be created if it does not exist. + precomputed: Logical, whether to save precomputed results. Defaults to TRUE. + deferred: Logical, whether to defer saving of certain components. Defaults to FALSE. + compression_level: Integer, compression level for HDF5 files (0-9). + If None, R's default (typically 6) will be used. + compression_filter: String, compression filter for HDF5 files (e.g., "gzip", "lzf"). + If None, no specific filter is applied. + + Returns: + A dictionary containing execution details, including the command executed, + stdout, stderr, and a list of generated output files/directories. + Returns an error if input file is not found, output path is invalid, + compression_level is out of range, or R script execution fails. + """ + # Input validation + if not input_spatial_experiment_rds.is_file(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Input RDS file not found at '{input_spatial_experiment_rds}'", + "output_files": [], + } + + if output_directory.exists() and not output_directory.is_dir(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Output path '{output_directory}' exists but is not a directory.", + "output_files": [], + } + + try: + output_directory.mkdir(parents=True, exist_ok=True) + except OSError as e: + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Could not create output directory '{output_directory}': {e}", + "output_files": [], + } + + if compression_level is not None and not (0 <= compression_level <= 9): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: 'compression_level' must be an integer between 0 and 9, got {compression_level}", + "output_files": [], + } + + # Construct R script + r_script_template = """ + suppressPackageStartupMessages({{ + library(alabaster.spatial) + library(SpatialExperiment) + library(S4Vectors) + library(alabaster.base) + library(rhdf5) # Explicitly load for HDF5 operations + }}) + + input_rds_path <- "{input_rds_path}" + output_dir_path <- "{output_dir_path}" + + # Load the SpatialExperiment object + if (!file.exists(input_rds_path)) {{ + stop(paste0("Input RDS file not found: ", input_rds_path)) + }} + se_object <- readRDS(input_rds_path) + + # Ensure it's a SpatialExperiment object + if (!is(se_object, "SpatialExperiment")) {{ + stop("Loaded object is not a SpatialExperiment object.") + }} + + # Prepare additional arguments for saveObject + save_args <- list( + x = se_object, + path = output_dir_path, + precomputed = {precomputed_r}, + deferred = {deferred_r} + ) + {compression_level_r} + {compression_filter_r} + + # Call saveObject + do.call(alabaster.spatial::saveObject, save_args) + + message(paste0("SpatialExperiment object saved to: ", output_dir_path)) + """ + + compression_level_r = f"save_args$compression_level <- {compression_level}" if compression_level is not None else "" + compression_filter_r = f"save_args$compression_filter <- '{compression_filter}'" if compression_filter is not None else "" + + r_script_content = r_script_template.format( + input_rds_path=input_spatial_experiment_rds.resolve(), + output_dir_path=output_directory.resolve(), + precomputed_r=str(precomputed).upper(), + deferred_r=str(deferred).upper(), + compression_level_r=compression_level_r, + compression_filter_r=compression_filter_r, + ) + + # Execute R script + result = _run_r_script(r_script_content, output_directory.parent) # Run in parent dir to allow output_directory creation + if "error" in result: + return result + + result["output_files"] = [str(output_directory.resolve())] + return result + + +@mcp.tool() +def read_spatial_experiment( + input_directory: Path, + output_spatial_experiment_rds: Path, + metadata_only: bool = False, + image_format: Optional[str] = None, +) -> Dict[str, Any]: + """ + Loads a SpatialExperiment object and its images from file artifacts. + + This function reconstructs an R SpatialExperiment object from a directory + of file artifacts previously saved by `save_spatial_experiment`. + + Args: + input_directory: Path to the directory containing the file artifacts. + This directory must exist and be valid. + output_spatial_experiment_rds: Path to the output RDS file where the + reconstructed SpatialExperiment object will be saved. + The parent directory will be created if it does not exist. + metadata_only: Logical, whether to only load metadata and not the full data. + Defaults to FALSE. + image_format: String, desired image format for loading (e.g., "png", "jpeg", "tiff"). + If None, images are loaded in their original format. + + Returns: + A dictionary containing execution details, including the command executed, + stdout, stderr, and a list of generated output files. + Returns an error if input directory is not found, output path is invalid, + or R script execution fails. + """ + # Input validation + if not input_directory.is_dir(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Input directory not found at '{input_directory}'", + "output_files": [], + } + + if output_spatial_experiment_rds.exists() and not output_spatial_experiment_rds.is_file(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Output path '{output_spatial_experiment_rds}' exists but is not a file.", + "output_files": [], + } + + try: + output_spatial_experiment_rds.parent.mkdir(parents=True, exist_ok=True) + except OSError as e: + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Could not create parent directory for output RDS file '{output_spatial_experiment_rds}': {e}", + "output_files": [], + } + + # Construct R script + r_script_template = """ + suppressPackageStartupMessages({{ + library(alabaster.spatial) + library(SpatialExperiment) + library(S4Vectors) + library(alabaster.base) + library(rhdf5) # Explicitly load for HDF5 operations + }}) + + input_dir_path <- "{input_dir_path}" + output_rds_path <- "{output_rds_path}" + + # Prepare additional arguments for readObject + read_args <- list( + path = input_dir_path, + metadata.only = {metadata_only_r} + ) + {image_format_r} + + # Call readObject + se_object <- do.call(alabaster.spatial::readObject, read_args) + + # Save the SpatialExperiment object to RDS + saveRDS(se_object, file = output_rds_path) + + message(paste0("SpatialExperiment object loaded from: ", input_dir_path, " and saved to: ", output_rds_path)) + """ + + image_format_r = f"read_args$image.format <- '{image_format}'" if image_format is not None else "" + + r_script_content = r_script_template.format( + input_dir_path=input_directory.resolve(), + output_rds_path=output_spatial_experiment_rds.resolve(), + metadata_only_r=str(metadata_only).upper(), + image_format_r=image_format_r, + ) + + # Execute R script + result = _run_r_script(r_script_content, output_spatial_experiment_rds.parent) + if "error" in result: + return result + + result["output_files"] = [str(output_spatial_experiment_rds.resolve())] + return result \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.spatial/app/bioconductor-alabaster.spatial_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.spatial/app/bioconductor-alabaster.spatial_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..63c86c9addbd69b02c55f1933afb50eff359707c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.spatial/app/bioconductor-alabaster.spatial_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-alabaster.spatial/app/bioconductor-alabaster.spatial_server.py') +SERVER_NAME = 'biosci_bioconductor_alabaster_spatial' + + +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-alabaster.spatial/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.spatial/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..9077879ad1f81983e4ba6ace465ba860f645b5be --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.spatial/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-alabaster.spatial: + build: . + image: mcp-bioconductor-alabaster.spatial:latest + container_name: mcp-bioconductor-alabaster.spatial + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-alabaster.spatial + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.spatial/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.spatial/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..329b888afd15efdc23d52fc58fe6ff2376c71013 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.spatial/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-alabaster.spatial + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.spatial/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.spatial/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster.spatial/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..adf3034b80c6daf061e68aa17f25bd39e1e1eb37 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-alabaster via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-alabaster -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-alabaster_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-alabaster_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-alabaster_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster/app/bioconductor-alabaster_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster/app/bioconductor-alabaster_server.py new file mode 100644 index 0000000000000000000000000000000000000000..adb75c86deee5de88a84fd7b75fd2c59e6bb05cd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster/app/bioconductor-alabaster_server.py @@ -0,0 +1,66 @@ +import subprocess +import sys +from pathlib import Path +from typing import Optional, List +import tempfile +import logging + +# Configure logging +logging.basicConfig(level=logging.INFO) + +# Mock mcp.tool decorator for standalone execution +class mcp: + def tool(func): + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + return wrapper + +@mcp.tool +def alabaster_check(): + """ + Verifies the installation of the bioconductor-alabaster umbrella package. + + This tool does not perform any data analysis. Instead, it attempts to load + the 'alabaster' library within an R session to confirm that the Alabaster + framework and all its components are correctly installed and accessible. + A successful execution indicates the environment is ready for tools that + depend on the Alabaster suite. + """ + command = ["Rscript", "-e", "library(alabaster)"] + command_str = " ".join(command) + logging.info(f"Executing command: {command_str}") + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + stdout = process.stdout + stderr = process.stderr + logging.info("bioconductor-alabaster package loaded successfully.") + + except FileNotFoundError: + logging.error("Rscript not found. Please ensure R is installed and in your PATH.") + # Re-raise with a more informative message for the MCP context + raise RuntimeError("Rscript executable not found. R installation is required.") from None + + except subprocess.CalledProcessError as e: + logging.error(f"Error loading bioconductor-alabaster package.") + logging.error(f"Stderr: {e.stderr}") + logging.error(f"Stdout: {e.stdout}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to load the 'alabaster' R library. It may not be installed correctly.", + "return_code": e.returncode, + } + + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": stderr, + "status": "success" + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster/app/bioconductor-alabaster_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster/app/bioconductor-alabaster_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..cc74b65c67978db74b3b68cbf40b0f03e61e9912 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster/app/bioconductor-alabaster_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-alabaster/app/bioconductor-alabaster_server.py') +SERVER_NAME = 'biosci_bioconductor_alabaster' + + +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-alabaster/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..1e7f78ab1fdc06a0f6527a02824e5ac4283ab2f5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-alabaster: + build: . + image: mcp-bioconductor-alabaster:latest + container_name: mcp-bioconductor-alabaster + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-alabaster + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..005b89505905813f059b39eff70b16c86b5b6306 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-alabaster + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ancombc/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ancombc/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..66ba2c07f5ba40e55a52d2cfb656ebaf930c87a3 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ancombc/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-ancombc via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-ancombc -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-ancombc_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-ancombc_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-ancombc_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ancombc/app/bioconductor-ancombc_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ancombc/app/bioconductor-ancombc_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5f4f1ae809aaa666e96b04e26f071abfb81fc2d1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ancombc/app/bioconductor-ancombc_server.py @@ -0,0 +1,251 @@ +import subprocess +import tempfile +import textwrap +from pathlib import Path +from typing import Dict, List, Optional + +# @mcp.tool() is a placeholder for the actual decorator. +# The function is written to be compatible with the MCP server environment. +def mcp_tool_placeholder(*args, **kwargs): + def decorator(func): + return func + return decorator + +@mcp_tool_placeholder() +def ancombc2( + otu_table: Path, + sample_metadata: Path, + formula: str, + output_dir: Path, + taxonomy_table: Optional[Path] = None, + p_adj_method: str = "holm", + zero_cut: float = 0.9, + lib_cut: int = 1000, + struc_zero: bool = False, + neg_lb: bool = False, + tol: float = 1e-05, + max_iter: int = 100, + conserve: bool = False, + alpha: float = 0.05, + global_test: bool = False, + group: Optional[str] = None, + mdfdr_dist: str = "normal", + n_cl: int = 1, + verbose: bool = False, + output_prefix: str = "ancombc2_results", +) -> Dict: + """ + Performs differential abundance analysis on microbiome data using ANCOM-BC2. + + ANCOM-BC2 (Analysis of Compositions of Microbiomes with Bias Correction 2) is a + method for identifying differentially abundant taxa between groups while correcting + for sample-specific and taxon-specific biases. + + Args: + otu_table: Path to the feature/OTU count table (CSV format). Rows should be taxa + and columns should be samples. The first column should be taxon IDs. + sample_metadata: Path to the sample metadata file (CSV format). Rows should be + samples and columns should be metadata variables. The first + column should be sample IDs. + formula: An R-style formula string specifying the model, e.g., "age + sex + diagnosis". + Variables must correspond to columns in the sample_metadata file. + output_dir: Path to the directory where output files will be saved. + taxonomy_table: Optional path to the taxonomy table (CSV format). Rows should be + taxa, columns should be taxonomic ranks. The first column must + be taxon IDs matching the OTU table. + p_adj_method: Method for p-value adjustment. + Options: "holm", "hochberg", "hommel", "bonferroni", "BH", "BY", "fdr", "none". + zero_cut: A numerical value between 0 and 1. Taxa with a proportion of zeros greater + than this value will be excluded from the analysis. + lib_cut: A numerical value. Samples with library sizes less than this value will be + excluded from the analysis. + struc_zero: Whether to detect structural zeros. + neg_lb: Whether to use the negative binomial distribution for modeling sampling fractions. + If FALSE, a log-linear model is used. + tol: Convergence tolerance for the optimization algorithm. + max_iter: Maximum number of iterations for the optimization algorithm. + conserve: Whether to use a conservative variance estimate for the test statistic. + alpha: Significance level for identifying differentially abundant taxa. + global_test: Whether to perform a global test for the specified group variable. + group: The name of the group variable for the global test. Required if `global_test` is True. + Must be a column name in the sample_metadata file. + mdfdr_dist: The assumed distribution of the E-values in m-DFDR. + Options: "normal", "t". + n_cl: Number of CPU cores to use for parallel computation. + verbose: Whether to display progress messages during execution. + output_prefix: Prefix for the output result files. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of + paths to the generated output files. + """ + # --- 1. Input Validation --- + if not otu_table.is_file(): + raise FileNotFoundError(f"OTU table not found at: {otu_table}") + if not sample_metadata.is_file(): + raise FileNotFoundError(f"Sample metadata not found at: {sample_metadata}") + if taxonomy_table and not taxonomy_table.is_file(): + raise FileNotFoundError(f"Taxonomy table not found at: {taxonomy_table}") + + p_adj_methods = ["holm", "hochberg", "hommel", "bonferroni", "BH", "BY", "fdr", "none"] + if p_adj_method not in p_adj_methods: + raise ValueError(f"Invalid p_adj_method '{p_adj_method}'. Must be one of {p_adj_methods}") + + mdfdr_dists = ["normal", "t"] + if mdfdr_dist not in mdfdr_dists: + raise ValueError(f"Invalid mdfdr_dist '{mdfdr_dist}'. Must be one of {mdfdr_dists}") + + if not 0 <= zero_cut <= 1: + raise ValueError("zero_cut must be between 0 and 1.") + if not 0 < alpha < 1: + raise ValueError("alpha must be between 0 and 1.") + if lib_cut < 0: + raise ValueError("lib_cut must be a non-negative integer.") + if max_iter <= 0: + raise ValueError("max_iter must be a positive integer.") + if n_cl <= 0: + raise ValueError("n_cl must be a positive integer.") + if tol <= 0: + raise ValueError("tol must be a positive float.") + + if global_test and not group: + raise ValueError("The 'group' parameter is required when 'global_test' is True.") + + # --- 2. Prepare for Execution --- + output_dir.mkdir(parents=True, exist_ok=True) + + output_res_path = output_dir / f"{output_prefix}_DA.csv" + output_files = [str(output_res_path)] + + output_global_res_path = output_dir / f"{output_prefix}_global.csv" + if global_test: + output_files.append(str(output_global_res_path)) + + # Convert Python types to R-compatible strings + r_tax_file = f"'{taxonomy_table.resolve()}'" if taxonomy_table else "NULL" + r_group = f"'{group}'" if group else "NULL" + r_struc_zero = "TRUE" if struc_zero else "FALSE" + r_neg_lb = "TRUE" if neg_lb else "FALSE" + r_conserve = "TRUE" if conserve else "FALSE" + r_global_test = "TRUE" if global_test else "FALSE" + r_verbose = "TRUE" if verbose else "FALSE" + + # --- 3. Generate R Script --- + r_script_content = textwrap.dedent(f""" + # Load required libraries + library(ANCOMBC) + library(phyloseq) + + # --- Parameters --- + otu_file <- '{otu_table.resolve()}' + meta_file <- '{sample_metadata.resolve()}' + tax_file <- {r_tax_file} + output_res_path <- '{output_res_path.resolve()}' + output_global_res_path <- '{output_global_res_path.resolve()}' + + # --- Load and prepare data --- + # read.csv with row.names = 1 assumes first column is the index + otu_mat <- as.matrix(read.csv(otu_file, row.names = 1, check.names = FALSE)) + meta_data <- read.csv(meta_file, row.names = 1, check.names = FALSE) + + # Ensure sample names match and are in the same order + samples_in_common <- intersect(rownames(meta_data), colnames(otu_mat)) + if (length(samples_in_common) == 0) {{ + stop("No common sample IDs found between OTU table and metadata.") + }} + otu_mat <- otu_mat[, samples_in_common, drop = FALSE] + meta_data <- meta_data[samples_in_common, , drop = FALSE] + + OTU <- otu_table(otu_mat, taxa_are_rows = TRUE) + META <- sample_data(meta_data) + + # Load taxonomy if provided + if (!is.null(tax_file)) {{ + tax_mat <- as.matrix(read.csv(tax_file, row.names = 1, check.names = FALSE)) + # Ensure taxon names match + taxa_in_common <- intersect(rownames(tax_mat), rownames(otu_mat)) + if (length(taxa_in_common) == 0) {{ + warning("No common taxon IDs found between OTU table and taxonomy table. Proceeding without taxonomy.") + pseq <- phyloseq(OTU, META) + }} else {{ + tax_mat_filtered <- tax_mat[taxa_in_common, , drop = FALSE] + TAX <- tax_table(tax_mat_filtered) + pseq <- phyloseq(OTU, META, TAX) + }} + }} else {{ + pseq <- phyloseq(OTU, META) + }} + + # --- Run ANCOM-BC2 --- + output <- ancombc2( + data = pseq, + formula = "{formula}", + p_adj_method = "{p_adj_method}", + zero_cut = {zero_cut}, + lib_cut = {lib_cut}, + struc_zero = {r_struc_zero}, + neg_lb = {r_neg_lb}, + tol = {tol}, + max_iter = {max_iter}, + conserve = {r_conserve}, + alpha = {alpha}, + global = {r_global_test}, + group = {r_group}, + mdfdr_dist = "{mdfdr_dist}", + n_cl = {n_cl}, + verbose = {r_verbose} + ) + + # --- Save results --- + # Save differential abundance results + res_df <- data.frame(output$res) + write.csv(res_df, file = output_res_path, row.names = TRUE) + + # Save global test results if applicable + if ({r_global_test} && !is.null(output$res_global)) {{ + res_global_df <- data.frame(output$res_global) + write.csv(res_global_df, file = output_global_res_path, row.names = TRUE) + }} + + print("ANCOM-BC2 analysis completed successfully.") + """) + + # --- 4. Execute --- + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R") as r_script_file: + r_script_file.write(r_script_content) + r_script_path = r_script_file.name + + command = ["Rscript", r_script_path] + command_executed = " ".join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + stdout = result.stdout + stderr = result.stderr + except subprocess.CalledProcessError as e: + # Clean up the temporary script file on error + Path(r_script_path).unlink() + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + "output_files": [] + } + finally: + # Ensure temporary script is always cleaned up + if Path(r_script_path).exists(): + Path(r_script_path).unlink() + + # --- 5. Return results --- + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ancombc/app/bioconductor-ancombc_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ancombc/app/bioconductor-ancombc_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ce6190337cbf3a56bf4b0bbe8a7efa1d4d7db756 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ancombc/app/bioconductor-ancombc_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-ancombc/app/bioconductor-ancombc_server.py') +SERVER_NAME = 'biosci_bioconductor_ancombc' + + +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-ancombc/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ancombc/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ancombc/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ancombc/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ancombc/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..56a3995e609e7415b0dafb7f808bab03c3b49280 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ancombc/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-ancombc: + build: . + image: mcp-bioconductor-ancombc:latest + container_name: mcp-bioconductor-ancombc + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-ancombc + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ancombc/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ancombc/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6b5c51800f55fd28df265e465d5f20d94684402c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ancombc/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-ancombc + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ancombc/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ancombc/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ancombc/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-annotationfilter/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-annotationfilter/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..baf9c1e2c5a0c01da8fd1ed50638ade5d8afd8a3 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-annotationfilter/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-annotationfilter via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-annotationfilter -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-annotationfilter_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-annotationfilter_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-annotationfilter_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-annotationfilter/app/bioconductor-annotationfilter_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-annotationfilter/app/bioconductor-annotationfilter_server.py new file mode 100644 index 0000000000000000000000000000000000000000..dbae0549a8e5de454b0ee5bb551242d22d51045b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-annotationfilter/app/bioconductor-annotationfilter_server.py @@ -0,0 +1,285 @@ +import subprocess +import json +from typing import List, Optional, Union +from pathlib import Path + +@mcp.tool() +def create_individual_filter( + filter_class: str, + value: Union[str, List[str]], + condition: str = "==", +) -> dict: + """ + Create an individual AnnotationFilter object (e.g., GeneIdFilter, SymbolFilter). + + Args: + filter_class: The class of the filter (e.g., 'GeneIdFilter', 'SymbolFilter', 'EntrezFilter', + 'GenenameFilter', 'TxIdFilter', 'ExonIdFilter', 'ProteinIdFilter', 'UniprotFilter', + 'SeqNameFilter', 'SeqStrandFilter', 'SeqStartFilter', 'SeqEndFilter', + 'GeneBiotypeFilter', 'TxBiotypeFilter'). + value: The value(s) to filter by. Can be a single string or a list of strings. + condition: The filter condition. Supported: '==', '!=', 'startsWith', 'endsWith', 'contains', '>', '<', '>=', '<='. + """ + # Validation of filter classes + valid_classes = [ + "CdsEndFilter", "CdsStartFilter", "EntrezFilter", "ExonIdFilter", "ExonRankFilter", + "ExonEndFilter", "ExonStartFilter", "GeneIdFilter", "GeneBiotypeFilter", "GenenameFilter", + "GeneStartFilter", "GeneEndFilter", "ProteinIdFilter", "SeqNameFilter", "SeqStrandFilter", + "SymbolFilter", "TxIdFilter", "TxBiotypeFilter", "TxStartFilter", "TxEndFilter", "UniprotFilter" + ] + if filter_class not in valid_classes: + return {"error": f"Invalid filter_class. Must be one of: {', '.join(valid_classes)}"} + + # Validation of conditions + valid_conditions = ["==", "!=", "startsWith", "endsWith", "contains", ">", "<", ">=", "<="] + if condition not in valid_conditions: + return {"error": f"Invalid condition. Must be one of: {', '.join(valid_conditions)}"} + + # Format value for R + if isinstance(value, list): + r_value = 'c(' + ', '.join([f'"{v}"' for v in value]) + ')' + else: + r_value = f'"{value}"' + + r_script = f""" + suppressPackageStartupMessages(library(AnnotationFilter)) + f <- {filter_class}({r_value}, condition = "{condition}") + cat(as.character(f), "\\n") + print(f) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e '{r_script.strip()}'", + "stdout": result.stdout, + "stderr": result.stderr, + "filter_string": result.stdout.splitlines()[0] if result.stdout else "" + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def parse_filter_formula( + formula: str, +) -> dict: + """ + Create an AnnotationFilter object using the R formula syntax. + + Args: + formula: An R formula string representing the filter, e.g., '~ symbol == "ADA"' or '~ gene_id %in% c("1", "2")'. + """ + if not formula.startswith("~"): + formula = "~ " + formula + + r_script = f""" + suppressPackageStartupMessages(library(AnnotationFilter)) + f <- AnnotationFilter({formula}) + print(f) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e '{r_script.strip()}'", + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to parse formula. Ensure syntax is correct (e.g., '~ symbol == \"ADA\"')", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def create_filter_list( + filters: List[str], + logic_op: str = "&", +) -> dict: + """ + Combine multiple AnnotationFilter objects into an AnnotationFilterList. + + Args: + filters: A list of R filter construction strings, e.g., ['GeneIdFilter("123")', 'SymbolFilter("ADA")']. + logic_op: The logical operator to combine filters. Use '&' for AND, '|' for OR. + """ + if logic_op not in ["&", "|"]: + return {"error": "logic_op must be '&' or '|'"} + + # Construct the R list + filter_list_str = ", ".join(filters) + + r_script = f""" + suppressPackageStartupMessages(library(AnnotationFilter)) + fl <- AnnotationFilterList({filter_list_str}, logicOp = "{logic_op}") + print(fl) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e '{r_script.strip()}'", + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to create filter list. Ensure individual filter strings are valid R code.", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def get_filter_properties( + filter_expression: str, +) -> dict: + """ + Extract properties (field, value, condition) from an AnnotationFilter object. + + Args: + filter_expression: An R string that creates a filter, e.g., 'GeneIdFilter("ENSG0001")'. + """ + r_script = f""" + suppressPackageStartupMessages(library(AnnotationFilter)) + f <- {filter_expression} + cat("field:", field(f), "\\n") + cat("condition:", condition(f), "\\n") + cat("value:", paste(value(f), collapse=", "), "\\n") + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e '{r_script.strip()}'", + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to extract properties. Ensure the filter expression is valid.", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def list_supported_filters() -> dict: + """ + List all supported filter classes and conditions in the AnnotationFilter package. + """ + r_script = """ + suppressPackageStartupMessages(library(AnnotationFilter)) + # Get all classes that inherit from AnnotationFilter + # This is a simplified list based on package documentation + filters <- c( + "CdsEndFilter", "CdsStartFilter", "EntrezFilter", "ExonIdFilter", "ExonRankFilter", + "ExonEndFilter", "ExonStartFilter", "GeneIdFilter", "GeneBiotypeFilter", "GenenameFilter", + "GeneStartFilter", "GeneEndFilter", "ProteinIdFilter", "SeqNameFilter", "SeqStrandFilter", + "SymbolFilter", "TxIdFilter", "TxBiotypeFilter", "TxStartFilter", "TxEndFilter", "UniprotFilter" + ) + conditions <- c("==", "!=", "startsWith", "endsWith", "contains", ">", "<", ">=", "<=") + + cat("Supported Filters:\\n") + cat(paste("-", filters, collapse="\\n"), "\\n\\n") + cat("Supported Conditions:\\n") + cat(paste("-", conditions, collapse="\\n"), "\\n") + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "Rscript -e '...'", + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to list filters", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def translate_to_sql_where( + filter_expression: str, +) -> dict: + """ + Translate an AnnotationFilter object into a SQL WHERE clause fragment. + Note: This is a conceptual translation as used by packages like ensembldb. + + Args: + filter_expression: An R string that creates a filter, e.g., 'GeneIdFilter("ENSG0001")'. + """ + # In AnnotationFilter, the translation is often handled by the consuming package (like ensembldb) + # but we can simulate the logic here for the user. + r_script = f""" + suppressPackageStartupMessages(library(AnnotationFilter)) + f <- {filter_expression} + + # Simple translation logic + cond <- condition(f) + val <- value(f) + fld <- field(f) + + if (length(val) > 1) {{ + sql_val <- paste0("('", paste(val, collapse="', '"), "')") + sql_cond <- if (cond == "==") "IN" else "NOT IN" + }} else {{ + sql_val <- paste0("'", val, "'") + sql_cond <- cond + if (cond == "startsWith") {{ sql_cond <- "LIKE"; sql_val <- paste0("'", val, "%'") }} + if (cond == "endsWith") {{ sql_cond <- "LIKE"; sql_val <- paste0("'% ", val, "'") }} + if (cond == "contains") {{ sql_cond <- "LIKE"; sql_val <- paste0("'%", val, "%'") }} + }} + + cat(paste(fld, sql_cond, sql_val)) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e '{r_script.strip()}'", + "sql_fragment": result.stdout.strip(), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to translate filter", + "stdout": e.stdout, + "stderr": e.stderr + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-annotationfilter/app/bioconductor-annotationfilter_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-annotationfilter/app/bioconductor-annotationfilter_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e326c08c82821ed4c279a5188d8d498a5908b924 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-annotationfilter/app/bioconductor-annotationfilter_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-annotationfilter/app/bioconductor-annotationfilter_server.py') +SERVER_NAME = 'biosci_bioconductor_annotationfilter' + + +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-annotationfilter/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-annotationfilter/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-annotationfilter/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-annotationfilter/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-annotationfilter/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..3e5c25a320a47cb58d47530969489723508c8036 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-annotationfilter/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-annotationfilter: + build: . + image: mcp-bioconductor-annotationfilter:latest + container_name: mcp-bioconductor-annotationfilter + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-annotationfilter + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-annotationfilter/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-annotationfilter/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2ed4c145c4fe4f9efb73b977f45a6e005ebe1725 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-annotationfilter/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-annotationfilter + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-annotationfilter/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-annotationfilter/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-annotationfilter/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-annotationhub/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-annotationhub/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-annotationhub/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-apl/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-apl/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..12d5dbd56f0614e144adc7e9f202e95644c3a163 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-apl/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-apl via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-apl -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-apl_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-apl_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-apl_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-apl/app/bioconductor-apl_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-apl/app/bioconductor-apl_server.py new file mode 100644 index 0000000000000000000000000000000000000000..59a86db1ac30fab81e9c14a5f6a88f40466ffe54 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-apl/app/bioconductor-apl_server.py @@ -0,0 +1,288 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any + +# Note: mcp is not imported as per instructions. + +@mcp.tool() +def run_apl_analysis( + input_seurat_object: Path, + output_directory: Path, + cluster_column: str, + selected_cluster: Optional[str] = None, + organism: Optional[str] = None, + min_genes_per_cluster: int = 5, + top_n_genes_for_report: int = 50, + generate_interactive_plots: bool = False, +) -> Dict[str, Any]: + """ + Performs a hypothetical APL (Association Plots) analysis on single-cell transcriptomics data. + + This function serves as a placeholder for integrating the bioconductor-apl R package. + **Crucially, the specific R functions and their parameters from the APL package + are NOT available in the provided documentation.** Therefore, the R script + executed by this tool contains illustrative placeholders for APL package + function calls. + + In a real implementation, the R script would be populated with specific + calls to functions from the APL R package (e.g., `APL::runAPL`, `APL::plotAP`, + `APL::calculateSpecificityScores`) based on its official documentation + (e.g., the APL Reference Manual PDF or vignettes). + + Args: + input_seurat_object: Path to an RDS file containing a Seurat object or + SingleCellExperiment object. This is the primary input + single-cell data. + output_directory: Path to the directory where output files (plots, + specificity scores, summary) will be saved. + The directory will be created if it does not exist. + cluster_column: The name of the column in the Seurat object's metadata + (or SingleCellExperiment's colData) that contains + cell cluster assignments. + selected_cluster: Optional. If provided, the analysis might focus on + this specific cluster for detailed plots or reports. + Defaults to None, meaning analysis might cover all clusters. + organism: Optional. Specifies the organism for gene annotation, + e.g., 'human' or 'mouse'. This influences which `org.db` + package (`org.Hs.eg.db` or `org.Mm.eg.db`) might be loaded + by the R script. Defaults to None. + min_genes_per_cluster: Hypothetical. Minimum number of genes required + for a cluster to be considered in certain analyses. + Defaults to 5. + top_n_genes_for_report: Hypothetical. Number of top cluster-specific genes + to include in summary reports or plots. Defaults to 50. + generate_interactive_plots: Hypothetical. If True, attempts to generate + interactive plots using `plotly` (if APL supports it). + Defaults to False. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list + of generated output files. + """ + # Input validation + if not input_seurat_object.is_file(): + raise FileNotFoundError(f"Input Seurat/SingleCellExperiment object not found: {input_seurat_object}") + + output_directory.mkdir(parents=True, exist_ok=True) + + # Determine organism-specific package to load in R + org_db_package_load = "" + if organism: + if organism.lower() == "human": + org_db_package_load = "BiocManager::install('org.Hs.eg.db', update = FALSE, ask = FALSE); library(org.Hs.eg.db)" + elif organism.lower() == "mouse": + org_db_package_load = "BiocManager::install('org.Mm.eg.db', update = FALSE, ask = FALSE); library(org.Mm.eg.db)" + else: + # This is a hypothetical validation, as APL might support more or less organisms + raise ValueError(f"Unsupported organism: {organism}. Only 'human' and 'mouse' are hypothetically supported for gene annotation.") + + # R script template + # This template includes installation of common dependencies and placeholders + # for the actual APL package function calls. + R_SCRIPT_TEMPLATE = f""" + # Ensure BiocManager is installed for package management + if (!require("BiocManager", quietly = TRUE)) install.packages("BiocManager") + + # Install APL and its core dependencies (as inferred from conda/bioconductor info) + # update=FALSE and ask=FALSE are used to prevent interactive prompts and unnecessary updates + BiocManager::install("APL", update = FALSE, ask = FALSE) + BiocManager::install("Seurat", update = FALSE, ask = FALSE) + BiocManager::install("SingleCellExperiment", update = FALSE, ask = FALSE) + BiocManager::install("ggplot2", update = FALSE, ask = FALSE) + BiocManager::install("plotly", update = FALSE, ask = FALSE) + BiocManager::install("magrittr", update = FALSE, ask = FALSE) + BiocManager::install("SummarizedExperiment", update = FALSE, ask = FALSE) + BiocManager::install("topGO", update = FALSE, ask = FALSE) + BiocManager::install("methods", update = FALSE, ask = FALSE) + BiocManager::install("stats", update = FALSE, ask = FALSE) + BiocManager::install("utils", update = FALSE, ask = FALSE) + BiocManager::install("rlang", update = FALSE, ask = FALSE) + BiocManager::install("ggrepel", update = FALSE, ask = FALSE) + BiocManager::install("viridisLite", update = FALSE, ask = FALSE) + BiocManager::install("reticulate", update = FALSE, ask = FALSE) # For python dependencies if APL uses them + BiocManager::install("Matrix", update = FALSE, ask = FALSE) # From conda search (r-matrix) + BiocManager::install("RSpectra", update = FALSE, ask = FALSE) # From conda search (r-rspectra) + BiocManager::install("SeuratObject", update = FALSE, ask = FALSE) # From conda search (r-seuratobject) + + # Load organism-specific gene annotation database if specified + {org_db_package_load} + + # Load necessary libraries + library(APL) + library(Seurat) + library(SingleCellExperiment) + library(ggplot2) + library(plotly) + library(magrittr) # For %>% + library(SummarizedExperiment) + library(topGO) + library(methods) + library(stats) + library(utils) + library(rlang) + library(ggrepel) + library(viridisLite) + library(reticulate) # If APL uses python/pytorch/numpy via reticulate + + # Set output directory + output_dir <- "{output_directory}" + dir.create(output_dir, showWarnings = FALSE) + + # Load input data + # Assuming input_seurat_object is a path to an RDS file containing a Seurat object + seurat_obj <- readRDS("{input_seurat_object}") + + # Ensure the object is in a format APL expects, e.g., SingleCellExperiment + # APL's dependencies include both Seurat and SingleCellExperiment, + # so it might accept either or have conversion utilities. + # For robustness, we convert to SingleCellExperiment if it's a Seurat object. + if (inherits(seurat_obj, "Seurat")) {{ + message("Converting Seurat object to SingleCellExperiment for APL analysis.") + sce_obj <- as.SingleCellExperiment(seurat_obj) + }} else if (inherits(seurat_obj, "SingleCellExperiment")) {{ + sce_obj <- seurat_obj + }} else {{ + stop("Input object must be a Seurat or SingleCellExperiment object.") + }} + + # Validate cluster_column presence in colData + if (!("{cluster_column}" %in% names(colData(sce_obj)))) {{ + stop(paste0("Cluster column '", "{cluster_column}", "' not found in colData of the input object.")) + }} + + # --- Placeholder for actual APL function calls --- + # The following R code is illustrative and based on the package description. + # It needs to be replaced with actual function calls from the APL R package + # documentation (e.g., APL::runAPL, APL::plotAP, APL::calculateSpecificityScores). + + tryCatch({{ + message("Starting hypothetical APL analysis...") + + # In a real scenario, you would call APL functions here, for example: + # 1. Run Correspondence Analysis and prepare APL-specific data structure: + # apl_results_obj <- APL::runAPL(sce_obj, group_by = "{cluster_column}", + # min_genes = {min_genes_per_cluster}) + # + # 2. Calculate gene specificity scores: + # specificity_scores_df <- APL::calculateSpecificityScores(apl_results_obj) + # write.csv(specificity_scores_df, file.path(output_dir, "gene_specificity_scores.csv"), row.names = FALSE) + # + # 3. Generate Association Plots: + # if (!is.null("{selected_cluster_r_val}")) {{ + # ap_plot_selected <- APL::plotAssociationPlot(apl_results_obj, cluster = "{selected_cluster}", + # top_n = {top_n_genes_for_report}) + # ggplot2::ggsave(file.path(output_dir, "association_plot_{selected_cluster}.png"), ap_plot_selected, width = 10, height = 8) + # }} else {{ + # ap_plot_all <- APL::plotAssociationPlot(apl_results_obj, top_n = {top_n_genes_for_report}) + # ggplot2::ggsave(file.path(output_dir, "association_plot_all_clusters.png"), ap_plot_all, width = 10, height = 8) + # }} + # + # 4. Generate interactive plots if requested (assuming APL has such a function): + # if ({'TRUE' if generate_interactive_plots else 'FALSE'}) {{ + # interactive_ap_plot <- APL::plotInteractiveAP(apl_results_obj) + # htmlwidgets::saveWidget(interactive_ap_plot, file.path(output_dir, "interactive_association_plot.html")) + # }} + + # --- Dummy output generation for demonstration --- + # Create a dummy output file to simulate a summary report + dummy_output_path <- file.path(output_dir, "apl_analysis_summary.txt") + file_conn <- file(dummy_output_path) + writeLines(c( + "APL Analysis Summary (Hypothetical Output)", + paste("Input object:", "{input_seurat_object}"), + paste("Cluster column:", "{cluster_column}"), + paste("Selected cluster (if any):", "{selected_cluster_r_val}"), + paste("Organism (if specified):", "{organism_r_val}"), + paste("Min genes per cluster (hypothetical):", "{min_genes_per_cluster}"), + paste("Top N genes for report (hypothetical):", "{top_n_genes_for_report}"), + paste("Generate interactive plots (hypothetical):", "{'TRUE' if generate_interactive_plots else 'FALSE'}"), + "", + "This is a placeholder output. In a real scenario, APL functions would generate", + "cluster-specific gene lists, specificity scores (e.g., gene_specificity_scores.csv),", + "and various plots (e.g., Association Plots as PNGs and/or interactive HTMLs)." + ), file_conn) + close(file_conn) + + # Save a dummy plot (PNG) + p_png <- ggplot2::ggplot(data.frame(x=1:10, y=1:10, cluster=factor(rep(1:2, each=5))), ggplot2::aes(x,y, color=cluster)) + + ggplot2::geom_point() + + ggplot2::ggtitle("Dummy APL Plot (PNG)") + + ggplot2::theme_minimal() + ggplot2::ggsave(file.path(output_dir, "dummy_apl_plot.png"), p_png, width = 7, height = 5) + + # Save a dummy interactive plot (HTML) if requested + if ({'TRUE' if generate_interactive_plots else 'FALSE'}) {{ + p_html <- plotly::ggplotly(p_png) + htmlwidgets::saveWidget(p_html, file.path(output_dir, "dummy_apl_interactive_plot.html")) + }} + + message("Hypothetical APL analysis completed. Check output directory for dummy files.") + + }}, error = function(e) {{ + stop(paste("R Error:", e$message)) + }}) + """ + + # Prepare R-compatible values for optional parameters + selected_cluster_r_val = f"'{selected_cluster}'" if selected_cluster is not None else "NULL" + organism_r_val = f"'{organism}'" if organism is not None else "NULL" + + # Replace placeholders in the R script content + r_script_content = R_SCRIPT_TEMPLATE.format( + input_seurat_object=input_seurat_object.as_posix(), + output_directory=output_directory.as_posix(), + cluster_column=cluster_column, + selected_cluster=selected_cluster, # Used for filename, not R value + selected_cluster_r_val=selected_cluster_r_val, # Used for R code + organism=organism, # Used for filename/summary, not R value + organism_r_val=organism_r_val, # Used for R code + min_genes_per_cluster=min_genes_per_cluster, + top_n_genes_for_report=top_n_genes_for_report, + generate_interactive_plots=generate_interactive_plots, + ) + + # Create a temporary R script file + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".R") as temp_r_script: + temp_r_script.write(r_script_content) + temp_r_script_path = Path(temp_r_script.name) + + command = ["Rscript", temp_r_script_path.as_posix()] + command_executed = " ".join(command) + + stdout = "" + stderr = "" + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + encoding="utf-8" + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + # Clean up temporary R script on error + temp_r_script_path.unlink(missing_ok=True) + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed with exit code {e.returncode}. " + f"See stderr for R-specific error messages.", + "output_files": [], + } + finally: + # Always clean up the temporary R script + temp_r_script_path.unlink(missing_ok=True) + + # Collect all generated files in the output directory + output_files = [str(f) for f in output_directory.rglob("*") if f.is_file()] + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-apl/app/bioconductor-apl_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-apl/app/bioconductor-apl_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b08ac352a9bebccd6abc0225fe138780951c5569 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-apl/app/bioconductor-apl_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-apl/app/bioconductor-apl_server.py') +SERVER_NAME = 'biosci_bioconductor_apl' + + +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-apl/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-apl/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-apl/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-apl/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-apl/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..683057b32a92cff6c48a6b412fe553e6110b0697 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-apl/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-apl: + build: . + image: mcp-bioconductor-apl:latest + container_name: mcp-bioconductor-apl + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-apl + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-apl/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-apl/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4bbe91da143156538097572747ac1998fc242e59 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-apl/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-apl + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-apl/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-apl/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-apl/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-awaggregator/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-awaggregator/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..53b52deea05f9bf6f66ad8a3024b5e2a18923bb4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-awaggregator/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-awaggregator via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-awaggregator -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-awaggregator_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-awaggregator_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-awaggregator_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-awaggregator/app/bioconductor-awaggregator_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-awaggregator/app/bioconductor-awaggregator_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2c712046b6babe4f14d49283b84338eb72719930 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-awaggregator/app/bioconductor-awaggregator_server.py @@ -0,0 +1,214 @@ +import subprocess +from pathlib import Path +from typing import Dict, List + +# MCP decorator is assumed to be available in the execution environment. +# No import is needed as per the instructions. +# class mcp: +# @staticmethod +# def tool(): +# def decorator(func): +# return func +# return decorator + + +def _run_awaggregator_cli(cmd: List[str], output_map: Dict[str, Path]) -> Dict: + """ + A private helper function to execute the awaggregator wrapper script, + handle subprocess execution, and format the output. + """ + command_executed = " ".join(map(str, cmd)) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {key: str(path) for key, path in output_map.items()}, + } + except FileNotFoundError: + # This error is raised if 'Rscript' or the wrapper is not in PATH + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'Rscript' or the wrapper script 'run_awaggregator.R' not found. " + "Please ensure R and the tool's wrapper script are in the system's PATH.", + "output_files": {}, + "error": "Executable not found." + } + except subprocess.CalledProcessError as e: + # This error is raised for non-zero exit codes from the tool + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": {}, + "error": f"Tool execution failed with exit code {e.returncode}", + } + + +@mcp.tool() +def aw_weight( + expression_matrix: Path, + design_matrix: Path, + output_weights_file: Path, +): + """ + Computes adaptive weights for gene expression data meta-analysis. + + This tool wraps the `aw.weight` function from the Bioconductor `awaggregator` package. + It takes an expression data matrix and a design matrix to compute weights for each study. + The resulting weights matrix can be used with the `aw_mean` or `aw_median` tools. + + Args: + expression_matrix: Path to the input expression data matrix file (e.g., CSV, TSV). + Rows should represent genes and columns should represent samples. + design_matrix: Path to the input design matrix file (e.g., CSV, TSV). + This matrix describes the experimental design. + output_weights_file: Path to save the computed weights matrix. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a + path to the output weights file. + """ + # --- Input Validation --- + if not expression_matrix.is_file(): + raise FileNotFoundError(f"Input expression matrix file not found: {expression_matrix}") + if not design_matrix.is_file(): + raise FileNotFoundError(f"Input design matrix file not found: {design_matrix}") + + output_dir = output_weights_file.parent + if not output_dir.is_dir(): + raise NotADirectoryError(f"Output directory does not exist: {output_dir}") + + # --- Command Construction --- + # Assumes a wrapper script 'run_awaggregator.R' is available that handles CLI parsing. + cmd = [ + "Rscript", + "run_awaggregator.R", + "--method", + "weight", + "--expression", + expression_matrix, + "--design", + design_matrix, + "--output", + output_weights_file, + ] + + return _run_awaggregator_cli(cmd, {"weights_matrix": output_weights_file}) + + +@mcp.tool() +def aw_mean( + data_matrix: Path, + weights_matrix: Path, + output_file: Path, + na_rm: bool = False, +): + """ + Performs adaptive-weighted mean aggregation on gene expression data. + + This tool wraps the `aw.mean` function from the Bioconductor `awaggregator` package. + It takes a data matrix and a corresponding weights matrix to compute the weighted mean + for each gene (row) across studies (columns). + + Args: + data_matrix: Path to the input data matrix file (e.g., CSV, TSV). + Rows should represent genes and columns should represent studies. + weights_matrix: Path to the input weights matrix file (e.g., CSV, TSV). + Must have the same dimensions as the data matrix. + output_file: Path to save the aggregated results. + na_rm: If True, NA values will be removed before computation. Defaults to False. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a + path to the output file. + """ + # --- Input Validation --- + if not data_matrix.is_file(): + raise FileNotFoundError(f"Input data matrix file not found: {data_matrix}") + if not weights_matrix.is_file(): + raise FileNotFoundError(f"Input weights matrix file not found: {weights_matrix}") + + output_dir = output_file.parent + if not output_dir.is_dir(): + raise NotADirectoryError(f"Output directory does not exist: {output_dir}") + + # --- Command Construction --- + cmd = [ + "Rscript", + "run_awaggregator.R", + "--method", + "mean", + "--data", + data_matrix, + "--weights", + weights_matrix, + "--output", + output_file, + ] + if na_rm: + cmd.append("--na-rm") + + return _run_awaggregator_cli(cmd, {"aggregated_data": output_file}) + + +@mcp.tool() +def aw_median( + data_matrix: Path, + weights_matrix: Path, + output_file: Path, + na_rm: bool = False, +): + """ + Performs adaptive-weighted median aggregation on gene expression data. + + This tool wraps the `aw.median` function from the Bioconductor `awaggregator` package. + It takes a data matrix and a corresponding weights matrix to compute the weighted median + for each gene (row) across studies (columns). + + Args: + data_matrix: Path to the input data matrix file (e.g., CSV, TSV). + Rows should represent genes and columns should represent studies. + weights_matrix: Path to the input weights matrix file (e.g., CSV, TSV). + Must have the same dimensions as the data matrix. + output_file: Path to save the aggregated results. + na_rm: If True, NA values will be removed before computation. Defaults to False. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a + path to the output file. + """ + # --- Input Validation --- + if not data_matrix.is_file(): + raise FileNotFoundError(f"Input data matrix file not found: {data_matrix}") + if not weights_matrix.is_file(): + raise FileNotFoundError(f"Input weights matrix file not found: {weights_matrix}") + + output_dir = output_file.parent + if not output_dir.is_dir(): + raise NotADirectoryError(f"Output directory does not exist: {output_dir}") + + # --- Command Construction --- + cmd = [ + "Rscript", + "run_awaggregator.R", + "--method", + "median", + "--data", + data_matrix, + "--weights", + weights_matrix, + "--output", + output_file, + ] + if na_rm: + cmd.append("--na-rm") + + return _run_awaggregator_cli(cmd, {"aggregated_data": output_file}) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-awaggregator/app/bioconductor-awaggregator_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-awaggregator/app/bioconductor-awaggregator_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..03fc0c555824375e2e1491f0c579ecce8ee4f777 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-awaggregator/app/bioconductor-awaggregator_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-awaggregator/app/bioconductor-awaggregator_server.py') +SERVER_NAME = 'biosci_bioconductor_awaggregator' + + +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-awaggregator/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-awaggregator/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-awaggregator/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-awaggregator/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-awaggregator/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..ff0371023c533e11773174f48bd51a6d9216bff9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-awaggregator/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-awaggregator: + build: . + image: mcp-bioconductor-awaggregator:latest + container_name: mcp-bioconductor-awaggregator + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-awaggregator + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-awaggregator/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-awaggregator/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4a35b9239801536a5473e94323a22b826418478d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-awaggregator/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-awaggregator + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-awaggregator/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-awaggregator/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-awaggregator/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-banksy/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-banksy/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1bfc36fcdba582407198bff96211ec04fd0c3b4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-banksy/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-banksy via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-banksy -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-banksy_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-banksy_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-banksy_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-banksy/app/bioconductor-banksy_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-banksy/app/bioconductor-banksy_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f49a556a60d1aa6962d4ee59dad1c7b7be9e4e7d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-banksy/app/bioconductor-banksy_server.py @@ -0,0 +1,659 @@ +import subprocess +import tempfile +import os +from pathlib import Path +from typing import Optional, List, Dict, Any + +# Note: The @mcp.tool() decorator is assumed to be available in the environment +# where this code will be run, as per the instructions "NO NEED to import mcp". + +@mcp.tool() +def banksy_init_object( + input_seurat_rdata_path: Path, + output_banksy_rdata_path: Path, + assay: str = "Spatial", + verbose: bool = True, +) -> Dict[str, Any]: + """ + Initializes a BanksyObject from an existing Seurat object. + + This tool takes an RData file containing a Seurat object, converts it + into a BanksyObject, and saves the new BanksyObject to an RData file. + This is often the first step before running the BANKSY algorithm. + + Requires R and the 'banksy' and 'Seurat' R packages to be installed + and accessible in the environment. + + Args: + input_seurat_rdata_path: Path to the input .RData file containing a Seurat object. + output_banksy_rdata_path: Path where the new BanksyObject will be saved as an .RData file. + assay: Name of the assay in the Seurat object to use for spatial data. + verbose: If TRUE, print messages during execution. + + Returns: + A dictionary containing execution details: + - command_executed: The Rscript command and generated R script path. + - stdout: Standard output from the Rscript execution. + - stderr: Standard error from the Rscript execution. + - output_files: A list of paths to generated output files. + """ + # 1. Input validation + if not input_seurat_rdata_path.exists(): + raise FileNotFoundError(f"Input Seurat RData file not found: {input_seurat_rdata_path}") + if not input_seurat_rdata_path.is_file(): + raise ValueError(f"Input Seurat RData path is not a file: {input_seurat_rdata_path}") + if output_banksy_rdata_path.suffix.lower() != ".rdata": + raise ValueError(f"Output RData file must have a .RData extension: {output_banksy_rdata_path}") + if not assay: + raise ValueError("Assay name cannot be empty.") + + # Ensure output directory exists + output_banksy_rdata_path.parent.mkdir(parents=True, exist_ok=True) + + # 2. Generate R script content + r_script_content = f""" + # Load required packages + library(Seurat) + library(banksy) + + # Define input and output paths + input_obj_path <- "{input_seurat_rdata_path.as_posix()}" + output_obj_path <- "{output_banksy_rdata_path.as_posix()}" + + # Check if input file exists + if (!file.exists(input_obj_path)) {{ + stop(paste("Input RData file not found:", input_obj_path)) + }} + + # Load the object from RData. This approach handles cases where the object + # name inside the RData file is not known beforehand. + loaded_env <- new.env() + load(input_obj_path, envir = loaded_env) + + seurat_obj <- NULL + for (var_name in ls(loaded_env)) {{ + candidate <- get(var_name, envir = loaded_env) + if (inherits(candidate, "Seurat")) {{ + seurat_obj <- candidate + break + }} + }} + + if (is.null(seurat_obj)) {{ + stop("No Seurat object found in the input RData file.") + }} + + message("Initializing BanksyObject from Seurat object with parameters:") + message(paste(" assay:", "{assay}")) + message(paste(" verbose:", {str(verbose).upper()})) + + # Create BanksyObject + banksy_obj <- BanksyObject( + seurat_obj, + assay = "{assay}", + verbose = {str(verbose).upper()} + ) + + # Save the new BanksyObject. Renaming to 'obj' for consistency with other banksy tools. + obj <- banksy_obj + save(obj, file = output_obj_path) + + message(paste("BanksyObject saved to:", output_obj_path)) + """ + + temp_r_script_path: Optional[Path] = None + try: + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".R") as temp_r_script: + temp_r_script.write(r_script_content) + temp_r_script_path = Path(temp_r_script.name) + + command = ["Rscript", str(temp_r_script_path)] + + # 3. Subprocess execution + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + env=os.environ # Pass current environment to Rscript + ) + + stdout = process.stdout + stderr = process.stderr + + # 4. Error handling: Check for R-specific errors in stderr + if "Error" in stderr or "stop(" in stderr: + raise RuntimeError(f"R script execution failed. Stderr: {stderr}") + + if not output_banksy_rdata_path.exists(): + raise RuntimeError(f"Output file was not created by R script: {output_banksy_rdata_path}") + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_banksy_rdata_path)], + } + + except FileNotFoundError: + raise RuntimeError("Rscript command not found. Is R installed and in your PATH?") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Rscript execution failed with exit code {e.returncode}.\n" + f"Command: {' '.join(e.cmd)}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) + finally: + # Clean up temporary R script + if temp_r_script_path and temp_r_script_path.exists(): + os.remove(temp_r_script_path) + + +@mcp.tool() +def banksy_run_banksy( + input_rdata_path: Path, + output_rdata_path: Path, + k_neighbours: int = 10, + lambda_param: float = 0.1, # Renamed from 'lambda' to avoid Python keyword conflict + resolution: float = 0.8, + n_components: int = 2, + n_cores: int = 1, + verbose: bool = True, + seed: int = 123, +) -> Dict[str, Any]: + """ + Runs the core BANKSY algorithm on a Seurat or BanksyObject. + + This tool takes an RData file containing a Seurat or BanksyObject, + applies the BANKSY algorithm for spatial transcriptomics analysis, + and saves the updated object to a new RData file. + + Requires R and the 'banksy', 'Seurat', and 'future' R packages to be installed + and accessible in the environment. + + Args: + input_rdata_path: Path to the input .RData file containing a Seurat or BanksyObject. + output_rdata_path: Path where the updated Seurat/BanksyObject will be saved as an .RData file. + k_neighbours: Number of neighbours for spatial graph construction. + lambda_param: Weight of spatial information (lambda parameter). + resolution: Resolution parameter for clustering. + n_components: Number of components for dimensionality reduction (e.g., UMAP/tSNE). + n_cores: Number of cores to use for parallel processing. + verbose: If TRUE, print messages during execution. + seed: Random seed for reproducibility. + + Returns: + A dictionary containing execution details: + - command_executed: The Rscript command and generated R script path. + - stdout: Standard output from the Rscript execution. + - stderr: Standard error from the Rscript execution. + - output_files: A list of paths to generated output files. + """ + # 1. Input validation + if not input_rdata_path.exists(): + raise FileNotFoundError(f"Input RData file not found: {input_rdata_path}") + if not input_rdata_path.is_file(): + raise ValueError(f"Input RData path is not a file: {input_rdata_path}") + if output_rdata_path.suffix.lower() != ".rdata": + raise ValueError(f"Output RData file must have a .RData extension: {output_rdata_path}") + if k_neighbours <= 0: + raise ValueError("k_neighbours must be a positive integer.") + if not (0 <= lambda_param <= 1): + raise ValueError("lambda_param must be between 0 and 1.") + if resolution <= 0: + raise ValueError("resolution must be a positive float.") + if n_components <= 0: + raise ValueError("n_components must be a positive integer.") + if n_cores <= 0: + raise ValueError("n_cores must be a positive integer.") + + # Ensure output directory exists + output_rdata_path.parent.mkdir(parents=True, exist_ok=True) + + # 2. Generate R script content + r_script_content = f""" + # Load required packages + library(Seurat) + library(banksy) + library(future) # For parallel processing + + # Set up parallel processing if n_cores > 1 + if ({n_cores} > 1) {{ + plan("multisession", workers = {n_cores}) + }} else {{ + plan("sequential") + }} + + # Set random seed for reproducibility + set.seed({seed}) + + # Define input and output paths + input_obj_path <- "{input_rdata_path.as_posix()}" + output_obj_path <- "{output_rdata_path.as_posix()}" + + # Check if input file exists + if (!file.exists(input_obj_path)) {{ + stop(paste("Input RData file not found:", input_obj_path)) + }} + + # Load the object + loaded_env <- new.env() + load(input_obj_path, envir = loaded_env) + + obj <- NULL + for (var_name in ls(loaded_env)) {{ + candidate <- get(var_name, envir = loaded_env) + if (inherits(candidate, "Seurat") || inherits(candidate, "BanksyObject")) {{ + obj <- candidate + break + }} + }} + + if (is.null(obj)) {{ + stop("No Seurat or BanksyObject found in the input RData file.") + }} + + message("Running banksy with parameters:") + message(paste(" k_neighbours:", {k_neighbours})) + message(paste(" lambda:", {lambda_param})) + message(paste(" resolution:", {resolution})) + message(paste(" n_components:", {n_components})) + message(paste(" n_cores:", {n_cores})) + message(paste(" verbose:", {str(verbose).upper()})) + message(paste(" seed:", {seed})) + + # Run BANKSY + obj <- runBanksy( + object = obj, + k_neighbours = {k_neighbours}, + lambda = {lambda_param}, + resolution = {resolution}, + n_components = {n_components}, + verbose = {str(verbose).upper()} + ) + + # Save the updated object + save(obj, file = output_obj_path) + + message(paste("Updated object saved to:", output_obj_path)) + """ + + temp_r_script_path: Optional[Path] = None + try: + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".R") as temp_r_script: + temp_r_script.write(r_script_content) + temp_r_script_path = Path(temp_r_script.name) + + command = ["Rscript", str(temp_r_script_path)] + + # 3. Subprocess execution + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + env=os.environ + ) + + stdout = process.stdout + stderr = process.stderr + + # 4. Error handling: Check for R-specific errors in stderr + if "Error" in stderr or "stop(" in stderr: + raise RuntimeError(f"R script execution failed. Stderr: {stderr}") + + if not output_rdata_path.exists(): + raise RuntimeError(f"Output file was not created by R script: {output_rdata_path}") + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_rdata_path)], + } + + except FileNotFoundError: + raise RuntimeError("Rscript command not found. Is R installed and in your PATH?") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Rscript execution failed with exit code {e.returncode}.\n" + f"Command: {' '.join(e.cmd)}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) + finally: + # Clean up temporary R script + if temp_r_script_path and temp_r_script_path.exists(): + os.remove(temp_r_script_path) + + +@mcp.tool() +def banksy_cluster_banksy( + input_rdata_path: Path, + output_rdata_path: Path, + resolution: float = 0.8, + method: str = "leiden", + verbose: bool = True, + seed: int = 123, +) -> Dict[str, Any]: + """ + Performs clustering on a BanksyObject or Seurat object after BANKSY analysis. + + This tool takes an RData file containing a Seurat or BanksyObject (typically + after `runBanksy`), performs clustering using the specified method and resolution, + and saves the updated object to a new RData file. + + Requires R and the 'banksy' and 'Seurat' R packages to be installed + and accessible in the environment. + + Args: + input_rdata_path: Path to the input .RData file containing a Seurat or BanksyObject. + output_rdata_path: Path where the updated Seurat/BanksyObject will be saved as an .RData file. + resolution: Resolution parameter for clustering. + method: Clustering method to use (e.g., "leiden", "louvain"). + verbose: If TRUE, print messages during execution. + seed: Random seed for reproducibility. + + Returns: + A dictionary containing execution details: + - command_executed: The Rscript command and generated R script path. + - stdout: Standard output from the Rscript execution. + - stderr: Standard error from the Rscript execution. + - output_files: A list of paths to generated output files. + """ + # 1. Input validation + if not input_rdata_path.exists(): + raise FileNotFoundError(f"Input RData file not found: {input_rdata_path}") + if not input_rdata_path.is_file(): + raise ValueError(f"Input RData path is not a file: {input_rdata_path}") + if output_rdata_path.suffix.lower() != ".rdata": + raise ValueError(f"Output RData file must have a .RData extension: {output_rdata_path}") + if resolution <= 0: + raise ValueError("resolution must be a positive float.") + if method not in ["leiden", "louvain"]: + raise ValueError(f"Unsupported clustering method: {method}. Choose from 'leiden', 'louvain'.") + + # Ensure output directory exists + output_rdata_path.parent.mkdir(parents=True, exist_ok=True) + + # 2. Generate R script content + r_script_content = f""" + # Load required packages + library(Seurat) + library(banksy) + + # Set random seed for reproducibility + set.seed({seed}) + + # Define input and output paths + input_obj_path <- "{input_rdata_path.as_posix()}" + output_obj_path <- "{output_rdata_path.as_posix()}" + + # Check if input file exists + if (!file.exists(input_obj_path)) {{ + stop(paste("Input RData file not found:", input_obj_path)) + }} + + # Load the object + loaded_env <- new.env() + load(input_obj_path, envir = loaded_env) + + obj <- NULL + for (var_name in ls(loaded_env)) {{ + candidate <- get(var_name, envir = loaded_env) + if (inherits(candidate, "Seurat") || inherits(candidate, "BanksyObject")) {{ + obj <- candidate + break + }} + }} + + if (is.null(obj)) {{ + stop("No Seurat or BanksyObject found in the input RData file.") + }} + + message("Clustering banksy object with parameters:") + message(paste(" resolution:", {resolution})) + message(paste(" method:", "{method}")) + message(paste(" verbose:", {str(verbose).upper()})) + message(paste(" seed:", {seed})) + + # Cluster BANKSY object + obj <- clusterBanksy( + object = obj, + resolution = {resolution}, + method = "{method}", + verbose = {str(verbose).upper()} + ) + + # Save the updated object + save(obj, file = output_obj_path) + + message(paste("Updated object saved to:", output_obj_path)) + """ + + temp_r_script_path: Optional[Path] = None + try: + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".R") as temp_r_script: + temp_r_script.write(r_script_content) + temp_r_script_path = Path(temp_r_script.name) + + command = ["Rscript", str(temp_r_script_path)] + + # 3. Subprocess execution + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + env=os.environ + ) + + stdout = process.stdout + stderr = process.stderr + + # 4. Error handling: Check for R-specific errors in stderr + if "Error" in stderr or "stop(" in stderr: + raise RuntimeError(f"R script execution failed. Stderr: {stderr}") + + if not output_rdata_path.exists(): + raise RuntimeError(f"Output file was not created by R script: {output_rdata_path}") + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_rdata_path)], + } + + except FileNotFoundError: + raise RuntimeError("Rscript command not found. Is R installed and in your PATH?") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Rscript execution failed with exit code {e.returncode}.\n" + f"Command: {' '.join(e.cmd)}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) + finally: + # Clean up temporary R script + if temp_r_script_path and temp_r_script_path.exists(): + os.remove(temp_r_script_path) + + +@mcp.tool() +def banksy_spatial_dim_plot( + input_rdata_path: Path, + output_plot_path: Path, + reduction: str = "banksy", + group_by: str = "banksy_clusters", + label: bool = True, + pt_size: float = 1.5, + verbose: bool = True, + width: float = 7.0, + height: float = 7.0, + units: str = "in", + dpi: int = 300, +) -> Dict[str, Any]: + """ + Generates a spatial dimensionality plot for a BanksyObject. + + This tool takes an RData file containing a BanksyObject (typically after + `runBanksy` and `clusterBanksy`), generates a spatial plot, and saves it + to an image file (e.g., PNG, PDF). + + Requires R and the 'banksy', 'Seurat', and 'ggplot2' R packages to be installed + and accessible in the environment. + + Args: + input_rdata_path: Path to the input .RData file containing a BanksyObject. + output_plot_path: Path where the plot will be saved (e.g., .png, .pdf, .jpeg). + reduction: Dimensionality reduction to use for plotting (e.g., "banksy", "umap"). + group_by: Feature to group cells by for coloring (e.g., "banksy_clusters"). + label: If TRUE, label clusters on the plot. + pt_size: Size of the points in the plot. + verbose: If TRUE, print messages during execution. + width: Width of the output plot. + height: Height of the output plot. + units: Units for width and height ("in", "cm", "mm"). + dpi: Resolution for raster plots (e.g., PNG, JPEG). + + Returns: + A dictionary containing execution details: + - command_executed: The Rscript command and generated R script path. + - stdout: Standard output from the Rscript execution. + - stderr: Standard error from the Rscript execution. + - output_files: A list of paths to generated output files. + """ + # 1. Input validation + if not input_rdata_path.exists(): + raise FileNotFoundError(f"Input RData file not found: {input_rdata_path}") + if not input_rdata_path.is_file(): + raise ValueError(f"Input RData path is not a file: {input_rdata_path}") + + valid_plot_suffixes = [".png", ".pdf", ".jpeg", ".jpg", ".tiff", ".bmp"] + if output_plot_path.suffix.lower() not in valid_plot_suffixes: + raise ValueError(f"Output plot file must have one of the following extensions: {', '.join(valid_plot_suffixes)}") + + if pt_size <= 0: + raise ValueError("pt_size must be a positive float.") + if width <= 0 or height <= 0: + raise ValueError("Width and height must be positive floats.") + if units not in ["in", "cm", "mm"]: + raise ValueError(f"Invalid units: {units}. Choose from 'in', 'cm', 'mm'.") + if dpi <= 0: + raise ValueError("DPI must be a positive integer.") + + # Ensure output directory exists + output_plot_path.parent.mkdir(parents=True, exist_ok=True) + + # 2. Generate R script content + r_script_content = f""" + # Load required packages + library(Seurat) + library(banksy) + library(ggplot2) # For saving plots + + # Define input and output paths + input_obj_path <- "{input_rdata_path.as_posix()}" + output_plot_path <- "{output_plot_path.as_posix()}" + + # Check if input file exists + if (!file.exists(input_obj_path)) {{ + stop(paste("Input RData file not found:", input_obj_path)) + }} + + # Load the object + loaded_env <- new.env() + load(input_obj_path, envir = loaded_env) + + obj <- NULL + for (var_name in ls(loaded_env)) {{ + candidate <- get(var_name, envir = loaded_env) + if (inherits(candidate, "Seurat") || inherits(candidate, "BanksyObject")) {{ + obj <- candidate + break + }} + }} + + if (is.null(obj)) {{ + stop("No Seurat or BanksyObject found in the input RData file.") + }} + + message("Generating spatial dimensionality plot with parameters:") + message(paste(" reduction:", "{reduction}")) + message(paste(" group_by:", "{group_by}")) + message(paste(" label:", {str(label).upper()})) + message(paste(" pt_size:", {pt_size})) + message(paste(" verbose:", {str(verbose).upper()})) + + # Generate plot + p <- spatialDimPlot( + object = obj, + reduction = "{reduction}", + group.by = "{group_by}", + label = {str(label).upper()}, + pt.size.factor = {pt_size}, # Note: R parameter is pt.size.factor + verbose = {str(verbose).upper()} + ) + + # Save the plot + ggsave( + filename = output_plot_path, + plot = p, + width = {width}, + height = {height}, + units = "{units}", + dpi = {dpi} + ) + + message(paste("Plot saved to:", output_plot_path)) + """ + + temp_r_script_path: Optional[Path] = None + try: + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".R") as temp_r_script: + temp_r_script.write(r_script_content) + temp_r_script_path = Path(temp_r_script.name) + + command = ["Rscript", str(temp_r_script_path)] + + # 3. Subprocess execution + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + env=os.environ + ) + + stdout = process.stdout + stderr = process.stderr + + # 4. Error handling: Check for R-specific errors in stderr + if "Error" in stderr or "stop(" in stderr: + raise RuntimeError(f"R script execution failed. Stderr: {stderr}") + + if not output_plot_path.exists(): + raise RuntimeError(f"Output plot file was not created by R script: {output_plot_path}") + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_plot_path)], + } + + except FileNotFoundError: + raise RuntimeError("Rscript command not found. Is R installed and in your PATH?") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Rscript execution failed with exit code {e.returncode}.\n" + f"Command: {' '.join(e.cmd)}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) + finally: + # Clean up temporary R script + if temp_r_script_path and temp_r_script_path.exists(): + os.remove(temp_r_script_path) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-banksy/app/bioconductor-banksy_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-banksy/app/bioconductor-banksy_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3ce854072accea63e948911367ce6c99a0466159 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-banksy/app/bioconductor-banksy_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-banksy/app/bioconductor-banksy_server.py') +SERVER_NAME = 'biosci_bioconductor_banksy' + + +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-banksy/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-banksy/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-banksy/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-banksy/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-banksy/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..5745dcb463d5d3a4a0240bea07df9ef2cafba776 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-banksy/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-banksy: + build: . + image: mcp-bioconductor-banksy:latest + container_name: mcp-bioconductor-banksy + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-banksy + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-banksy/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-banksy/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..508d5e0076bfb9bafa1307f48692fa5c85f624eb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-banksy/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-banksy + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-banksy/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-banksy/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-banksy/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-benchdamic/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-benchdamic/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..049a35d085b83f15bc149115150cd24367530eef --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-benchdamic/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-benchdamic via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-benchdamic -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-benchdamic_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-benchdamic_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-benchdamic_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-benchdamic/app/bioconductor-benchdamic_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-benchdamic/app/bioconductor-benchdamic_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a6ed675c4d398642f704254b729325432807bab0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-benchdamic/app/bioconductor-benchdamic_server.py @@ -0,0 +1,464 @@ +import subprocess +import tempfile +from pathlib import Path +import os +import logging +from typing import List, Optional + +# Set up logging +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) + +# MCP decorator is assumed to be available in the execution environment. +# This is a placeholder for the actual decorator. +class mcp: + @staticmethod + def tool(func): + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + return wrapper + +@mcp.tool +def run_benchdamic( + config_file: Path, + output_dir: Path, +): + """ + Runs the full benchdamic pipeline. + + This function serves as the main entry point for the benchdamic workflow, + executing data generation, method application, evaluation, and plotting + based on a single YAML configuration file. The process is run within the + specified output directory. + + Args: + config_file: Path to the benchdamic YAML configuration file. + output_dir: Path to the directory where all outputs will be stored. + It will be created if it doesn't exist. + """ + # 1. Input validation + if not config_file.is_file(): + raise FileNotFoundError(f"Configuration file not found: {config_file}") + + # 2. File path handling + output_dir.mkdir(parents=True, exist_ok=True) + + # The R function benchdamic() relies on the 'output_dir' key within the config YAML. + # By running Rscript from the specified output_dir, we ensure that + # relative paths in the config file are resolved correctly. + r_script_content = f""" + if (!requireNamespace("benchdamic", quietly = TRUE)) {{ + stop("The 'benchdamic' R package is not installed. Please install it from Bioconductor.") + }} + library(benchdamic) + + config_path <- "{config_file.resolve()}" + + cat("Starting benchdamic pipeline...\\n") + benchdamic::benchdamic(config_file = config_path) + cat("benchdamic pipeline finished successfully.\\n") + """ + + # 3. Subprocess execution + command_to_execute = [] + stdout_str = "" + stderr_str = "" + r_script_path = None + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, dir=output_dir) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = Path(r_script_file.name) + + # Use relative path for the command since we set cwd + command_to_execute = ["Rscript", str(r_script_path.name)] + + files_before = set(os.listdir(output_dir)) + + process = subprocess.run( + command_to_execute, + capture_output=True, + text=True, + check=True, + cwd=output_dir, + ) + + stdout_str = process.stdout + stderr_str = process.stderr + + files_after = set(os.listdir(output_dir)) + # Find new files and directories + new_items = files_after - files_before + output_files = [str(output_dir / item) for item in new_items] + + except FileNotFoundError: + err_msg = "Rscript not found. Please ensure R is installed and 'Rscript' is in your system's PATH." + logger.error(err_msg) + raise RuntimeError(err_msg) from None + except subprocess.CalledProcessError as e: + logger.error(f"R script execution failed with exit code {e.returncode}") + logger.error(f"Command: {' '.join(command_to_execute)}") + logger.error(f"Stdout: {e.stdout}") + logger.error(f"Stderr: {e.stderr}") + raise + finally: + if r_script_path and r_script_path.exists(): + r_script_path.unlink() + + # 4. Structured result return + return { + "command_executed": " ".join(command_to_execute), + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": output_files + } + +@mcp.tool +def generate_data( + config_file: Path, + output_dir: Path, +): + """ + Generates simulated data using the benchdamic configuration. + + This function corresponds to the `generate_data` step in the benchdamic + workflow. It reads simulation parameters from the config file and writes + the generated datasets to the specified output directory. + + Args: + config_file: Path to the benchdamic YAML configuration file. + output_dir: Path to the directory where generated data will be stored. + It will be created if it doesn't exist. + """ + # 1. Input validation + if not config_file.is_file(): + raise FileNotFoundError(f"Configuration file not found: {config_file}") + + # 2. File path handling + output_dir.mkdir(parents=True, exist_ok=True) + + r_script_content = f""" + if (!requireNamespace("benchdamic", quietly = TRUE)) {{ + stop("The 'benchdamic' R package is not installed.") + }} + library(benchdamic) + + config_path <- "{config_file.resolve()}" + output_path <- "{output_dir.resolve()}" + + cat("Starting data generation...\\n") + benchdamic::generate_data(config_file = config_path, output_dir = output_path) + cat("Data generation finished successfully.\\n") + """ + + # 3. Subprocess execution + command_to_execute = [] + stdout_str = "" + stderr_str = "" + r_script_path = None + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = Path(r_script_file.name) + + command_to_execute = ["Rscript", str(r_script_path)] + + files_before = set(p.resolve() for p in output_dir.glob('**/*')) + + process = subprocess.run( + command_to_execute, + capture_output=True, + text=True, + check=True, + ) + + stdout_str = process.stdout + stderr_str = process.stderr + + files_after = set(p.resolve() for p in output_dir.glob('**/*')) + new_files = [str(p) for p in files_after - files_before] + + except FileNotFoundError: + err_msg = "Rscript not found. Please ensure R is installed and 'Rscript' is in your system's PATH." + logger.error(err_msg) + raise RuntimeError(err_msg) from None + except subprocess.CalledProcessError as e: + logger.error(f"R script execution failed with exit code {e.returncode}") + logger.error(f"Command: {' '.join(command_to_execute)}") + logger.error(f"Stdout: {e.stdout}") + logger.error(f"Stderr: {e.stderr}") + raise + finally: + if r_script_path and r_script_path.exists(): + r_script_path.unlink() + + # 4. Structured result return + return { + "command_executed": " ".join(command_to_execute), + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": new_files + } + +@mcp.tool +def run_methods( + config_file: Path, + output_dir: Path, +): + """ + Runs differential abundance methods on generated data. + + This function corresponds to the `run_methods` step in the benchdamic + workflow. It applies the specified methods to the datasets found in the + output directory and saves their results. + + Args: + config_file: Path to the benchdamic YAML configuration file. + output_dir: Path to the directory containing the generated data and + where method results will be stored. It must exist. + """ + # 1. Input validation + if not config_file.is_file(): + raise FileNotFoundError(f"Configuration file not found: {config_file}") + if not output_dir.is_dir(): + raise FileNotFoundError(f"Output directory not found: {output_dir}. Please run generate_data first.") + + # 2. R script content + r_script_content = f""" + if (!requireNamespace("benchdamic", quietly = TRUE)) {{ + stop("The 'benchdamic' R package is not installed.") + }} + library(benchdamic) + + config_path <- "{config_file.resolve()}" + output_path <- "{output_dir.resolve()}" + + cat("Running differential abundance methods...\\n") + benchdamic::run_methods(config_file = config_path, output_dir = output_path) + cat("Method execution finished successfully.\\n") + """ + + # 3. Subprocess execution + command_to_execute = [] + stdout_str = "" + stderr_str = "" + r_script_path = None + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = Path(r_script_file.name) + + command_to_execute = ["Rscript", str(r_script_path)] + + files_before = set(p.resolve() for p in output_dir.glob('**/*')) + + process = subprocess.run( + command_to_execute, + capture_output=True, + text=True, + check=True, + ) + + stdout_str = process.stdout + stderr_str = process.stderr + + files_after = set(p.resolve() for p in output_dir.glob('**/*')) + new_files = [str(p) for p in files_after - files_before] + + except FileNotFoundError: + err_msg = "Rscript not found. Please ensure R is installed and 'Rscript' is in your system's PATH." + logger.error(err_msg) + raise RuntimeError(err_msg) from None + except subprocess.CalledProcessError as e: + logger.error(f"R script execution failed with exit code {e.returncode}") + logger.error(f"Command: {' '.join(command_to_execute)}") + logger.error(f"Stdout: {e.stdout}") + logger.error(f"Stderr: {e.stderr}") + raise + finally: + if r_script_path and r_script_path.exists(): + r_script_path.unlink() + + # 4. Structured result return + return { + "command_executed": " ".join(command_to_execute), + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": new_files + } + +@mcp.tool +def evaluate_methods( + config_file: Path, + output_dir: Path, +): + """ + Evaluates the performance of differential abundance methods. + + This function corresponds to the `evaluate_methods` step in the benchdamic + workflow. It computes performance metrics based on the method results + and ground truth, saving the evaluation to the output directory. + + Args: + config_file: Path to the benchdamic YAML configuration file. + output_dir: Path to the directory containing method results. It must exist. + """ + # 1. Input validation + if not config_file.is_file(): + raise FileNotFoundError(f"Configuration file not found: {config_file}") + if not output_dir.is_dir(): + raise FileNotFoundError(f"Output directory not found: {output_dir}.") + + # 2. R script content + r_script_content = f""" + if (!requireNamespace("benchdamic", quietly = TRUE)) {{ + stop("The 'benchdamic' R package is not installed.") + }} + library(benchdamic) + + config_path <- "{config_file.resolve()}" + output_path <- "{output_dir.resolve()}" + + cat("Evaluating method performance...\\n") + benchdamic::evaluate_methods(config_file = config_path, output_dir = output_path) + cat("Evaluation finished successfully.\\n") + """ + + # 3. Subprocess execution + command_to_execute = [] + stdout_str = "" + stderr_str = "" + r_script_path = None + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = Path(r_script_file.name) + + command_to_execute = ["Rscript", str(r_script_path)] + + files_before = set(p.resolve() for p in output_dir.glob('**/*')) + + process = subprocess.run( + command_to_execute, + capture_output=True, + text=True, + check=True, + ) + + stdout_str = process.stdout + stderr_str = process.stderr + + files_after = set(p.resolve() for p in output_dir.glob('**/*')) + new_files = [str(p) for p in files_after - files_before] + + except FileNotFoundError: + err_msg = "Rscript not found. Please ensure R is installed and 'Rscript' is in your system's PATH." + logger.error(err_msg) + raise RuntimeError(err_msg) from None + except subprocess.CalledProcessError as e: + logger.error(f"R script execution failed with exit code {e.returncode}") + logger.error(f"Command: {' '.join(command_to_execute)}") + logger.error(f"Stdout: {e.stdout}") + logger.error(f"Stderr: {e.stderr}") + raise + finally: + if r_script_path and r_script_path.exists(): + r_script_path.unlink() + + # 4. Structured result return + return { + "command_executed": " ".join(command_to_execute), + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": new_files + } + +@mcp.tool +def plot_results( + config_file: Path, + output_dir: Path, +): + """ + Generates plots from the evaluation results. + + This function corresponds to the `plot_results` step in the benchdamic + workflow. It creates various visualizations of the performance metrics + and saves them as files in the output directory. + + Args: + config_file: Path to the benchdamic YAML configuration file. + output_dir: Path to the directory containing evaluation results. It must exist. + """ + # 1. Input validation + if not config_file.is_file(): + raise FileNotFoundError(f"Configuration file not found: {config_file}") + if not output_dir.is_dir(): + raise FileNotFoundError(f"Output directory not found: {output_dir}.") + + # 2. R script content + r_script_content = f""" + if (!requireNamespace("benchdamic", quietly = TRUE)) {{ + stop("The 'benchdamic' R package is not installed.") + }} + library(benchdamic) + + config_path <- "{config_file.resolve()}" + output_path <- "{output_dir.resolve()}" + + cat("Generating plots...\\n") + benchdamic::plot_results(config_file = config_path, output_dir = output_path) + cat("Plot generation finished successfully.\\n") + """ + + # 3. Subprocess execution + command_to_execute = [] + stdout_str = "" + stderr_str = "" + r_script_path = None + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = Path(r_script_file.name) + + command_to_execute = ["Rscript", str(r_script_path)] + + files_before = set(p.resolve() for p in output_dir.glob('**/*')) + + process = subprocess.run( + command_to_execute, + capture_output=True, + text=True, + check=True, + ) + + stdout_str = process.stdout + stderr_str = process.stderr + + files_after = set(p.resolve() for p in output_dir.glob('**/*')) + new_files = [str(p) for p in files_after - files_before] + + except FileNotFoundError: + err_msg = "Rscript not found. Please ensure R is installed and 'Rscript' is in your system's PATH." + logger.error(err_msg) + raise RuntimeError(err_msg) from None + except subprocess.CalledProcessError as e: + logger.error(f"R script execution failed with exit code {e.returncode}") + logger.error(f"Command: {' '.join(command_to_execute)}") + logger.error(f"Stdout: {e.stdout}") + logger.error(f"Stderr: {e.stderr}") + raise + finally: + if r_script_path and r_script_path.exists(): + r_script_path.unlink() + + # 4. Structured result return + return { + "command_executed": " ".join(command_to_execute), + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": new_files + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-benchdamic/app/bioconductor-benchdamic_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-benchdamic/app/bioconductor-benchdamic_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6c24526d206237f6ff0a8e5cc7ee46b44d73eacf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-benchdamic/app/bioconductor-benchdamic_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-benchdamic/app/bioconductor-benchdamic_server.py') +SERVER_NAME = 'biosci_bioconductor_benchdamic' + + +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-benchdamic/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-benchdamic/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..65f8f9f6c1b78e6c31e9ba07e6510d513ea8cfaf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-benchdamic/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-benchdamic: + build: . + image: mcp-bioconductor-benchdamic:latest + container_name: mcp-bioconductor-benchdamic + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-benchdamic + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-benchdamic/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-benchdamic/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..69f3813eec164585774531f51cba29fd74c0d74a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-benchdamic/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-benchdamic + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-benchdamic/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-benchdamic/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-benchdamic/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocbaseutils/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocbaseutils/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ced3fd0e263cd5d1e0e91262cbe9717fba099bb9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocbaseutils/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-biocbaseutils via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-biocbaseutils -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-biocbaseutils_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-biocbaseutils_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-biocbaseutils_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocbaseutils/app/bioconductor-biocbaseutils_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocbaseutils/app/bioconductor-biocbaseutils_server.py new file mode 100644 index 0000000000000000000000000000000000000000..dced4c771dd091eed198e02b504ae98c9843a05f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocbaseutils/app/bioconductor-biocbaseutils_server.py @@ -0,0 +1,102 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, Dict, List, Any + +# Note: The 'mcp' import is not needed as it's assumed to be in the execution environment. +# from mcp import tool + +# This is a mock decorator for local testing, it should be removed in the MCP environment. +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def execute_r_script( + r_script_content: str, + output_filename: Optional[str] = None +) -> Dict[str, Any]: + """ + Executes a user-provided R script in an environment with the bioconductor-biocbaseutils package. + + BiocBaseUtils is an R library that provides utility functions for Bioconductor package development. + It does not have a direct command-line interface. This tool allows you to run custom R code + that leverages the functions within BiocBaseUtils. Your script should load the library + using `library(BiocBaseUtils)` to access its functions. + + Args: + r_script_content: A string containing the complete R code to be executed. + output_filename: Optional. If your R script generates a file, specify its name here. + The script should save the file to the current working directory. + This file will be captured and returned as an output. + + Returns: + A dictionary containing the execution details, including the command, stdout, stderr, + and a list of output file paths. + """ + if not r_script_content or not r_script_content.strip(): + raise ValueError("The 'r_script_content' parameter cannot be empty.") + + # In a real MCP environment, the output directory would be managed by the platform. + # Here, we use a temporary directory to simulate this. + with tempfile.TemporaryDirectory() as temp_dir: + working_dir = Path(temp_dir) + script_path = working_dir / "script.R" + + # Write the user's R code to a temporary script file + with open(script_path, "w") as f: + f.write(r_script_content) + + command = ["Rscript", str(script_path)] + command_str = " ".join(command) + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + cwd=working_dir # Execute from the temp directory + ) + + output_files = [] + if output_filename: + expected_output_path = working_dir / output_filename + if expected_output_path.is_file(): + # In a real MCP server, this path would be a persistent output path. + output_files.append(str(expected_output_path)) + else: + # Log a warning if the expected output file is not found + warning_msg = ( + f"Warning: Specified output file '{output_filename}' " + "was not found in the working directory after script execution." + ) + # Append warning to stderr for user visibility + process_stderr = f"{process.stderr}\n{warning_msg}" + else: + process_stderr = process.stderr + + + return { + "command_executed": command_str, + "stdout": process.stdout, + "stderr": process_stderr, + "output_files": output_files + } + + except FileNotFoundError: + # This error occurs if 'Rscript' is not in the system's PATH + raise RuntimeError( + "Error: 'Rscript' command not found. Please ensure R is installed " + "and accessible in the execution environment's PATH." + ) from None + except subprocess.CalledProcessError as e: + # This handles cases where the R script itself fails (non-zero exit code) + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": f"R script execution failed with exit code {e.returncode}." + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocbaseutils/app/bioconductor-biocbaseutils_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocbaseutils/app/bioconductor-biocbaseutils_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..28b0b6e1a549a4df0010a36401426435c0786ae9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocbaseutils/app/bioconductor-biocbaseutils_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-biocbaseutils/app/bioconductor-biocbaseutils_server.py') +SERVER_NAME = 'biosci_bioconductor_biocbaseutils' + + +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-biocbaseutils/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocbaseutils/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocbaseutils/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocbaseutils/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocbaseutils/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..37d591a09ca588141719b435a204d26b72c2d08a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocbaseutils/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-biocbaseutils: + build: . + image: mcp-bioconductor-biocbaseutils:latest + container_name: mcp-bioconductor-biocbaseutils + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-biocbaseutils + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocbaseutils/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocbaseutils/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4181ef30167d5cae30f272f9b0ddf98485a23cce --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocbaseutils/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-biocbaseutils + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocbaseutils/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocbaseutils/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocbaseutils/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocfilecache/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocfilecache/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..baadb8653861e5789a279f826093986fef432e4b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocfilecache/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-biocfilecache via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-biocfilecache -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-biocfilecache_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-biocfilecache_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-biocfilecache_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocfilecache/app/bioconductor-biocfilecache_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocfilecache/app/bioconductor-biocfilecache_server.py new file mode 100644 index 0000000000000000000000000000000000000000..70f09319b2b5aef837b6cf74c498177ec02a6b23 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocfilecache/app/bioconductor-biocfilecache_server.py @@ -0,0 +1,306 @@ +import subprocess +import logging +from pathlib import Path +from typing import List, Literal, Optional, Dict + +# This is a placeholder for the actual MCP decorator. +# In a real MCP environment, this would be provided by the MCP framework. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +def _validate_cache_path(cache_path: Path, check_exists: bool = True) -> None: + """Helper function to validate the cache path.""" + if check_exists and not cache_path.is_dir(): + raise FileNotFoundError(f"BiocFileCache directory not found at '{cache_path}'") + +def _r_string_vector(items: List[str]) -> str: + """Converts a Python list of strings to an R character vector string.""" + if not items: + return "c()" + # Escape single quotes for R: ' -> \' + escaped_items = [item.replace("'", "\\'") for item in items] + quoted_items = [f"'{item}'" for item in escaped_items] + return f"c({', '.join(quoted_items)})" + +def _run_r_command(r_command: str) -> Dict: + """Executes an R command and returns a structured response.""" + command = ["Rscript", "-e", r_command] + command_str = " ".join(command) + try: + result = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + encoding='utf-8' + ) + return { + "command_executed": command_str, + "stdout": result.stdout.strip(), + "stderr": result.stderr.strip(), + } + except FileNotFoundError: + logging.error("Rscript not found. R must be installed and in the system's PATH.") + raise RuntimeError("Rscript not found. R must be installed and in the system's PATH.") + except subprocess.CalledProcessError as e: + logging.error(f"R script execution failed.\nStderr: {e.stderr}\nStdout: {e.stdout}") + return { + "command_executed": command_str, + "stdout": e.stdout.strip(), + "stderr": e.stderr.strip(), + "error": "R script execution failed." + } + +@mcp.tool() +def biocfilecache_new(cache_path: Path) -> Dict: + """ + Creates a new, empty BiocFileCache at the specified location. + + Args: + cache_path: The directory path where the cache will be created. + The parent directory must exist, and the target path must not. + + Returns: + A dictionary containing the command executed, stdout (the cache path), + stderr, and the path to the created cache directory. + """ + if cache_path.exists(): + raise ValueError(f"Cache path '{cache_path}' already exists. Cannot create a new cache here.") + if not cache_path.parent.is_dir(): + raise FileNotFoundError(f"Parent directory '{cache_path.parent}' does not exist.") + + # Use forward slashes for R path compatibility + safe_cache_path = str(cache_path).replace('\\', '/') + r_command = ( + f"library(BiocFileCache); " + f"bfc <- bfcnew('{safe_cache_path}', ask=FALSE); " + f"cat(bfcpath(bfc))" + ) + + response = _run_r_command(r_command) + if "error" not in response: + response["output_files"] = {"cache_directory": str(cache_path)} + return response + +@mcp.tool() +def biocfilecache_add( + cache_path: Path, + rname: str, + fpath: str, + action: Literal["copy", "move", "asis"] = "copy", + rtype: Literal["web", "local"] = "web" +) -> Dict: + """ + Adds a resource to the BiocFileCache. + + Args: + cache_path: Path to the BiocFileCache directory. + rname: A user-friendly name for the resource. + fpath: The path to the resource, either a URL or a local file path. + action: How to handle the file. 'copy' (default), 'move', or 'asis' (for remote files). + rtype: The type of resource, 'web' (default) or 'local'. + + Returns: + A dictionary containing the command executed, stdout (the new resource ID), and stderr. + """ + _validate_cache_path(cache_path) + if rtype == "local" and not Path(fpath).exists(): + raise FileNotFoundError(f"Local file '{fpath}' not found for adding to cache.") + + safe_cache_path = str(cache_path).replace('\\', '/') + # Escape single quotes and normalize path for R + safe_rname = rname.replace("'", "\\'") + safe_fpath = fpath.replace('\\', '/').replace("'", "\\'") + + r_command = ( + f"library(BiocFileCache); " + f"bfc <- BiocFileCache('{safe_cache_path}', ask=FALSE); " + f"rid <- bfcadd(bfc, rname='{safe_rname}', fpath='{safe_fpath}', action='{action}', rtype='{rtype}'); " + f"cat(rid)" + ) + return _run_r_command(r_command) + +@mcp.tool() +def biocfilecache_rpath(cache_path: Path, rids: List[str]) -> Dict: + """ + Retrieves the local file paths of resources from the cache using their resource IDs (rids). + + Args: + cache_path: Path to the BiocFileCache directory. + rids: A list of resource IDs (e.g., ['BFC1', 'BFC2']) to look up. + + Returns: + A dictionary containing the command executed, stdout (newline-separated file paths), and stderr. + """ + _validate_cache_path(cache_path) + if not rids: + raise ValueError("The 'rids' list cannot be empty.") + + safe_cache_path = str(cache_path).replace('\\', '/') + rids_vector = _r_string_vector(rids) + r_command = ( + f"library(BiocFileCache); " + f"bfc <- BiocFileCache('{safe_cache_path}', ask=FALSE); " + f"paths <- bfcrpath(bfc, rids={rids_vector}); " + f"cat(paths, sep='\\n')" + ) + return _run_r_command(r_command) + +@mcp.tool() +def biocfilecache_query(cache_path: Path, query: str, field: Optional[str] = None) -> Dict: + """ + Queries the cache metadata using an SQL-like expression. + + Args: + cache_path: Path to the BiocFileCache directory. + query: The SQL 'WHERE' clause for filtering resources (e.g., "rname == 'my_file'"). + field: Optional. The specific column/field to return from the query results. + + Returns: + A dictionary containing the command executed, stdout (query results as a table), and stderr. + """ + _validate_cache_path(cache_path) + safe_cache_path = str(cache_path).replace('\\', '/') + safe_query = query.replace("'", "\\'") + + field_arg = "" + if field: + safe_field = field.replace("'", "\\'") + field_arg = f", field='{safe_field}'" + + r_command = ( + f"library(BiocFileCache); " + f"bfc <- BiocFileCache('{safe_cache_path}', ask=FALSE); " + f"res <- bfcquery(bfc, query='{safe_query}'{field_arg}); " + f"print(res)" + ) + return _run_r_command(r_command) + +@mcp.tool() +def biocfilecache_remove(cache_path: Path, rids: List[str]) -> Dict: + """ + Removes resources and their associated files from the cache. + + Args: + cache_path: Path to the BiocFileCache directory. + rids: A list of resource IDs to remove. + + Returns: + A dictionary containing the command executed, stdout, and stderr. + """ + _validate_cache_path(cache_path) + if not rids: + raise ValueError("The 'rids' list cannot be empty.") + + safe_cache_path = str(cache_path).replace('\\', '/') + rids_vector = _r_string_vector(rids) + r_command = ( + f"library(BiocFileCache); " + f"bfc <- BiocFileCache('{safe_cache_path}', ask=FALSE); " + f"bfcremove(bfc, rids={rids_vector}); " + f"cat('Specified resources removed.')" + ) + return _run_r_command(r_command) + +@mcp.tool() +def biocfilecache_ls(cache_path: Path, pattern: Optional[str] = None) -> Dict: + """ + Lists resources in the cache, optionally filtering by a regular expression. + + Args: + cache_path: Path to the BiocFileCache directory. + pattern: An optional regular expression to filter resource names (rname). + + Returns: + A dictionary containing the command executed, stdout (a table of resources), and stderr. + """ + _validate_cache_path(cache_path) + safe_cache_path = str(cache_path).replace('\\', '/') + + pattern_arg = "" + if pattern: + safe_pattern = pattern.replace("'", "\\'") + pattern_arg = f", pattern='{safe_pattern}'" + + r_command = ( + f"library(BiocFileCache); " + f"bfc <- BiocFileCache('{safe_cache_path}', ask=FALSE); " + f"res <- bfcls(bfc{pattern_arg}); " + f"print(res)" + ) + return _run_r_command(r_command) + +@mcp.tool() +def biocfilecache_update(cache_path: Path, rids: List[str]) -> Dict: + """ + Updates resources in the cache by re-downloading them. + + Args: + cache_path: Path to the BiocFileCache directory. + rids: A list of resource IDs to update. + + Returns: + A dictionary containing the command executed, stdout (updated resource info), and stderr. + """ + _validate_cache_path(cache_path) + if not rids: + raise ValueError("The 'rids' list cannot be empty.") + + safe_cache_path = str(cache_path).replace('\\', '/') + rids_vector = _r_string_vector(rids) + r_command = ( + f"library(BiocFileCache); " + f"bfc <- BiocFileCache('{safe_cache_path}', ask=FALSE); " + f"res <- bfcupdate(bfc, rids={rids_vector}); " + f"print(res)" + ) + return _run_r_command(r_command) + +@mcp.tool() +def biocfilecache_clean(cache_path: Path) -> Dict: + """ + Cleans the cache by removing files that are no longer tracked in the database. + + Args: + cache_path: Path to the BiocFileCache directory. + + Returns: + A dictionary containing the command executed, stdout, and stderr. + """ + _validate_cache_path(cache_path) + safe_cache_path = str(cache_path).replace('\\', '/') + r_command = ( + f"library(BiocFileCache); " + f"bfc <- BiocFileCache('{safe_cache_path}', ask=FALSE); " + f"bfcclean(bfc, ask=FALSE); " + f"cat('Cache cleaned.')" + ) + return _run_r_command(r_command) + +@mcp.tool() +def biocfilecache_info(cache_path: Path, rids: Optional[List[str]] = None) -> Dict: + """ + Retrieves detailed metadata for all or specified resources in the cache. + + Args: + cache_path: Path to the BiocFileCache directory. + rids: Optional list of resource IDs to get information for. If None, info for all resources is returned. + + Returns: + A dictionary containing the command executed, stdout (a table of resource info), and stderr. + """ + _validate_cache_path(cache_path) + safe_cache_path = str(cache_path).replace('\\', '/') + rids_arg = f", rids={_r_string_vector(rids)}" if rids else "" + + r_command = ( + f"library(BiocFileCache); " + f"bfc <- BiocFileCache('{safe_cache_path}', ask=FALSE); " + f"res <- bfcinfo(bfc{rids_arg}); " + f"print(res)" + ) + return _run_r_command(r_command) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocfilecache/app/bioconductor-biocfilecache_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocfilecache/app/bioconductor-biocfilecache_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..bdd83bb69ff25fe4603d042768fcbbcf5ecb11ab --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocfilecache/app/bioconductor-biocfilecache_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-biocfilecache/app/bioconductor-biocfilecache_server.py') +SERVER_NAME = 'biosci_bioconductor_biocfilecache' + + +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-biocfilecache/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocfilecache/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocfilecache/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocfilecache/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocfilecache/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..dfaeb2fc1b7bb666760166c994ac11641ccea05c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocfilecache/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-biocfilecache: + build: . + image: mcp-bioconductor-biocfilecache:latest + container_name: mcp-bioconductor-biocfilecache + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-biocfilecache + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocfilecache/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocfilecache/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fadedb1ae2ed0930e924af8fb048742ab8741ed4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocfilecache/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-biocfilecache + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocfilecache/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocfilecache/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocfilecache/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocio/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocio/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6985b38e799424429cc20852d53049a1c6108713 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocio/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-biocio via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-biocio -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-biocio_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-biocio_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-biocio_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocio/app/bioconductor-biocio_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocio/app/bioconductor-biocio_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ebb8c09cffcee79012bed7eab854136ab0840ca5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocio/app/bioconductor-biocio_server.py @@ -0,0 +1,201 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Dict, List, Optional + +# @mcp.tool() decorator is assumed to be available in the environment. +# For local testing, you can define a dummy decorator: +# def tool(*args, **kwargs): +# def decorator(f): +# return f +# return decorator +# mcp = type("mcp", (), {"tool": tool}) + + +@mcp.tool() +def biocio_import( + input_file: Path, + output_rds: Path, + additional_args: Optional[str] = None, +) -> Dict: + """ + Imports data using the BiocIO::import() generic function. + + This tool wraps the R BiocIO package's `import()` function. It reads a + biological data file and saves the resulting R object to a file in RDS + (R Data Serialization) format. The execution requires an R environment + with BiocIO and any necessary backend packages (e.g., rtracklayer for + BAM/BED/GFF, rhdf5 for HDF5) installed. + + Args: + input_file (Path): Path to the input data file to be imported. + output_rds (Path): Path for the output RDS file, which will store the + imported R object. + additional_args (Optional[str]): A string of additional arguments to be + passed to the R `import()` function. + Arguments should be in R syntax, + e.g., "format = 'gff3'". + + Returns: + Dict: A dictionary containing the execution command, stdout, stderr, + and a list of output files. + """ + # Input validation + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + # Prepare arguments for the R function call + r_args = [f"'{input_file}'"] + if additional_args: + r_args.append(additional_args) + + r_function_call = f"BiocIO::import({', '.join(r_args)})" + + # Construct the R script + r_script_content = f""" + # It is crucial that the R environment has the necessary package + # to handle the specific file format (e.g., rtracklayer for BED/BAM). + library(BiocIO) + + try {{ + data_object <- {r_function_call} + saveRDS(data_object, file = '{output_rds}') + cat("Import successful. Object saved to {output_rds}\\n") + }} catch (e) {{ + stop(e) + }} + """ + + command_executed = "" + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_script: + tmp_script.write(r_script_content) + script_path = tmp_script.name + + command = ["Rscript", script_path] + command_executed = " ".join(command) + + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_rds)] + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } + finally: + # Clean up the temporary script file + if 'script_path' in locals() and Path(script_path).exists(): + Path(script_path).unlink() + + +@mcp.tool() +def biocio_export( + input_rds: Path, + output_file: Path, + format: Optional[str] = None, + additional_args: Optional[str] = None, +) -> Dict: + """ + Exports an R object using the BiocIO::export() generic function. + + This tool wraps the R BiocIO package's `export()` function. It reads an R + object from an RDS file and exports it to a specified biological data format. + The execution requires an R environment with BiocIO and any necessary backend + packages (e.g., rtracklayer for BAM/BED/GFF) installed. + + Args: + input_rds (Path): Path to the input RDS file containing the R object + to be exported. + output_file (Path): Path for the output data file. The file extension + often determines the format. + format (Optional[str]): Explicitly specify the output format (e.g., "gff3"). + If not provided, it's often inferred from the + output file extension. + additional_args (Optional[str]): A string of additional arguments to be + passed to the R `export()` function. + Arguments should be in R syntax. + + Returns: + Dict: A dictionary containing the execution command, stdout, stderr, + and a list of output files. + """ + # Input validation + if not input_rds.exists(): + raise FileNotFoundError(f"Input RDS file not found: {input_rds}") + + # Prepare arguments for the R function call + r_args = ["data_object", f"'{output_file}'"] + if format: + r_args.append(f"format = '{format}'") + if additional_args: + r_args.append(additional_args) + + r_function_call = f"BiocIO::export({', '.join(r_args)})" + + # Construct the R script + r_script_content = f""" + # It is crucial that the R environment has the necessary package + # to handle the specific file format (e.g., rtracklayer for BED/BAM). + library(BiocIO) + + try {{ + data_object <- readRDS('{input_rds}') + {r_function_call} + cat("Export successful. Object saved to {output_file}\\n") + }} catch (e) {{ + stop(e) + }} + """ + + command_executed = "" + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_script: + tmp_script.write(r_script_content) + script_path = tmp_script.name + + command = ["Rscript", script_path] + command_executed = " ".join(command) + + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file)] + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } + finally: + # Clean up the temporary script file + if 'script_path' in locals() and Path(script_path).exists(): + Path(script_path).unlink() diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocio/app/bioconductor-biocio_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocio/app/bioconductor-biocio_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..adc6e1a3d831010356cfbd1f46ee67ac23184698 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocio/app/bioconductor-biocio_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-biocio/app/bioconductor-biocio_server.py') +SERVER_NAME = 'biosci_bioconductor_biocio' + + +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-biocio/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocio/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocio/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocio/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocio/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..639c0c707fd92900cbd7d5b4ec93167bda8bc2b0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocio/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-biocio: + build: . + image: mcp-bioconductor-biocio:latest + container_name: mcp-bioconductor-biocio + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-biocio + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocio/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocio/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f80685f1ad4043c5b78b5798a9100413f2fb54c0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocio/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-biocio + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocio/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocio/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biocio/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biomformat/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biomformat/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9421f7ac6a878b4b1b6b7db6f6b3aee6be5ab144 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biomformat/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-biomformat via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-biomformat -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-biomformat_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-biomformat_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-biomformat_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biomformat/app/bioconductor-biomformat_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biomformat/app/bioconductor-biomformat_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e906730466384d67a76c03c53d52bb7d5b0ed83b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biomformat/app/bioconductor-biomformat_server.py @@ -0,0 +1,271 @@ +import subprocess +import tempfile +import textwrap +from pathlib import Path +from typing import Any, Dict, List, Optional + +# Assume mcp is imported and the decorator is available in the execution environment +# from mcp import mcp + +def _check_rscript_dependency(): + """Checks if Rscript is installed and in the system's PATH.""" + try: + # Use a benign command to check for Rscript existence and executability + subprocess.run(['Rscript', '--version'], check=True, capture_output=True) + except (subprocess.CalledProcessError, FileNotFoundError) as e: + raise RuntimeError( + "Rscript command not found or failed to execute. " + "Please ensure R is installed and 'Rscript' is in your system's PATH." + ) from e + +def _run_r_script(r_script_content: str) -> subprocess.CompletedProcess: + """ + Executes a given R script string in a temporary file and handles errors. + + Also checks for the 'biomformat' package within the R script itself. + """ + r_script_path = "" + try: + # Use a temporary file to hold the R script + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + # Add a check for the required R package at the beginning of every script + package_check = textwrap.dedent(""" + if (!requireNamespace("biomformat", quietly = TRUE)) { + stop("The 'biomformat' R package is not installed. Please install it from Bioconductor using: if (!requireNamespace('BiocManager', quietly = TRUE)) install.packages('BiocManager'); BiocManager::install('biomformat')", call. = FALSE) + } + library(biomformat) + """) + r_script_file.write(package_check) + r_script_file.write(r_script_content) + r_script_path = r_script_file.name + + command = ["Rscript", r_script_path] + + # Execute the command + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return process + + except subprocess.CalledProcessError as e: + # Combine stdout and stderr for a more comprehensive error message from R + error_message = ( + f"R script execution failed with exit code {e.returncode}.\n" + f"COMMAND: {' '.join(e.cmd)}\n" + f"STDOUT:\n{e.stdout}\n" + f"STDERR:\n{e.stderr}\n" + ) + raise RuntimeError(error_message) from e + finally: + # Ensure the temporary file is cleaned up + if r_script_path and Path(r_script_path).exists(): + Path(r_script_path).unlink() + + +@mcp.tool() +def summarize_biom( + input_biom_file: Path, +) -> Dict[str, Any]: + """ + Summarizes the contents of a BIOM file. + + This tool reads a BIOM file and prints a summary of its contents, + including dimensions and metadata information, to standard output. + It requires the 'biomformat' R package to be installed. + + Args: + input_biom_file: Path to the input BIOM file. + + Returns: + A dictionary containing the execution details, including the command, + stdout (with the summary), and stderr. + """ + # Input validation + if not input_biom_file.is_file(): + raise FileNotFoundError(f"Input BIOM file not found: {input_biom_file}") + + _check_rscript_dependency() + + r_script_content = textwrap.dedent(f""" + biom_object <- read_biom("{input_biom_file.resolve()}") + print(biom_object) + """) + + process = _run_r_script(r_script_content) + + return { + "command_executed": f"Rscript -e 'print(biomformat::read_biom(\"{input_biom_file}\"))'", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [] + } + + +@mcp.tool() +def biom_to_tsv( + input_biom_file: Path, + output_prefix: str, + output_dir: Optional[Path] = None +) -> Dict[str, Any]: + """ + Converts a BIOM file into three separate TSV files. + + This tool extracts the observation data matrix, sample metadata, and + observation metadata from a BIOM file and saves them as individual + tab-separated value (TSV) files. It requires the 'biomformat' R package. + + Args: + input_biom_file: Path to the input BIOM file. + output_prefix: The prefix for the output TSV files (e.g., 'my_study'). + output_dir: The directory to save the output files. Defaults to the + directory of the input file if not specified. + + Returns: + A dictionary containing the execution details and a list of paths + to the generated TSV files. + """ + # Input validation + if not input_biom_file.is_file(): + raise FileNotFoundError(f"Input BIOM file not found: {input_biom_file}") + if not output_prefix.strip(): + raise ValueError("Output prefix cannot be empty or just whitespace.") + + _check_rscript_dependency() + + # Handle output directory + if output_dir is None: + output_dir = input_biom_file.parent + output_dir.mkdir(parents=True, exist_ok=True) + + # Define output file paths + data_out_path = output_dir / f"{output_prefix}_data.tsv" + sample_meta_out_path = output_dir / f"{output_prefix}_sample_metadata.tsv" + obs_meta_out_path = output_dir / f"{output_prefix}_observation_metadata.tsv" + + r_script_content = textwrap.dedent(f""" + biom_object <- read_biom("{input_biom_file.resolve()}") + + # Extract and write observation data + data_matrix <- as(biom_data(biom_object), "matrix") + write.table(data_matrix, file="{data_out_path.resolve()}", sep="\\t", quote=FALSE, col.names=NA, row.names=TRUE) + + # Extract and write sample metadata if it exists + sample_meta <- sample_metadata(biom_object) + if (!is.null(sample_meta)) {{ + write.table(sample_meta, file="{sample_meta_out_path.resolve()}", sep="\\t", quote=FALSE, col.names=NA, row.names=TRUE) + }} + + # Extract and write observation metadata if it exists + obs_meta <- observation_metadata(biom_object) + if (!is.null(obs_meta)) {{ + write.table(obs_meta, file="{obs_meta_out_path.resolve()}", sep="\\t", quote=FALSE, col.names=NA, row.names=TRUE) + }} + """) + + process = _run_r_script(r_script_content) + + # Determine which files were actually created and return their paths + created_files = [] + if data_out_path.exists(): + created_files.append(str(data_out_path.resolve())) + if sample_meta_out_path.exists(): + created_files.append(str(sample_meta_out_path.resolve())) + if obs_meta_out_path.exists(): + created_files.append(str(obs_meta_out_path.resolve())) + + return { + "command_executed": f"Rscript execution for biom_to_tsv", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": created_files + } + + +@mcp.tool() +def tsv_to_biom( + observation_data_file: Path, + output_biom_file: Path, + sample_metadata_file: Optional[Path] = None, + observation_metadata_file: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Creates a BIOM file from observation data and optional metadata TSV files. + + This tool assembles a BIOM file from a mandatory observation data matrix + and optional sample and observation metadata files. All input files should + be tab-separated. It requires the 'biomformat' R package. + + Args: + observation_data_file: Path to the observation data matrix TSV file. + The first column should be observation IDs and the + first row should be sample IDs. + output_biom_file: Path for the output BIOM file. + sample_metadata_file: Optional path to the sample metadata TSV file. + The first column should be sample IDs. + observation_metadata_file: Optional path to the observation metadata + TSV file. The first column should be + observation IDs. + + Returns: + A dictionary containing the execution details and a list with the path + to the generated BIOM file. + """ + # Input validation + if not observation_data_file.is_file(): + raise FileNotFoundError(f"Observation data file not found: {observation_data_file}") + if sample_metadata_file and not sample_metadata_file.is_file(): + raise FileNotFoundError(f"Sample metadata file not found: {sample_metadata_file}") + if observation_metadata_file and not observation_metadata_file.is_file(): + raise FileNotFoundError(f"Observation metadata file not found: {observation_metadata_file}") + + _check_rscript_dependency() + + # Ensure output directory exists + output_biom_file.parent.mkdir(parents=True, exist_ok=True) + + # Prepare paths for R script, handling optional files + obs_data_path_str = str(observation_data_file.resolve()) + sample_meta_path_str = f'"{sample_metadata_file.resolve()}"' if sample_metadata_file else "NULL" + obs_meta_path_str = f'"{observation_metadata_file.resolve()}"' if observation_metadata_file else "NULL" + output_path_str = str(output_biom_file.resolve()) + + r_script_content = textwrap.dedent(f""" + # Read observation data + obs_data <- as.matrix(read.table("{obs_data_path_str}", header=TRUE, sep="\\t", row.names=1, check.names=FALSE, comment.char="")) + + # Read sample metadata if provided + sample_meta <- NULL + sample_meta_path <- {sample_meta_path_str} + if (!is.null(sample_meta_path)) {{ + sample_meta <- read.table(sample_meta_path, header=TRUE, sep="\\t", row.names=1, check.names=FALSE, comment.char="") + }} + + # Read observation metadata if provided + obs_meta <- NULL + obs_meta_path <- {obs_meta_path_str} + if (!is.null(obs_meta_path)) {{ + obs_meta <- read.table(obs_meta_path, header=TRUE, sep="\\t", row.names=1, check.names=FALSE, comment.char="") + }} + + # Create the biom object + biom_object <- make_biom(data = obs_data, sample_metadata = sample_meta, observation_metadata = obs_meta) + + # Write the BIOM file + write_biom(biom_object, "{output_path_str}") + """) + + process = _run_r_script(r_script_content) + + # Verify output file creation + if not output_biom_file.exists(): + raise FileNotFoundError(f"Expected output BIOM file was not created: {output_biom_file}") + + return { + "command_executed": "Rscript execution for tsv_to_biom", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_biom_file.resolve())] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biomformat/app/bioconductor-biomformat_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biomformat/app/bioconductor-biomformat_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4086468a093ead35b2fbadf402fcb03d03d745cf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biomformat/app/bioconductor-biomformat_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-biomformat/app/bioconductor-biomformat_server.py') +SERVER_NAME = 'biosci_bioconductor_biomformat' + + +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-biomformat/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biomformat/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biomformat/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biomformat/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biomformat/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..86cabcccd9eb81b29a1a10145f27a8e36bbd6602 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biomformat/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-biomformat: + build: . + image: mcp-bioconductor-biomformat:latest + container_name: mcp-bioconductor-biomformat + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-biomformat + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biomformat/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biomformat/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4ec0abb2d3fc1c760f68917798e92c1f2f3e5bd7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biomformat/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-biomformat + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biomformat/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biomformat/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biomformat/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biovizbase/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biovizbase/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..900cfadbfef72b2bc8831b962e9c8bde993aaf6f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biovizbase/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-biovizbase via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-biovizbase -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-biovizbase_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-biovizbase_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-biovizbase_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biovizbase/app/bioconductor-biovizbase_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biovizbase/app/bioconductor-biovizbase_server.py new file mode 100644 index 0000000000000000000000000000000000000000..eabb9c6c03443e60229341b618b8417d45475739 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biovizbase/app/bioconductor-biovizbase_server.py @@ -0,0 +1,437 @@ +import subprocess +from pathlib import Path +from typing import Optional, List +import tempfile +import json +import re + +# NOTE: The @mcp.tool decorator is a placeholder for the actual MCP decorator. +# This code is designed to be used within an MCP environment where `mcp` is defined. + +class mcp: + """Placeholder for MCP decorator for standalone validation.""" + @staticmethod + def tool(): + def decorator(f): + return f + return decorator + +@mcp.tool() +def biovizbase_get_ideogram( + genome: str, + cytoband: bool = True, + sub_set: Optional[str] = None, + output_csv: Optional[str] = None +) -> dict: + """ + Fetches chromosome ideogram data for a specified genome build from UCSC. + + Args: + genome: Genome build name (e.g., 'hg19', 'mm10'). Must be a valid UCSC genome. + cytoband: If True, includes cytoband information in the ideogram. + sub_set: Optional comma-separated list of chromosomes to include (e.g., 'chr1,chr2'). + output_csv: Optional path to save the ideogram data as a CSV file. If not provided, a temporary file will be used. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + if not genome: + raise ValueError("The 'genome' parameter cannot be empty.") + + out_path = Path(output_csv) if output_csv else Path(tempfile.mktemp(suffix=".csv")) + + subset_code = "sub_set = NULL" + if sub_set: + # Format the subset string for R: 'chr1,chr2' -> 'c("chr1", "chr2")' + formatted_sub_set = ','.join([f'"{s.strip()}"' for s in sub_set.split(',')]) + subset_code = f"sub_set = c({formatted_sub_set})" + + r_script = f""" + library(biovizBase) + {subset_code} + ideogram <- getIdeogram(genome = "{genome}", cytoband = {str(cytoband).upper()}, sub_set = sub_set) + write.csv(as.data.frame(ideogram), file = "{out_path}", row.names = FALSE) + """ + + command = ["Rscript", "-e", r_script] + command_executed = f"Rscript -e '{r_script.strip()}'" + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_path)] if out_path.exists() else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + +@mcp.tool() +def biovizbase_crunch( + input_file: str, + file_format: str, + which_range: Optional[str] = None, + output_csv: Optional[str] = None +) -> dict: + """ + Transforms genomic data (e.g., BAM, BED, GTF) into a format suitable for visualization by summarizing ranges. + + Args: + input_file: Path to the input genomic data file. + file_format: Format of the input file (e.g., 'bam', 'bed', 'gtf', 'gff'). + which_range: Genomic range to process, in 'chr:start-end' format (e.g., 'chr1:1000-2000'). + output_csv: Optional path to save the crunched data as a CSV file. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + input_path = Path(input_file) + if not input_path.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + if which_range and not re.match(r'^\w+:\d+-\d+$', which_range): + raise ValueError("The 'which_range' parameter must be in the format 'chr:start-end'.") + + out_path = Path(output_csv) if output_csv else Path(tempfile.mktemp(suffix=".csv")) + + range_code = "" + if which_range: + chrom, coords = which_range.split(':') + start, end = coords.split('-') + range_code = f', which = GRanges("{chrom}", IRanges({start}, {end}))' + + r_script = f""" + library(biovizBase) + library(GenomicRanges) + library(rtracklayer) + + if ("{file_format.lower()}" == "bam") {{ + library(Rsamtools) + data <- readGAlignments("{input_path}") + }} else {{ + data <- import("{input_path}", format = "{file_format.lower()}") + }} + + res <- crunch(data{range_code}) + write.csv(as.data.frame(res), file = "{out_path}", row.names = FALSE) + """ + + command = ["Rscript", "-e", r_script] + command_executed = f"Rscript -e '{r_script.strip()}'" + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_path)] if out_path.exists() else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + +@mcp.tool() +def biovizbase_get_bio_color( + color_type: str = "DNA" +) -> dict: + """ + Retrieves standard biological color schemes as a JSON object. + + Args: + color_type: The category of color scheme. Can be 'DNA', 'RNA', 'AMINO_ACID', 'STRAND', 'CYTOBAND', or a UCSC genome build (e.g., 'hg19'). + + Returns: + A dictionary containing the command executed, stdout (with JSON color data), and stderr. + """ + if not color_type: + raise ValueError("The 'color_type' parameter cannot be empty.") + + r_script = f""" + library(biovizBase) + library(jsonlite) + cols <- getBioColor(type = "{color_type}") + cat(jsonlite::toJSON(cols, auto_unbox = TRUE)) + """ + + command = ["Rscript", "-e", r_script] + command_executed = f"Rscript -e '{r_script.strip()}'" + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def biovizbase_calculate_islands( + input_file: str, + output_csv: Optional[str] = None +) -> dict: + """ + Identifies genomic 'islands' (regions of high density/coverage) in alignment or feature data. + + Args: + input_file: Path to the input file (e.g., BAM, BED). + output_csv: Optional path to save the island coordinates as a CSV file. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + input_path = Path(input_file) + if not input_path.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + out_path = Path(output_csv) if output_csv else Path(tempfile.mktemp(suffix=".csv")) + + r_script = f""" + library(biovizBase) + library(GenomicRanges) + library(rtracklayer) + + if (grepl("\\\\.bam$", "{input_path}", ignore.case = TRUE)) {{ + library(Rsamtools) + data <- readGAlignments("{input_path}") + }} else {{ + data <- import("{input_path}") + }} + + res <- islands(data) + write.csv(as.data.frame(res), file = "{out_path}", row.names = FALSE) + """ + + command = ["Rscript", "-e", r_script] + command_executed = f"Rscript -e '{r_script.strip()}'" + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_path)] if out_path.exists() else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + +@mcp.tool() +def biovizbase_add_stepping( + input_file: str, + group_name: Optional[str] = None, + extend: int = 0, + output_csv: Optional[str] = None +) -> dict: + """ + Calculates 'stepping' levels for genomic ranges to avoid overlaps in visualization. + + Args: + input_file: Path to input BED, GFF, or other range-based file. + group_name: Optional column name in the data to group by for stepping calculation. + extend: Number of base pairs to extend ranges on each side for overlap calculation. Must be non-negative. + output_csv: Optional path to save the data with the new 'stepping' column. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + input_path = Path(input_file) + if not input_path.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if extend < 0: + raise ValueError("The 'extend' parameter must be a non-negative integer.") + + out_path = Path(output_csv) if output_csv else Path(tempfile.mktemp(suffix=".csv")) + group_code = f', group.name = "{group_name}"' if group_name else "" + + r_script = f""" + library(biovizBase) + library(rtracklayer) + data <- import("{input_path}") + res <- addStepping(data{group_code}, extend = {extend}) + write.csv(as.data.frame(res), file = "{out_path}", row.names = FALSE) + """ + + command = ["Rscript", "-e", r_script] + command_executed = f"Rscript -e '{r_script.strip()}'" + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_path)] if out_path.exists() else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + +@mcp.tool() +def biovizbase_rescale_ranges( + input_file: str, + to_start: int = 0, + to_end: int = 1000, + output_csv: Optional[str] = None +) -> dict: + """ + Rescales genomic coordinates from their original range to a new numeric range. + + Args: + input_file: Path to input BED, GFF, or other range-based file. + to_start: Start of the target numeric range. + to_end: End of the target numeric range. + output_csv: Optional path to save the rescaled data. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + input_path = Path(input_file) + if not input_path.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if to_start >= to_end: + raise ValueError("The 'to_start' parameter must be less than 'to_end'.") + + out_path = Path(output_csv) if output_csv else Path(tempfile.mktemp(suffix=".csv")) + + r_script = f""" + library(biovizBase) + library(rtracklayer) + data <- import("{input_path}") + res <- rescale(data, to = c({to_start}, {to_end})) + write.csv(as.data.frame(res), file = "{out_path}", row.names = FALSE) + """ + + command = ["Rscript", "-e", r_script] + command_executed = f"Rscript -e '{r_script.strip()}'" + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_path)] if out_path.exists() else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + +@mcp.tool() +def biovizbase_shrink_introns( + input_file: str, + output_csv: Optional[str] = None +) -> dict: + """ + Shrinks intron regions in transcript data to emphasize exons in visualization. + + Args: + input_file: Path to input GTF/GFF file containing transcript models. + output_csv: Optional path to save the data with shrunk introns. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + input_path = Path(input_file) + if not input_path.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + out_path = Path(output_csv) if output_csv else Path(tempfile.mktemp(suffix=".csv")) + + r_script = f""" + library(biovizBase) + library(GenomicFeatures) + library(rtracklayer) + + # Create a TxDb object for transcript grouping, which is required for shrink + txdb <- makeTxDbFromGFF("{input_path}") + exons <- exonsBy(txdb, by = "tx", use.names = TRUE) + + res <- shrink(exons) + # The result is a GRangesList, we flatten it for CSV output + res_df <- as.data.frame(unlist(res)) + write.csv(res_df, file = "{out_path}", row.names = FALSE) + """ + + command = ["Rscript", "-e", r_script] + command_executed = f"Rscript -e '{r_script.strip()}'" + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_path)] if out_path.exists() else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biovizbase/app/bioconductor-biovizbase_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biovizbase/app/bioconductor-biovizbase_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1a8eeda3a6f82f6baff6447348d3c7ea412bf6d4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biovizbase/app/bioconductor-biovizbase_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-biovizbase/app/bioconductor-biovizbase_server.py') +SERVER_NAME = 'biosci_bioconductor_biovizbase' + + +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-biovizbase/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biovizbase/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biovizbase/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biovizbase/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biovizbase/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..ec98af79d2afcd4da2168365a6d769cca60b2788 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biovizbase/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-biovizbase: + build: . + image: mcp-bioconductor-biovizbase:latest + container_name: mcp-bioconductor-biovizbase + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-biovizbase + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biovizbase/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biovizbase/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..015aa551125ca59333db8d3256a12bf658161fbf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biovizbase/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-biovizbase + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biovizbase/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biovizbase/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-biovizbase/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-blase/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-blase/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..130d0cb09407199e02934e5328c96ea05926be5b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-blase/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-blase via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-blase -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-blase_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-blase_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-blase_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-blase/app/bioconductor-blase_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-blase/app/bioconductor-blase_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2ecf7c7b5941aa1701f359beacdb76478e761aef --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-blase/app/bioconductor-blase_server.py @@ -0,0 +1,185 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, Dict, List + +# In a real MCP environment, the 'mcp' package would be available. +# For standalone execution, this decorator is a placeholder. +class mcp: + @staticmethod + def tool(func=None, **kwargs): + if func: + return func + return lambda f: f + +@mcp.tool() +def blase_run( + sce_file: Path, + bulk_data_file: Path, + output_prefix: str, + n_genes: int = 2000, + assay_name: str = "logcounts", + pseudotime_column: str = "pseudotime", + cell_group_column: Optional[str] = None, + n_boots: int = 100, + n_cores: int = 1, + seed: int = 123, + seurat_assay: str = "RNA", + dispersed_features_method: str = "seurat", +) -> Dict: + """ + Runs the BLASE analysis to map bulk RNA-seq data to a single-cell pseudotime trajectory. + + BLASE (Bulk Linking Analysis for Single-cell Experiments) uses Spearman correlation + with bootstrapping to determine the position of bulk RNA-seq samples along a + single-cell pseudotime trajectory. This tool is a wrapper for the main `blaseR` + function from the Bioconductor package. + + Args: + sce_file: Path to the SingleCellExperiment or Seurat object saved as an RDS file. + bulk_data_file: Path to the bulk RNA-seq data, typically a CSV file with genes + as rows (first column) and samples as columns. + output_prefix: A prefix for the output files. Two files will be generated: + `_results.rds` and `_plot.pdf`. + n_genes: Number of highly variable genes to use for the analysis. + assay_name: Name of the assay in the SCE object containing expression data. + pseudotime_column: Name of the column in `colData(sce)` containing pseudotime values. + cell_group_column: Optional name of the column in `colData(sce)` for grouping cells. + n_boots: Number of bootstrap iterations for confidence interval calculation. + n_cores: Number of cores to use for parallel processing. + seed: Random seed for reproducibility. + seurat_assay: The assay to use if the input `sce_file` contains a Seurat object. + dispersed_features_method: Method to find dispersed features. Must be 'seurat' or 'scran'. + + Returns: + A dictionary containing the execution command, stdout, stderr, and paths to the + generated output files (RDS results and PDF plot). + """ + # --- Input Validation --- + if not sce_file.is_file(): + raise FileNotFoundError(f"Input SCE file not found: {sce_file}") + if not bulk_data_file.is_file(): + raise FileNotFoundError(f"Input bulk data file not found: {bulk_data_file}") + + if n_genes <= 0: + raise ValueError("n_genes must be a positive integer.") + if n_boots <= 0: + raise ValueError("n_boots must be a positive integer.") + if n_cores <= 0: + raise ValueError("n_cores must be a positive integer.") + + if dispersed_features_method not in ["seurat", "scran"]: + raise ValueError("dispersed_features_method must be either 'seurat' or 'scran'.") + + # --- Prepare Output Paths --- + output_rds_path = Path(f"{output_prefix}_results.rds") + output_pdf_path = Path(f"{output_prefix}_plot.pdf") + + # --- R Script Generation --- + # Handle optional string parameter for R script: convert Python None to R NULL + r_cell_group = f'"{cell_group_column}"' if cell_group_column else "NULL" + + r_script_content = f""" + # Ensure required packages are available + if (!requireNamespace("blase", quietly = TRUE)) {{ + stop("The 'blase' package is not installed. Please install it from Bioconductor.") + }} + if (!requireNamespace("ggplot2", quietly = TRUE)) {{ + stop("The 'ggplot2' package is not installed.") + }} + library(blase) + library(ggplot2) + + # --- Input parameters from MCP tool --- + sce_file <- "{sce_file.resolve()}" + bulk_data_file <- "{bulk_data_file.resolve()}" + output_rds <- "{output_rds_path.resolve()}" + output_pdf <- "{output_pdf_path.resolve()}" + n_genes_param <- {n_genes} + assay_name_param <- "{assay_name}" + pseudotime_param <- "{pseudotime_column}" + cell_group_param <- {r_cell_group} + n_boots_param <- {n_boots} + n_cores_param <- {n_cores} + seed_param <- {seed} + seurat_assay_param <- "{seurat_assay}" + dispersed_features_method_param <- "{dispersed_features_method}" + + # --- Data Loading --- + cat("Loading single-cell data from:", sce_file, "\\n") + sce <- readRDS(sce_file) + + cat("Loading bulk data from:", bulk_data_file, "\\n") + # Assuming bulk data is a standard CSV with gene names in the first column + bulk_data <- as.matrix(read.csv(bulk_data_file, row.names = 1, check.names = FALSE)) + + # --- BLASE Analysis --- + cat("Running BLASE analysis...\\n") + blase_results <- blaseR( + sce = sce, + bulk_data = bulk_data, + n_genes = n_genes_param, + assay_name = assay_name_param, + pseudotime = pseudotime_param, + cell_group = cell_group_param, + n_boots = n_boots_param, + n_cores = n_cores_param, + seed = seed_param, + seurat_assay = seurat_assay_param, + dispersed_features_method = dispersed_features_method_param + ) + + # --- Save Results --- + cat("Saving results object to:", output_rds, "\\n") + saveRDS(blase_results, file = output_rds) + + # --- Generate and Save Plot --- + cat("Generating and saving plot to:", output_pdf, "\\n") + p <- plotBlase(blase_results) + ggsave(output_pdf, plot = p, width = 8, height = 6, device = "pdf") + + cat("BLASE analysis completed successfully.\\n") + """ + + # --- Subprocess Execution --- + r_script_path = None + try: + with tempfile.NamedTemporaryFile(mode="w", suffix=".R", delete=False) as tmp_r_script: + tmp_r_script.write(r_script_content) + r_script_path = tmp_r_script.name + + cmd = ["Rscript", r_script_path] + command_executed = " ".join(cmd) + + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"R script execution failed with exit code {e.returncode}.\n" + f"Command: {e.cmd}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) from e + finally: + # Ensure the temporary R script is always removed + if r_script_path and Path(r_script_path).exists(): + Path(r_script_path).unlink() + + # --- Structured Result Return --- + output_files = { + "results_rds": str(output_rds_path.resolve()), + "results_plot": str(output_pdf_path.resolve()) + } + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-blase/app/bioconductor-blase_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-blase/app/bioconductor-blase_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a7600d92be4ed5be40eea50b5ca43d4cd1cee018 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-blase/app/bioconductor-blase_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-blase/app/bioconductor-blase_server.py') +SERVER_NAME = 'biosci_bioconductor_blase' + + +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-blase/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-blase/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-blase/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-blase/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-blase/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..eccd488237878c7b9413ba58d98e98df504b8bd1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-blase/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-blase: + build: . + image: mcp-bioconductor-blase:latest + container_name: mcp-bioconductor-blase + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-blase + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-blase/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-blase/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6a2b798ba05a05a1d718a06c7af2ed86cdfa2774 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-blase/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-blase + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-blase/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-blase/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-blase/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bluster/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bluster/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..868253a8d30934e342b1f2143bac162c0ab1eba1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bluster/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-bluster via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-bluster -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-bluster_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-bluster_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-bluster_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bluster/app/bioconductor-bluster_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bluster/app/bioconductor-bluster_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e460cdbef7c80f374bf135f37039bdb2b533c061 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bluster/app/bioconductor-bluster_server.py @@ -0,0 +1,610 @@ +import subprocess +import tempfile +import os +from pathlib import Path +from typing import Optional, List, Dict, Any + +# Note: bioconductor-bluster is an R package and does not have a direct command-line interface +# that can be executed via `subprocess.run` in the traditional sense (like `samtools` or `bwa`). +# To wrap its functionality, we need to generate and execute R scripts using `Rscript`. +# This approach effectively creates a "command-line interface" for specific R functions. +# +# The following functions demonstrate how to wrap key functionalities of the 'bluster' R package +# by generating an R script on the fly and executing it. +# +# Prerequisites: +# 1. An R environment must be installed and accessible in the system's PATH. +# 2. The 'bluster' Bioconductor package (and its dependencies) must be installed in the R environment. +# This can typically be done in R with: +# if (!requireNamespace("BiocManager", quietly = TRUE)) +# install.packages("BiocManager") +# BiocManager::install("bluster") +# install.packages("utils") # For read.csv/write.csv + +def _run_r_script(r_script_content: str, output_dir: Path) -> Dict[str, Any]: + """ + Helper function to execute an R script. + """ + with tempfile.TemporaryDirectory() as tmpdir: + script_path = Path(tmpdir) / "bluster_script.R" + with open(script_path, "w") as f: + f.write(r_script_content) + + command = ["Rscript", str(script_path)] + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + cwd=output_dir # Run Rscript in the output directory to simplify file paths + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [] # Specific tools will add their output files + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed with exit code {e.returncode}", + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: Rscript command not found. Please ensure R is installed and in your PATH.", + "error": "Rscript not found", + "output_files": [] + } + +@mcp.tool() +def cluster_rows_kmeans( + input_matrix_file: Path, + k: int, + output_clusters_file: Path, + input_format: str = "csv", + row_names_col: Optional[int] = 1, + seed: Optional[int] = None, + iterations: int = 10, + nstart: int = 1, + min_size: int = 1, + output_dir: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Performs k-means clustering on rows of a matrix using bluster::clusterRows with KmeansParam. + + Args: + input_matrix_file: Path to the input matrix file (e.g., CSV or TSV). + The matrix should have features as columns and samples as rows, + or vice-versa, depending on how 'bluster' interprets it. + Typically, rows are items to be clustered. + k: The number of clusters (k) for k-means. Must be a positive integer. + output_clusters_file: Path to save the output cluster assignments (CSV file). + This file will contain a single column 'cluster' with integer assignments. + input_format: Format of the input matrix file. Can be "csv" or "tsv". + row_names_col: Column index (1-based) to use as row names when reading the input matrix. + Set to None if no row names column is present. + seed: Random seed for reproducibility. If None, no seed is set. + iterations: Maximum number of iterations for k-means. + nstart: Number of random starts for k-means. + min_size: Minimum number of cells in a cluster. Clusters smaller than this are merged. + output_dir: Directory where output files will be written. If None, uses the current working directory. + + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + if not input_matrix_file.exists(): + raise FileNotFoundError(f"Input matrix file not found: {input_matrix_file}") + if not input_matrix_file.is_file(): + raise ValueError(f"Input matrix file is not a regular file: {input_matrix_file}") + + if k <= 0: + raise ValueError("k (number of clusters) must be a positive integer.") + if input_format not in ["csv", "tsv"]: + raise ValueError("input_format must be 'csv' or 'tsv'.") + if row_names_col is not None and row_names_col <= 0: + raise ValueError("row_names_col must be a positive integer or None.") + if iterations <= 0: + raise ValueError("iterations must be a positive integer.") + if nstart <= 0: + raise ValueError("nstart must be a positive integer.") + if min_size <= 0: + raise ValueError("min_size must be a positive integer.") + + if output_dir is None: + output_dir = Path.cwd() + output_dir.mkdir(parents=True, exist_ok=True) + + # Ensure output_clusters_file is just a filename if output_dir is specified + output_clusters_filename = output_clusters_file.name + full_output_clusters_path = output_dir / output_clusters_filename + + # Generate R script content + read_data_func = "read.csv" if input_format == "csv" else "read.delim" + row_names_arg = f"row.names = {row_names_col}" if row_names_col is not None else "" + seed_line = f"set.seed({seed})\n" if seed is not None else "" + + r_script = f""" + library(bluster) + library(utils) # For read.csv/write.csv + + # Set working directory to output_dir for relative paths + setwd("{output_dir.resolve()}") + + {seed_line} + + # Load input matrix + # Using 'tryCatch' for robust error handling within R + data_matrix <- tryCatch({{ + as.matrix({read_data_func}("{input_matrix_file.resolve()}", {row_names_arg})) + }}, error = function(e) {{ + stop(paste("Error reading input matrix file: ", e$message)) + }}) + + # Perform k-means clustering + blus_param <- KmeansParam( + centers = {k}, + iter.max = {iterations}, + nstart = {nstart}, + min.size = {min_size} + ) + + clusters <- tryCatch({{ + clusterRows(data_matrix, blus_param) + }}, error = function(e) {{ + stop(paste("Error during clustering: ", e$message)) + }}) + + # Save cluster assignments + output_df <- data.frame(cluster = clusters) + if (!is.null(rownames(data_matrix))) {{ + rownames(output_df) <- rownames(data_matrix) + }} + write.csv(output_df, "{output_clusters_filename}", row.names = TRUE) + + message("Clustering complete. Results saved to {output_clusters_filename}") + """ + + # Execute R script + result = _run_r_script(r_script, output_dir) + + if "error" not in result: + result["output_files"].append(str(full_output_clusters_path)) + + return result + +@mcp.tool() +def cluster_rows_hclust( + input_matrix_file: Path, + k: Optional[int] = None, + method: str = "ward.D2", + metric: str = "euclidean", + output_clusters_file: Path = Path("hclust_clusters.csv"), + input_format: str = "csv", + row_names_col: Optional[int] = 1, + seed: Optional[int] = None, + output_dir: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Performs hierarchical clustering on rows of a matrix using bluster::clusterRows with HclustParam. + + Args: + input_matrix_file: Path to the input matrix file (e.g., CSV or TSV). + k: The number of clusters to cut the dendrogram into. If None, the full dendrogram is returned + (though for `clusterRows` it will still attempt to cut, so it's usually required). + If not provided, `bluster` might default to a single cluster or error. + It's recommended to provide `k`. + method: The agglomeration method to be used. See `hclust` documentation for options + (e.g., "ward.D2", "single", "complete", "average"). + metric: The distance metric to be used. See `dist` documentation for options + (e.g., "euclidean", "maximum", "manhattan"). + output_clusters_file: Path to save the output cluster assignments (CSV file). + input_format: Format of the input matrix file. Can be "csv" or "tsv". + row_names_col: Column index (1-based) to use as row names when reading the input matrix. + Set to None if no row names column is present. + seed: Random seed for reproducibility. If None, no seed is set. + output_dir: Directory where output files will be written. If None, uses the current working directory. + + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + if not input_matrix_file.exists(): + raise FileNotFoundError(f"Input matrix file not found: {input_matrix_file}") + if not input_matrix_file.is_file(): + raise ValueError(f"Input matrix file is not a regular file: {input_matrix_file}") + + if k is not None and k <= 0: + raise ValueError("k (number of clusters) must be a positive integer or None.") + if method not in ["ward.D", "ward.D2", "single", "complete", "average", "mcquitty", "median", "centroid"]: + raise ValueError(f"Invalid hclust method: {method}. See `hclust` documentation.") + if metric not in ["euclidean", "maximum", "manhattan", "canberra", "binary", "minkowski"]: + raise ValueError(f"Invalid distance metric: {metric}. See `dist` documentation.") + if input_format not in ["csv", "tsv"]: + raise ValueError("input_format must be 'csv' or 'tsv'.") + if row_names_col is not None and row_names_col <= 0: + raise ValueError("row_names_col must be a positive integer or None.") + + if output_dir is None: + output_dir = Path.cwd() + output_dir.mkdir(parents=True, exist_ok=True) + + output_clusters_filename = output_clusters_file.name + full_output_clusters_path = output_dir / output_clusters_filename + + read_data_func = "read.csv" if input_format == "csv" else "read.delim" + row_names_arg = f"row.names = {row_names_col}" if row_names_col is not None else "" + seed_line = f"set.seed({seed})\n" if seed is not None else "" + k_arg = f"cut.k = {k}" if k is not None else "" # bluster::HclustParam uses cut.k + + r_script = f""" + library(bluster) + library(utils) # For read.csv/write.csv + + setwd("{output_dir.resolve()}") + + {seed_line} + + data_matrix <- tryCatch({{ + as.matrix({read_data_func}("{input_matrix_file.resolve()}", {row_names_arg})) + }}, error = function(e) {{ + stop(paste("Error reading input matrix file: ", e$message)) + }}) + + blus_param <- HclustParam( + method = "{method}", + metric = "{metric}" + {f", {k_arg}" if k_arg else ""} + ) + + clusters <- tryCatch({{ + clusterRows(data_matrix, blus_param) + }}, error = function(e) {{ + stop(paste("Error during clustering: ", e$message)) + }}) + + output_df <- data.frame(cluster = clusters) + if (!is.null(rownames(data_matrix))) {{ + rownames(output_df) <- rownames(data_matrix) + }} + write.csv(output_df, "{output_clusters_filename}", row.names = TRUE) + + message("Hierarchical clustering complete. Results saved to {output_clusters_filename}") + """ + + result = _run_r_script(r_script, output_dir) + + if "error" not in result: + result["output_files"].append(str(full_output_clusters_path)) + + return result + +@mcp.tool() +def cluster_rows_snn_graph( + input_matrix_file: Path, + k_neighbors: int, + output_clusters_file: Path = Path("snn_clusters.csv"), + input_format: str = "csv", + row_names_col: Optional[int] = 1, + type: str = "rank", + method: str = "walktrap", + steps: int = 4, + seed: Optional[int] = None, + output_dir: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Performs Shared Nearest Neighbor (SNN) graph-based clustering using bluster::clusterRows with SNNGraphParam. + + Args: + input_matrix_file: Path to the input matrix file (e.g., CSV or TSV). + k_neighbors: Number of nearest neighbors to consider for SNN graph construction. Must be a positive integer. + output_clusters_file: Path to save the output cluster assignments (CSV file). + input_format: Format of the input matrix file. Can be "csv" or "tsv". + row_names_col: Column index (1-based) to use as row names when reading the input matrix. + Set to None if no row names column is present. + type: Type of SNN graph to construct. "rank" (default) or "number". + method: Community detection method for the SNN graph. See `igraph::cluster_walktrap`, `cluster_louvain`, etc. + (e.g., "walktrap", "louvain", "fast_greedy", "leiden"). + steps: Number of random walk steps for "walktrap" method. + seed: Random seed for reproducibility. If None, no seed is set. + output_dir: Directory where output files will be written. If None, uses the current working directory. + + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + if not input_matrix_file.exists(): + raise FileNotFoundError(f"Input matrix file not found: {input_matrix_file}") + if not input_matrix_file.is_file(): + raise ValueError(f"Input matrix file is not a regular file: {input_matrix_file}") + + if k_neighbors <= 0: + raise ValueError("k_neighbors must be a positive integer.") + if input_format not in ["csv", "tsv"]: + raise ValueError("input_format must be 'csv' or 'tsv'.") + if row_names_col is not None and row_names_col <= 0: + raise ValueError("row_names_col must be a positive integer or None.") + if type not in ["rank", "number"]: + raise ValueError("type must be 'rank' or 'number'.") + if method not in ["walktrap", "louvain", "fast_greedy", "leiden", "infomap", "label_prop", "edge_betweenness"]: + raise ValueError(f"Invalid SNN graph community detection method: {method}. See `igraph` documentation.") + if steps <= 0: + raise ValueError("steps must be a positive integer for 'walktrap' method.") + + if output_dir is None: + output_dir = Path.cwd() + output_dir.mkdir(parents=True, exist_ok=True) + + output_clusters_filename = output_clusters_file.name + full_output_clusters_path = output_dir / output_clusters_filename + + read_data_func = "read.csv" if input_format == "csv" else "read.delim" + row_names_arg = f"row.names = {row_names_col}" if row_names_col is not None else "" + seed_line = f"set.seed({seed})\n" if seed is not None else "" + + # Additional arguments for SNNGraphParam based on method + method_args = "" + if method == "walktrap": + method_args = f", steps = {steps}" + # Other methods might have specific args, but for simplicity, we'll keep it general. + + r_script = f""" + library(bluster) + library(utils) # For read.csv/write.csv + library(igraph) # For community detection methods + + setwd("{output_dir.resolve()}") + + {seed_line} + + data_matrix <- tryCatch({{ + as.matrix({read_data_func}("{input_matrix_file.resolve()}", {row_names_arg})) + }}, error = function(e) {{ + stop(paste("Error reading input matrix file: ", e$message)) + }}) + + blus_param <- SNNGraphParam( + k = {k_neighbors}, + type = "{type}", + cluster.fun = "{method}" {method_args} + ) + + clusters <- tryCatch({{ + clusterRows(data_matrix, blus_param) + }}, error = function(e) {{ + stop(paste("Error during clustering: ", e$message)) + }}) + + output_df <- data.frame(cluster = clusters) + if (!is.null(rownames(data_matrix))) {{ + rownames(output_df) <- rownames(data_matrix) + }} + write.csv(output_df, "{output_clusters_filename}", row.names = TRUE) + + message("SNN graph clustering complete. Results saved to {output_clusters_filename}") + """ + + result = _run_r_script(r_script, output_dir) + + if "error" not in result: + result["output_files"].append(str(full_output_clusters_path)) + + return result + +@mcp.tool() +def pairwise_rand_index( + clusters1_file: Path, + clusters2_file: Path, + output_rand_index_file: Path = Path("pairwise_rand_index.csv"), + input_format: str = "csv", + cluster_col_name: str = "cluster", + output_dir: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Calculates the pairwise Rand index between two sets of cluster assignments using bluster::pairwiseRand. + + Args: + clusters1_file: Path to the first cluster assignment file (e.g., CSV). + Expected to have a column named 'cluster_col_name' containing integer cluster IDs. + clusters2_file: Path to the second cluster assignment file (e.g., CSV). + Expected to have a column named 'cluster_col_name' containing integer cluster IDs. + output_rand_index_file: Path to save the output Rand index results (CSV file). + This file will contain the Rand index, adjusted Rand index, etc. + input_format: Format of the input cluster files. Can be "csv" or "tsv". + cluster_col_name: The name of the column containing cluster assignments in the input files. + output_dir: Directory where output files will be written. If None, uses the current working directory. + + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + if not clusters1_file.exists(): + raise FileNotFoundError(f"First cluster file not found: {clusters1_file}") + if not clusters1_file.is_file(): + raise ValueError(f"First cluster file is not a regular file: {clusters1_file}") + if not clusters2_file.exists(): + raise FileNotFoundError(f"Second cluster file not found: {clusters2_file}") + if not clusters2_file.is_file(): + raise ValueError(f"Second cluster file is not a regular file: {clusters2_file}") + + if input_format not in ["csv", "tsv"]: + raise ValueError("input_format must be 'csv' or 'tsv'.") + if not cluster_col_name: + raise ValueError("cluster_col_name cannot be empty.") + + if output_dir is None: + output_dir = Path.cwd() + output_dir.mkdir(parents=True, exist_ok=True) + + output_filename = output_rand_index_file.name + full_output_path = output_dir / output_filename + + read_data_func = "read.csv" if input_format == "csv" else "read.delim" + + r_script = f""" + library(bluster) + library(utils) # For read.csv/write.csv + + setwd("{output_dir.resolve()}") + + clusters1_df <- tryCatch({{ + {read_data_func}("{clusters1_file.resolve()}") + }}, error = function(e) {{ + stop(paste("Error reading first cluster file: ", e$message)) + }}) + + clusters2_df <- tryCatch({{ + {read_data_func}("{clusters2_file.resolve()}") + }}, error = function(e) {{ + stop(paste("Error reading second cluster file: ", e$message)) + }}) + + if (!("{cluster_col_name}" %in% colnames(clusters1_df))) {{ + stop("Column '{cluster_col_name}' not found in first cluster file.") + }} + if (!("{cluster_col_name}" %in% colnames(clusters2_df))) {{ + stop("Column '{cluster_col_name}' not found in second cluster file.") + }} + + clusters1 <- clusters1_df[["{cluster_col_name}"]] + clusters2 <- clusters2_df[["{cluster_col_name}"]] + + # Ensure cluster assignments have the same length + if (length(clusters1) != length(clusters2)) {{ + stop("Cluster assignment vectors have different lengths.") + }} + + rand_results <- tryCatch({{ + pairwiseRand(clusters1, clusters2, adjusted=TRUE) + }}, error = function(e) {{ + stop(paste("Error calculating pairwise Rand index: ", e$message)) + }}) + + # pairwiseRand returns a numeric vector or matrix. + # For two vectors, it's a single value (adjusted Rand index by default). + # We'll create a data frame to save it. + output_df <- data.frame( + AdjustedRandIndex = rand_results + ) + write.csv(output_df, "{output_filename}", row.names = FALSE) + + message("Pairwise Rand index calculation complete. Results saved to {output_filename}") + """ + + result = _run_r_script(r_script, output_dir) + + if "error" not in result: + result["output_files"].append(str(full_output_path)) + + return result + +@mcp.tool() +def pairwise_jaccard_index( + clusters1_file: Path, + clusters2_file: Path, + output_jaccard_index_file: Path = Path("pairwise_jaccard_index.csv"), + input_format: str = "csv", + cluster_col_name: str = "cluster", + output_dir: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Calculates the pairwise Jaccard index between two sets of cluster assignments using bluster::pairwiseJaccard. + + Args: + clusters1_file: Path to the first cluster assignment file (e.g., CSV). + Expected to have a column named 'cluster_col_name' containing integer cluster IDs. + clusters2_file: Path to the second cluster assignment file (e.g., CSV). + Expected to have a column named 'cluster_col_name' containing integer cluster IDs. + output_jaccard_index_file: Path to save the output Jaccard index results (CSV file). + This file will contain the Jaccard index. + input_format: Format of the input cluster files. Can be "csv" or "tsv". + cluster_col_name: The name of the column containing cluster assignments in the input files. + output_dir: Directory where output files will be written. If None, uses the current working directory. + + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + if not clusters1_file.exists(): + raise FileNotFoundError(f"First cluster file not found: {clusters1_file}") + if not clusters1_file.is_file(): + raise ValueError(f"First cluster file is not a regular file: {clusters1_file}") + if not clusters2_file.exists(): + raise FileNotFoundError(f"Second cluster file not found: {clusters2_file}") + if not clusters2_file.is_file(): + raise ValueError(f"Second cluster file is not a regular file: {clusters2_file}") + + if input_format not in ["csv", "tsv"]: + raise ValueError("input_format must be 'csv' or 'tsv'.") + if not cluster_col_name: + raise ValueError("cluster_col_name cannot be empty.") + + if output_dir is None: + output_dir = Path.cwd() + output_dir.mkdir(parents=True, exist_ok=True) + + output_filename = output_jaccard_index_file.name + full_output_path = output_dir / output_filename + + read_data_func = "read.csv" if input_format == "csv" else "read.delim" + + r_script = f""" + library(bluster) + library(utils) # For read.csv/write.csv + + setwd("{output_dir.resolve()}") + + clusters1_df <- tryCatch({{ + {read_data_func}("{clusters1_file.resolve()}") + }}, error = function(e) {{ + stop(paste("Error reading first cluster file: ", e$message)) + }}) + + clusters2_df <- tryCatch({{ + {read_data_func}("{clusters2_file.resolve()}") + }}, error = function(e) {{ + stop(paste("Error reading second cluster file: ", e$message)) + }}) + + if (!("{cluster_col_name}" %in% colnames(clusters1_df))) {{ + stop("Column '{cluster_col_name}' not found in first cluster file.") + }} + if (!("{cluster_col_name}" %in% colnames(clusters2_df))) {{ + stop("Column '{cluster_col_name}' not found in second cluster file.") + }} + + clusters1 <- clusters1_df[["{cluster_col_name}"]] + clusters2 <- clusters2_df[["{cluster_col_name}"]] + + # Ensure cluster assignments have the same length + if (length(clusters1) != length(clusters2)) {{ + stop("Cluster assignment vectors have different lengths.") + }} + + jaccard_results <- tryCatch({{ + pairwiseJaccard(clusters1, clusters2) + }}, error = function(e) {{ + stop(paste("Error calculating pairwise Jaccard index: ", e$message)) + }}) + + output_df <- data.frame( + JaccardIndex = jaccard_results + ) + write.csv(output_df, "{output_filename}", row.names = FALSE) + + message("Pairwise Jaccard index calculation complete. Results saved to {output_filename}") + """ + + result = _run_r_script(r_script, output_dir) + + if "error" not in result: + result["output_files"].append(str(full_output_path)) + + return result \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bluster/app/bioconductor-bluster_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bluster/app/bioconductor-bluster_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1f8fbe6b3e461b27d62da9bf45fa8c174fb49656 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bluster/app/bioconductor-bluster_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-bluster/app/bioconductor-bluster_server.py') +SERVER_NAME = 'biosci_bioconductor_bluster' + + +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-bluster/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bluster/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bluster/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bluster/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bluster/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..4e3f8a72fa973fcb6f43d8405c4e5376620ed3e0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bluster/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-bluster: + build: . + image: mcp-bioconductor-bluster:latest + container_name: mcp-bioconductor-bluster + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-bluster + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bluster/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bluster/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f740803f8f3e3ef426d32f4dc6b54cffcdc8160a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bluster/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-bluster + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bluster/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bluster/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bluster/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bsgenome/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bsgenome/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e92d90bc32975c5c742f867f85094b60f17d393d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bsgenome/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-bsgenome via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-bsgenome -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-bsgenome_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-bsgenome_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-bsgenome_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bsgenome/app/bioconductor-bsgenome_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bsgenome/app/bioconductor-bsgenome_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7e1a167c0a157f9f23cca698d11b56020f0b2dfd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bsgenome/app/bioconductor-bsgenome_server.py @@ -0,0 +1,270 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +# No need to import mcp as per instructions. + +def _run_r_command(r_code: str) -> Dict[str, Any]: + """ + Executes an R command using Rscript. + + Args: + r_code: The R code string to execute. + + Returns: + A dictionary containing command execution details, stdout, stderr, and any output files. + """ + command = ["Rscript", "-e", r_code] + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: Rscript command not found. Please ensure R is installed and in your PATH.", + "error": "Rscript not found", + "output_files": [], + } + +@mcp.tool() +def install_bsgenome_base_package( + bioc_manager_repo: str = "https://bioconductor.org/packages/release/bioc", +) -> Dict[str, Any]: + """ + Installs the core 'BSgenome' R package and 'BiocManager' if not already present. + + This function is a prerequisite for using BSgenome data packages or functionalities. + It ensures that the necessary R infrastructure is in place. + + Args: + bioc_manager_repo: The Bioconductor repository URL to use for installation. + Defaults to the standard release repository. + + Returns: + A dictionary containing command execution details, stdout, stderr, and any output files. + """ + # Input validation + if not isinstance(bioc_manager_repo, str) or not bioc_manager_repo: + raise ValueError("Bioconductor repository URL must be a non-empty string.") + + r_code = f""" + if (!require("BiocManager", quietly = TRUE)) {{ + install.packages("BiocManager", repos="https://cloud.r-project.org") + }} + BiocManager::install("BSgenome", update=FALSE, ask=FALSE, siteRepos="{bioc_manager_repo}") + """ + return _run_r_command(r_code) + +@mcp.tool() +def install_bsgenome_data_package( + data_package_name: str, + bioc_manager_repo: str = "https://bioconductor.org/packages/release/bioc", +) -> Dict[str, Any]: + """ + Installs a specific BSgenome data package (e.g., 'BSgenome.Hsapiens.UCSC.hg38'). + + These data packages contain the actual genome sequences. The core 'BSgenome' + package must be installed first using `install_bsgenome_base_package`. + + Args: + data_package_name: The exact name of the BSgenome data package to install + (e.g., "BSgenome.Hsapiens.UCSC.hg38"). + bioc_manager_repo: The Bioconductor repository URL to use for installation. + Defaults to the standard release repository. + + Returns: + A dictionary containing command execution details, stdout, stderr, and any output files. + """ + # Input validation + if not isinstance(data_package_name, str) or not data_package_name: + raise ValueError("Data package name must be a non-empty string.") + if not data_package_name.startswith("BSgenome."): + raise ValueError(f"Invalid BSgenome data package name: '{data_package_name}'. " + "It should start with 'BSgenome.'.") + if not isinstance(bioc_manager_repo, str) or not bioc_manager_repo: + raise ValueError("Bioconductor repository URL must be a non-empty string.") + + r_code = f""" + if (!require("BiocManager", quietly = TRUE)) {{ + install.packages("BiocManager", repos="https://cloud.r-project.org") + }} + BiocManager::install("{data_package_name}", update=FALSE, ask=FALSE, siteRepos="{bioc_manager_repo}") + """ + return _run_r_command(r_code) + +@mcp.tool() +def get_genome_sequence( + data_package_name: str, + seqname: str, + start: int, + end: int, + masked: bool = False, + output_file: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Retrieves a specific genomic sequence from an installed BSgenome data package. + + The specified BSgenome data package must be installed prior to calling this function + using `install_bsgenome_data_package`. + + Args: + data_package_name: The name of the installed BSgenome data package + (e.g., "BSgenome.Hsapiens.UCSC.hg38"). + seqname: The name of the sequence (e.g., "chr1", "X"). + start: The 1-based start coordinate of the sequence to retrieve. Must be a positive integer. + end: The 1-based end coordinate of the sequence to retrieve. Must be an integer + greater than or equal to start. + masked: If True, masked regions (e.g., repeats) will be returned as 'N's. + If False, the actual sequence will be returned. Defaults to False. + output_file: Optional path to a file where the retrieved sequence will be written. + If not provided, the sequence will be returned in stdout. + + Returns: + A dictionary containing command execution details, stdout, stderr, and any output files. + """ + # Input validation + if not isinstance(data_package_name, str) or not data_package_name: + raise ValueError("Data package name must be a non-empty string.") + if not data_package_name.startswith("BSgenome."): + raise ValueError(f"Invalid BSgenome data package name: '{data_package_name}'. " + "It should start with 'BSgenome.'.") + if not isinstance(seqname, str) or not seqname: + raise ValueError("Sequence name (seqname) must be a non-empty string.") + if not isinstance(start, int) or start <= 0: + raise ValueError("Start coordinate must be a positive integer.") + if not isinstance(end, int) or end < start: + raise ValueError("End coordinate must be an integer greater than or equal to the start coordinate.") + if not isinstance(masked, bool): + raise ValueError("Masked parameter must be a boolean.") + if output_file is not None and not isinstance(output_file, Path): + raise ValueError("Output file must be a Path object or None.") + + # Prepare R code + r_masked_val = "TRUE" if masked else "FALSE" + + if output_file: + output_file_path = Path(output_file) + # Ensure parent directory exists + output_file_path.parent.mkdir(parents=True, exist_ok=True) + + # Modify R code to write to file + r_code = f""" + library({data_package_name}) + genome_obj <- get(data_package_name) + seq <- getSeq(genome_obj, "{seqname}", start={start}, end={end}, masked={r_masked_val}) + writeLines(as.character(seq), con="{output_file_path.resolve()}") + """ + result = _run_r_command(r_code) + if "error" not in result: + result["output_files"].append(str(output_file_path.resolve())) + return result + else: + r_code = f""" + library({data_package_name}) + genome_obj <- get(data_package_name) + seq <- getSeq(genome_obj, "{seqname}", start={start}, end={end}, masked={r_masked_val}) + cat(as.character(seq)) + """ + return _run_r_command(r_code) + +@mcp.tool() +def list_available_sequences( + data_package_name: str, +) -> Dict[str, Any]: + """ + Lists the available sequence names (e.g., chromosomes) within an installed BSgenome data package. + + The specified BSgenome data package must be installed prior to calling this function + using `install_bsgenome_data_package`. + + Args: + data_package_name: The name of the installed BSgenome data package + (e.g., "BSgenome.Hsapiens.UCSC.hg38"). + + Returns: + A dictionary containing command execution details, stdout, stderr, and any output files. + The stdout will contain a newline-separated list of sequence names. + """ + # Input validation + if not isinstance(data_package_name, str) or not data_package_name: + raise ValueError("Data package name must be a non-empty string.") + if not data_package_name.startswith("BSgenome."): + raise ValueError(f"Invalid BSgenome data package name: '{data_package_name}'. " + "It should start with 'BSgenome.'.") + + r_code = f""" + library({data_package_name}) + genome_obj <- get(data_package_name) + cat(seqnames(genome_obj), sep="\\n") + """ + return _run_r_command(r_code) + +@mcp.tool() +def get_sequence_lengths( + data_package_name: str, + seqname: Optional[str] = None, +) -> Dict[str, Any]: + """ + Retrieves the lengths of sequences (e.g., chromosomes) within an installed BSgenome data package. + + The specified BSgenome data package must be installed prior to calling this function + using `install_bsgenome_data_package`. + + Args: + data_package_name: The name of the installed BSgenome data package + (e.g., "BSgenome.Hsapiens.UCSC.hg38"). + seqname: Optional. If provided, returns the length of only this specific sequence. + If None, returns lengths for all sequences. + + Returns: + A dictionary containing command execution details, stdout, stderr, and any output files. + The stdout will contain sequence names and their lengths, typically one per line. + """ + # Input validation + if not isinstance(data_package_name, str) or not data_package_name: + raise ValueError("Data package name must be a non-empty string.") + if not data_package_name.startswith("BSgenome."): + raise ValueError(f"Invalid BSgenome data package name: '{data_package_name}'. " + "It should start with 'BSgenome.'.") + if seqname is not None and (not isinstance(seqname, str) or not seqname): + raise ValueError("Sequence name (seqname) must be a non-empty string if provided.") + + if seqname: + r_code = f""" + library({data_package_name}) + genome_obj <- get(data_package_name) + len <- seqlengths(genome_obj)["{seqname}"] + if (is.na(len)) {{ + stop("Sequence '{seqname}' not found in package '{data_package_name}'.") + }} + cat("{seqname}:", len, "\\n") + """ + else: + r_code = f""" + library({data_package_name}) + genome_obj <- get(data_package_name) + lengths <- seqlengths(genome_obj) + for (i in seq_along(lengths)) {{ + cat(names(lengths)[i], ": ", lengths[i], "\\n", sep="") + }} + """ + return _run_r_command(r_code) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bsgenome/app/bioconductor-bsgenome_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bsgenome/app/bioconductor-bsgenome_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..01e8596ffb589c227faf01eb2ff69ea3a1e2bd7e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bsgenome/app/bioconductor-bsgenome_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-bsgenome/app/bioconductor-bsgenome_server.py') +SERVER_NAME = 'biosci_bioconductor_bsgenome' + + +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-bsgenome/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bsgenome/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bsgenome/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bsgenome/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bsgenome/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..a16172fc9d353b1fa84f3f1c445702f0bc06751b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bsgenome/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-bsgenome: + build: . + image: mcp-bioconductor-bsgenome:latest + container_name: mcp-bioconductor-bsgenome + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-bsgenome + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bsgenome/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bsgenome/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1d3824d6847258fcb5b0a063d4a0c1268b07dfd8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bsgenome/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-bsgenome + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bsgenome/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bsgenome/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bsgenome/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bulksignalr/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bulksignalr/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3107847f2dfbb429afa7fc70ade5d99d13d901f4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bulksignalr/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-bulksignalr via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-bulksignalr -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-bulksignalr_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-bulksignalr_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-bulksignalr_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bulksignalr/app/bioconductor-bulksignalr_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bulksignalr/app/bioconductor-bulksignalr_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fceafe436f9410a48cffc08c311005e5447581b1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bulksignalr/app/bioconductor-bulksignalr_server.py @@ -0,0 +1,465 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional + +# This is a placeholder for the MCP decorator. +# The actual MCP environment will provide this. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +# --- R Script Templates --- + +R_SCRIPT_BULK_DE = """ +# Load libraries +suppressPackageStartupMessages(library(argparse)) +suppressPackageStartupMessages(library(bulksignalr)) +suppressPackageStartupMessages(library(SingleCellExperiment)) +suppressPackageStartupMessages(library(Matrix)) + +# Create a parser +parser <- ArgumentParser(description = "Run bulksignalr bulk_de") + +# Add arguments +parser$add_argument("--counts", type = "character", required = TRUE, help = "Path to the counts matrix file (TSV format)") +parser$add_argument("--metadata", type = "character", required = TRUE, help = "Path to the metadata file (TSV format)") +parser$add_argument("--output", type = "character", required = TRUE, help = "Path to the output DE results file (TSV format)") +parser$add_argument("--design", type = "character", required = TRUE, help = "Design formula for the model (e.g., '~ 0 + group')") +parser$add_argument("--sample_col", type = "character", default = "sample", help = "Column name for samples in metadata") +parser$add_argument("--group_col", type = "character", default = "group", help = "Column name for groups in metadata") +parser$add_argument("--lfc_threshold", type = "double", default = 0, help = "Log-fold change threshold") +parser$add_argument("--fdr_threshold", type = "double", default = 0.05, help = "FDR threshold") +parser$add_argument("--min_cells", type = "integer", default = 3, help = "Minimum number of cells expressing a gene") +parser$add_argument("--min_samples", type = "integer", default = 2, help = "Minimum number of samples in a group") +parser$add_argument("--n_cores", type = "integer", default = 1, help = "Number of cores to use") + +# Parse arguments +args <- parser$parse_args() + +# Read data +counts <- read.csv(args$counts, sep = "\\t", row.names = 1, check.names = FALSE) +counts_matrix <- as.matrix(counts) +metadata <- read.csv(args$metadata, sep = "\\t", row.names = 1, check.names = FALSE) + +# Ensure metadata rows match counts columns +if (!all(colnames(counts_matrix) %in% rownames(metadata))) { + stop("Not all column names in the counts matrix are present as row names in the metadata.") +} +metadata <- metadata[colnames(counts_matrix), , drop = FALSE] + +# Create SingleCellExperiment object +sce <- SingleCellExperiment(assays = list(counts = counts_matrix), + colData = metadata) + +# Run bulk_de +de_results <- bulk_de( + object = sce, + design = as.formula(args$design), + sample_col = args$sample_col, + group_col = args$group_col, + lfc_threshold = args$lfc_threshold, + fdr_threshold = args$fdr_threshold, + min_cells = args$min_cells, + min_samples = args$min_samples, + n_cores = args$n_cores +) + +# Save results +write.table(de_results, file = args$output, sep = "\\t", row.names = FALSE, quote = FALSE) + +cat("bulk_de analysis completed successfully.\\n") +""" + +R_SCRIPT_BULK_WALK = """ +# Load libraries +suppressPackageStartupMessages(library(argparse)) +suppressPackageStartupMessages(library(bulksignalr)) +suppressPackageStartupMessages(library(SingleCellExperiment)) +suppressPackageStartupMessages(library(Matrix)) + +# Create a parser +parser <- ArgumentParser(description = "Run bulksignalr bulk_walk") + +# Add arguments +parser$add_argument("--counts", type = "character", required = TRUE, help = "Path to the counts matrix file (TSV format)") +parser$add_argument("--metadata", type = "character", required = TRUE, help = "Path to the metadata file (TSV format)") +parser$add_argument("--de_results", type = "character", required = TRUE, help = "Path to the DE results file from bulk_de (TSV format)") +parser$add_argument("--output", type = "character", required = TRUE, help = "Path to the output co-regulation results file (TSV format)") +parser$add_argument("--sample_col", type = "character", default = "sample", help = "Column name for samples in metadata") +parser$add_argument("--group_col", type = "character", default = "group", help = "Column name for groups in metadata") +parser$add_argument("--cor_method", type = "character", choices = c("spearman", "pearson"), default = "spearman", help = "Correlation method") +parser$add_argument("--cor_threshold", type = "double", default = 0.4, help = "Correlation threshold") +parser$add_argument("--n_cores", type = "integer", default = 1, help = "Number of cores to use") + +# Parse arguments +args <- parser$parse_args() + +# Read data +counts <- read.csv(args$counts, sep = "\\t", row.names = 1, check.names = FALSE) +counts_matrix <- as.matrix(counts) +metadata <- read.csv(args$metadata, sep = "\\t", row.names = 1, check.names = FALSE) +de_results <- read.csv(args$de_results, sep = "\\t", check.names = FALSE) + +# Ensure metadata rows match counts columns +if (!all(colnames(counts_matrix) %in% rownames(metadata))) { + stop("Not all column names in the counts matrix are present as row names in the metadata.") +} +metadata <- metadata[colnames(counts_matrix), , drop = FALSE] + +# Create SingleCellExperiment object +sce <- SingleCellExperiment(assays = list(counts = counts_matrix), + colData = metadata) +colData(sce)[[args$sample_col]] <- colData(sce)[[args$sample_col]] +colData(sce)[[args$group_col]] <- colData(sce)[[args$group_col]] + +# Run bulk_walk +walk_results <- bulk_walk( + object = sce, + de_results = de_results, + sample_col = args$sample_col, + group_col = args$group_col, + cor_method = args$cor_method, + cor_threshold = args$cor_threshold, + n_cores = args$n_cores +) + +# Save results +write.table(walk_results, file = args$output, sep = "\\t", row.names = FALSE, quote = FALSE) + +cat("bulk_walk analysis completed successfully.\\n") +""" + +R_SCRIPT_SIGNAL_WALK = """ +# Load libraries +suppressPackageStartupMessages(library(argparse)) +suppressPackageStartupMessages(library(bulksignalr)) +suppressPackageStartupMessages(library(SingleCellExperiment)) +suppressPackageStartupMessages(library(Matrix)) + +# Create a parser +parser <- ArgumentParser(description = "Run bulksignalr signal_walk") + +# Add arguments +parser$add_argument("--counts", type = "character", required = TRUE, help = "Path to the counts matrix file (TSV format)") +parser$add_argument("--metadata", type = "character", required = TRUE, help = "Path to the metadata file (TSV format)") +parser$add_argument("--bulk_walk_results", type = "character", required = TRUE, help = "Path to the bulk_walk results file (TSV format)") +parser$add_argument("--output", type = "character", required = TRUE, help = "Path to the output signaling results file (TSV format)") +parser$add_argument("--sample_col", type = "character", default = "sample", help = "Column name for samples in metadata") +parser$add_argument("--group_col", type = "character", default = "group", help = "Column name for groups in metadata") +parser$add_argument("--lr_db", type = "character", default = NULL, help = "Optional path to a custom ligand-receptor database file (TSV format)") +parser$add_argument("--n_perms", type = "integer", default = 1000, help = "Number of permutations for significance testing") +parser$add_argument("--n_cores", type = "integer", default = 1, help = "Number of cores to use") + +# Parse arguments +args <- parser$parse_args() + +# Read data +counts <- read.csv(args$counts, sep = "\\t", row.names = 1, check.names = FALSE) +counts_matrix <- as.matrix(counts) +metadata <- read.csv(args$metadata, sep = "\\t", row.names = 1, check.names = FALSE) +bulk_walk_results <- read.csv(args$bulk_walk_results, sep = "\\t", check.names = FALSE) + +# Load ligand-receptor database +if (!is.null(args$lr_db)) { + lr_db <- read.csv(args$lr_db, sep = "\\t", check.names = FALSE) +} else { + lr_db <- bulksignalr::lr_db +} + +# Ensure metadata rows match counts columns +if (!all(colnames(counts_matrix) %in% rownames(metadata))) { + stop("Not all column names in the counts matrix are present as row names in the metadata.") +} +metadata <- metadata[colnames(counts_matrix), , drop = FALSE] + +# Create SingleCellExperiment object +sce <- SingleCellExperiment(assays = list(counts = counts_matrix), + colData = metadata) +colData(sce)[[args$sample_col]] <- colData(sce)[[args$sample_col]] +colData(sce)[[args$group_col]] <- colData(sce)[[args$group_col]] + +# Run signal_walk +signal_results <- signal_walk( + object = sce, + bulk_walk_results = bulk_walk_results, + ligand_receptor_db = lr_db, + sample_col = args$sample_col, + group_col = args$group_col, + n_perms = args$n_perms, + n_cores = args$n_cores +) + +# Save results +write.table(signal_results, file = args$output, sep = "\\t", row.names = FALSE, quote = FALSE) + +cat("signal_walk analysis completed successfully.\\n") +""" + +# --- MCP Tools --- + +@mcp.tool() +def bulk_de( + counts_file: Path, + metadata_file: Path, + design: str, + output_file: Path, + sample_col: str = "sample", + group_col: str = "group", + lfc_threshold: float = 0.0, + fdr_threshold: float = 0.05, + min_cells: int = 3, + min_samples: int = 2, + n_cores: int = 1, +): + """ + Performs differential expression analysis using bulksignalr::bulk_de. + + This tool requires an R environment with the 'bulksignalr', 'SingleCellExperiment', + 'Matrix', and 'argparse' packages installed. + + Args: + counts_file: Path to the counts matrix file (TSV format, genes as rows, cells/samples as columns). + metadata_file: Path to the metadata file (TSV format, cells/samples as rows). + design: Design formula for the model (e.g., '~ 0 + group'). + output_file: Path to save the differential expression results (TSV format). + sample_col: Column name for samples in the metadata file. + group_col: Column name for groups in the metadata file. + lfc_threshold: Log-fold change threshold for differential expression. + fdr_threshold: False discovery rate (FDR) threshold. + min_cells: Minimum number of cells a gene must be expressed in to be included. + min_samples: Minimum number of samples required within a group for comparison. + n_cores: Number of CPU cores to use for parallel processing. + """ + # Input validation + if not counts_file.is_file(): + raise FileNotFoundError(f"Counts file not found: {counts_file}") + if not metadata_file.is_file(): + raise FileNotFoundError(f"Metadata file not found: {metadata_file}") + if not design.strip(): + raise ValueError("Design formula cannot be empty.") + if not (0 <= fdr_threshold <= 1): + raise ValueError("fdr_threshold must be between 0 and 1.") + if lfc_threshold < 0: + raise ValueError("lfc_threshold must be non-negative.") + if min_cells < 0: + raise ValueError("min_cells must be non-negative.") + if min_samples < 1: + raise ValueError("min_samples must be at least 1.") + if n_cores < 1: + raise ValueError("n_cores must be at least 1.") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + r_script_path = "" + try: + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R") as r_script_file: + r_script_file.write(R_SCRIPT_BULK_DE) + r_script_path = r_script_file.name + + cmd = [ + "Rscript", r_script_path, + "--counts", str(counts_file), + "--metadata", str(metadata_file), + "--output", str(output_file), + "--design", design, + "--sample_col", sample_col, + "--group_col", group_col, + "--lfc_threshold", str(lfc_threshold), + "--fdr_threshold", str(fdr_threshold), + "--min_cells", str(min_cells), + "--min_samples", str(min_samples), + "--n_cores", str(n_cores), + ] + + process = subprocess.run(cmd, check=True, capture_output=True, text=True) + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_file)], + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"R script execution failed with return code {e.returncode}.\n" + f"Command: {' '.join(e.cmd)}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) from e + finally: + if r_script_path and Path(r_script_path).exists(): + Path(r_script_path).unlink() + + +@mcp.tool() +def bulk_walk( + counts_file: Path, + metadata_file: Path, + de_results_file: Path, + output_file: Path, + sample_col: str = "sample", + group_col: str = "group", + cor_method: str = "spearman", + cor_threshold: float = 0.4, + n_cores: int = 1, +): + """ + Identifies co-regulated gene clusters using bulksignalr::bulk_walk. + + This tool requires an R environment with the 'bulksignalr', 'SingleCellExperiment', + 'Matrix', and 'argparse' packages installed. + + Args: + counts_file: Path to the counts matrix file (TSV format). + metadata_file: Path to the metadata file (TSV format). + de_results_file: Path to the differential expression results file from `bulk_de`. + output_file: Path to save the co-regulation cluster results (TSV format). + sample_col: Column name for samples in the metadata file. + group_col: Column name for groups in the metadata file. + cor_method: Correlation method to use ('spearman' or 'pearson'). + cor_threshold: Correlation threshold for defining co-regulation. + n_cores: Number of CPU cores to use for parallel processing. + """ + # Input validation + if not counts_file.is_file(): + raise FileNotFoundError(f"Counts file not found: {counts_file}") + if not metadata_file.is_file(): + raise FileNotFoundError(f"Metadata file not found: {metadata_file}") + if not de_results_file.is_file(): + raise FileNotFoundError(f"DE results file not found: {de_results_file}") + if cor_method not in ["spearman", "pearson"]: + raise ValueError("cor_method must be either 'spearman' or 'pearson'.") + if not (0 <= cor_threshold <= 1): + raise ValueError("cor_threshold must be between 0 and 1.") + if n_cores < 1: + raise ValueError("n_cores must be at least 1.") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + r_script_path = "" + try: + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R") as r_script_file: + r_script_file.write(R_SCRIPT_BULK_WALK) + r_script_path = r_script_file.name + + cmd = [ + "Rscript", r_script_path, + "--counts", str(counts_file), + "--metadata", str(metadata_file), + "--de_results", str(de_results_file), + "--output", str(output_file), + "--sample_col", sample_col, + "--group_col", group_col, + "--cor_method", cor_method, + "--cor_threshold", str(cor_threshold), + "--n_cores", str(n_cores), + ] + + process = subprocess.run(cmd, check=True, capture_output=True, text=True) + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_file)], + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"R script execution failed with return code {e.returncode}.\n" + f"Command: {' '.join(e.cmd)}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) from e + finally: + if r_script_path and Path(r_script_path).exists(): + Path(r_script_path).unlink() + + +@mcp.tool() +def signal_walk( + counts_file: Path, + metadata_file: Path, + bulk_walk_results_file: Path, + output_file: Path, + sample_col: str = "sample", + group_col: str = "group", + ligand_receptor_db_file: Optional[Path] = None, + n_perms: int = 1000, + n_cores: int = 1, +): + """ + Identifies potential signaling genes using bulksignalr::signal_walk. + + This tool requires an R environment with the 'bulksignalr', 'SingleCellExperiment', + 'Matrix', and 'argparse' packages installed. + + Args: + counts_file: Path to the counts matrix file (TSV format). + metadata_file: Path to the metadata file (TSV format). + bulk_walk_results_file: Path to the co-regulation results from `bulk_walk`. + output_file: Path to save the signaling analysis results (TSV format). + sample_col: Column name for samples in the metadata file. + group_col: Column name for groups in the metadata file. + ligand_receptor_db_file: Optional path to a custom ligand-receptor database (TSV). + If not provided, the built-in database is used. + n_perms: Number of permutations for significance testing. + n_cores: Number of CPU cores to use for parallel processing. + """ + # Input validation + if not counts_file.is_file(): + raise FileNotFoundError(f"Counts file not found: {counts_file}") + if not metadata_file.is_file(): + raise FileNotFoundError(f"Metadata file not found: {metadata_file}") + if not bulk_walk_results_file.is_file(): + raise FileNotFoundError(f"bulk_walk results file not found: {bulk_walk_results_file}") + if ligand_receptor_db_file and not ligand_receptor_db_file.is_file(): + raise FileNotFoundError(f"Ligand-receptor DB file not found: {ligand_receptor_db_file}") + if n_perms < 1: + raise ValueError("n_perms must be at least 1.") + if n_cores < 1: + raise ValueError("n_cores must be at least 1.") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + r_script_path = "" + try: + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R") as r_script_file: + r_script_file.write(R_SCRIPT_SIGNAL_WALK) + r_script_path = r_script_file.name + + cmd = [ + "Rscript", r_script_path, + "--counts", str(counts_file), + "--metadata", str(metadata_file), + "--bulk_walk_results", str(bulk_walk_results_file), + "--output", str(output_file), + "--sample_col", sample_col, + "--group_col", group_col, + "--n_perms", str(n_perms), + "--n_cores", str(n_cores), + ] + if ligand_receptor_db_file: + cmd.extend(["--lr_db", str(ligand_receptor_db_file)]) + + process = subprocess.run(cmd, check=True, capture_output=True, text=True) + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_file)], + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"R script execution failed with return code {e.returncode}.\n" + f"Command: {' '.join(e.cmd)}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) from e + finally: + if r_script_path and Path(r_script_path).exists(): + Path(r_script_path).unlink() \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bulksignalr/app/bioconductor-bulksignalr_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bulksignalr/app/bioconductor-bulksignalr_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f27f85ad515675717b3609c954d73948760f3c19 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bulksignalr/app/bioconductor-bulksignalr_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-bulksignalr/app/bioconductor-bulksignalr_server.py') +SERVER_NAME = 'biosci_bioconductor_bulksignalr' + + +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-bulksignalr/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bulksignalr/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bulksignalr/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bulksignalr/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bulksignalr/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d72a6246e2b76a0ccf6c71ebb53a4fa56f20c47d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bulksignalr/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-bulksignalr: + build: . + image: mcp-bioconductor-bulksignalr:latest + container_name: mcp-bioconductor-bulksignalr + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-bulksignalr + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bulksignalr/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bulksignalr/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b52b1c33a3dec4f61c346282f61bc93331020d24 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bulksignalr/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-bulksignalr + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bulksignalr/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bulksignalr/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bulksignalr/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cardspa/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cardspa/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..53a99bf8cbf88e922ebdad2fbfe1ce6dd59da719 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cardspa/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-cardspa via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-cardspa -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-cardspa_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-cardspa_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-cardspa_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cardspa/app/bioconductor-cardspa_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cardspa/app/bioconductor-cardspa_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ec297386b892503c618230c6cdedfc3d4062884e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cardspa/app/bioconductor-cardspa_server.py @@ -0,0 +1,181 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Dict, List, Literal, Union + +# This is a placeholder for the MCP framework's decorator. +# The user's environment will provide the actual mcp.tool implementation. +class Mcp: + def tool(self): + def decorator(f): + return f + return decorator +mcp = Mcp() + + +@mcp.tool() +def cardspa( + sce_object: Path, + output_path: Path, + phenotype_col: str, + location_col_1: str = "row", + location_col_2: str = "col", + method: Literal["Giotto", "SpaGCN", "BayesSpace"] = "Giotto", + num_results: int = 10, + num_core: int = 1, + min_cells: int = 10, + min_pairs: int = 10, +) -> Dict[str, Union[str, List[str], int]]: + """ + Performs spatial analysis on single-cell data using the cardspa R package. + + This tool wraps the main `cardspa` function, which can utilize different + backend methods like Giotto, SpaGCN, or BayesSpace to identify significant + co-enrichment of cell types in spatial transcriptomics data. + + Args: + sce_object: Path to the input SingleCellExperiment object in RDS format. + output_path: Path to save the output results object in RDS format. + phenotype_col: The column name in the SCE object's colData that contains cell type annotations. + location_col_1: The column name for the first spatial coordinate (e.g., 'row', 'x'). + location_col_2: The column name for the second spatial coordinate (e.g., 'col', 'y'). + method: The computational method to use for the analysis. + num_results: The number of top co-enriched cell type pairs to return. + num_core: The number of CPU cores to use for parallel processing. + min_cells: The minimum number of cells required for a cell type to be included in the analysis. + min_pairs: The minimum number of interacting pairs for a result to be considered significant. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + In case of an error, it includes an error message and return code. + """ + # --- Input Validation --- + if not sce_object.is_file(): + raise FileNotFoundError(f"Input file not found: {sce_object}") + + if not output_path.parent.is_dir(): + try: + output_path.parent.mkdir(parents=True, exist_ok=True) + except OSError as e: + raise NotADirectoryError( + f"Output directory does not exist and could not be created: {output_path.parent}" + ) from e + + if num_results <= 0: + raise ValueError("num_results must be a positive integer.") + if num_core <= 0: + raise ValueError("num_core must be a positive integer.") + if min_cells <= 0: + raise ValueError("min_cells must be a positive integer.") + if min_pairs <= 0: + raise ValueError("min_pairs must be a positive integer.") + + # R script to be executed. It includes package installation for portability. + r_script_content = """ + # run_cardspa.R + options(warn=-1) + suppressPackageStartupMessages({ + if (!requireNamespace("argparser", quietly = TRUE)) { + install.packages("argparser", repos = "http://cran.us.r-project.org", quiet = TRUE) + } + if (!requireNamespace("BiocManager", quietly = TRUE)) { + install.packages("BiocManager", repos = "http://cran.us.r-project.org", quiet = TRUE) + } + if (!requireNamespace("cardspa", quietly = TRUE)) { + BiocManager::install("cardspa", update=FALSE, ask=FALSE, quiet = TRUE) + } + if (!requireNamespace("SingleCellExperiment", quietly = TRUE)) { + BiocManager::install("SingleCellExperiment", update=FALSE, ask=FALSE, quiet = TRUE) + } + library(argparser) + library(cardspa) + library(SingleCellExperiment) + }) + + p <- arg_parser("Run cardspa analysis") + p <- add_argument(p, "--sce_object", help="Path to the input SingleCellExperiment RDS file", type="character") + p <- add_argument(p, "--output_path", help="Path to save the output RDS file", type="character") + p <- add_argument(p, "--phenotype_col", help="Column name for cell types", type="character") + p <- add_argument(p, "--location_col_1", help="First column name for spatial coordinates", default="row", type="character") + p <- add_argument(p, "--location_col_2", help="Second column name for spatial coordinates", default="col", type="character") + p <- add_argument(p, "--method", help="Method for spatial analysis (Giotto, SpaGCN, BayesSpace)", default="Giotto", type="character") + p <- add_argument(p, "--num_results", help="Number of top results to return", default=10, type="integer") + p <- add_argument(p, "--num_core", help="Number of cores for parallel processing", default=1, type="integer") + p <- add_argument(p, "--min_cells", help="Minimum number of cells for a cell type", default=10, type="integer") + p <- add_argument(p, "--min_pairs", help="Minimum number of interacting pairs", default=10, type="integer") + + argv <- parse_args(p) + + if (is.na(argv$sce_object) || is.na(argv$output_path) || is.na(argv$phenotype_col)) { + stop("Missing required arguments: --sce_object, --output_path, or --phenotype_col", call. = FALSE) + } + + cat("Reading input SCE object from:", argv$sce_object, "\\n") + sce <- readRDS(argv$sce_object) + + cat("Running cardspa analysis with method:", argv$method, "\\n") + results <- cardspa( + sce_object = sce, + location_col = c(argv$location_col_1, argv$location_col_2), + phenotype_col = argv$phenotype_col, + method = argv$method, + num_results = argv$num_results, + num_core = argv$num_core, + min_cells = argv$min_cells, + min_pairs = argv$min_pairs + ) + + cat("Saving results to:", argv$output_path, "\\n") + saveRDS(results, file = argv$output_path) + cat("cardspa analysis complete. Results saved to:", argv$output_path, "\\n") + """ + + # --- Subprocess Execution --- + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = Path(r_script_file.name) + + cmd = [ + "Rscript", str(r_script_path), + "--sce_object", str(sce_object.resolve()), + "--output_path", str(output_path.resolve()), + "--phenotype_col", phenotype_col, + "--location_col_1", location_col_1, + "--location_col_2", location_col_2, + "--method", method, + "--num_results", str(num_results), + "--num_core", str(num_core), + "--min_cells", str(min_cells), + "--min_pairs", str(min_pairs), + ] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + encoding='utf-8' + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path.resolve())] + } + except FileNotFoundError: + raise RuntimeError("Rscript command not found. Please ensure R is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "cardspa execution failed.", + "return_code": e.returncode, + "output_files": [] + } + finally: + # Ensure temporary script is always removed + if r_script_path.exists(): + r_script_path.unlink() diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cardspa/app/bioconductor-cardspa_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cardspa/app/bioconductor-cardspa_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a55562c398f4635d7bfe3f2efb1225952a6ac076 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cardspa/app/bioconductor-cardspa_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-cardspa/app/bioconductor-cardspa_server.py') +SERVER_NAME = 'biosci_bioconductor_cardspa' + + +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-cardspa/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cardspa/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cardspa/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cardspa/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cardspa/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c97f759a1c64d8bf5d0c061ab68e38a779fc9afd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cardspa/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-cardspa: + build: . + image: mcp-bioconductor-cardspa:latest + container_name: mcp-bioconductor-cardspa + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-cardspa + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cardspa/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cardspa/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7ea224b0da926f170bcd200087a22fdb529c04e4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cardspa/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-cardspa + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cardspa/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cardspa/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cardspa/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-catscradle/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-catscradle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d4d8e2ec0016e59226eb9e474ee2211b6eda3866 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-catscradle/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-catscradle via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-catscradle -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-catscradle_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-catscradle_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-catscradle_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-catscradle/app/bioconductor-catscradle_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-catscradle/app/bioconductor-catscradle_server.py new file mode 100644 index 0000000000000000000000000000000000000000..db34f938ca814762a8dacf40f5d0301f8f7b3a7a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-catscradle/app/bioconductor-catscradle_server.py @@ -0,0 +1,304 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Union +import tempfile + +@mcp.tool() +def catscradle_build_neighborhoods( + input_rds: str, + output_rds: str, + radius: float = 50.0, + cell_type_col: str = "cell_type", + assay: str = "Spatial", + slot: str = "counts", + min_cells: int = 1 +): + """ + Identifies tissue neighborhoods in spatial transcriptomics data and produces a Seurat object + where individual elements are neighborhoods rather than cells. + + Args: + input_rds: Path to the input Seurat or SpatialExperiment object (RDS format). + output_rds: Path where the resulting neighborhood Seurat object will be saved. + radius: The radius (in spatial units) defining the contiguous region surrounding individual cells. + cell_type_col: Metadata column name containing cell type annotations. + assay: Assay to use from the input object. + slot: Slot to use (e.g., counts, data). + min_cells: Minimum number of cells required to define a neighborhood. + """ + input_path = Path(input_rds) + output_path = Path(output_rds) + + if not input_path.exists(): + return {"error": f"Input file not found: {input_rds}"} + + if radius <= 0: + return {"error": "Radius must be a positive float."} + + # R script to perform neighborhood construction + r_code = f""" + library(CatsCradle) + library(Seurat) + library(SpatialExperiment) + + # Load data + input_data <- readRDS("{input_path}") + + # Check if it's SpatialExperiment and convert if necessary + if (inherits(input_data, "SpatialExperiment")) {{ + # CatsCradle handles SE/SPE, but we ensure Seurat compatibility if needed + # Internal CatsCradle functions typically take these objects + }} + + # Core CatsCradle logic for neighborhood construction + # Based on package description: "produces Seurat objects whose individual elements are neighborhoods" + # We use the primary constructor function (inferred from documentation) + neighborhood_obj <- CatsCradle::spatialToNeighborhoods( + object = input_data, + radius = {radius}, + cell_type_col = "{cell_type_col}", + assay = "{assay}", + slot = "{slot}", + min_cells = {min_cells} + ) + + saveRDS(neighborhood_obj, "{output_path}") + """ + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_code) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": " ".join(e.cmd) + } + finally: + if 'tmp_path' in locals() and Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def catscradle_gene_centric_analysis( + input_rds: str, + output_rds: str, + assay: str = "RNA", + slot: str = "data", + variable_features_only: bool = True, + n_features: int = 2000 +): + """ + Enables the categorisation and annotation of genes by producing Seurat objects + whose elements are genes rather than cells. + + Args: + input_rds: Path to the input Seurat object (RDS format). + output_rds: Path where the gene-centric Seurat object will be saved. + assay: Assay to use for gene expression data. + slot: Slot to use (e.g., data, scale.data). + variable_features_only: Whether to only include highly variable features. + n_features: Number of features to select if variable_features_only is True. + """ + input_path = Path(input_rds) + output_path = Path(output_rds) + + if not input_path.exists(): + return {"error": f"Input file not found: {input_rds}"} + + r_code = f""" + library(CatsCradle) + library(Seurat) + + input_data <- readRDS("{input_path}") + + # Core CatsCradle logic for gene-centric Seurat object creation + gene_obj <- CatsCradle::geneCentricSeurat( + object = input_data, + assay = "{assay}", + slot = "{slot}", + variable_features_only = {"TRUE" if variable_features_only else "FALSE"}, + n_features = {n_features} + ) + + saveRDS(gene_obj, "{output_path}") + """ + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_code) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": " ".join(e.cmd) + } + finally: + if 'tmp_path' in locals() and Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def catscradle_tag_neighborhoods( + neighborhood_rds: str, + output_rds: str, + tag_by: str = "cell_type", + threshold: float = 0.1 +): + """ + Categorizes neighborhoods by the cell types contained in them or the genes expressed in them. + + Args: + neighborhood_rds: Path to the neighborhood Seurat object created by catscradle_build_neighborhoods. + output_rds: Path to save the tagged neighborhood object. + tag_by: Attribute to tag by ('cell_type' or 'gene_expression'). + threshold: Minimum proportion or expression level to consider a tag present in a neighborhood. + """ + input_path = Path(neighborhood_rds) + output_path = Path(output_rds) + + if not input_path.exists(): + return {"error": f"Input file not found: {neighborhood_rds}"} + + r_code = f""" + library(CatsCradle) + library(Seurat) + + nb_obj <- readRDS("{input_path}") + + # Categorize neighborhoods + nb_obj <- CatsCradle::tagNeighborhoods( + object = nb_obj, + tag_by = "{tag_by}", + threshold = {threshold} + ) + + saveRDS(nb_obj, "{output_path}") + """ + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_code) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": " ".join(e.cmd) + } + finally: + if 'tmp_path' in locals() and Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def catscradle_spatial_vignette_pipeline( + input_rds: str, + output_prefix: str, + radius: float = 50.0, + cell_type_col: str = "cell_type" +): + """ + Runs a standard CatsCradle spatial analysis pipeline, including neighborhood construction + and gene clustering, as described in the package vignettes. + + Args: + input_rds: Path to the input spatial transcriptomics RDS file. + output_prefix: Prefix for output files (e.g., 'results/sample1'). + radius: Radius for neighborhood definition. + cell_type_col: Metadata column for cell types. + """ + input_path = Path(input_rds) + out_dir = Path(output_prefix).parent + if not out_dir.exists(): + out_dir.mkdir(parents=True, exist_ok=True) + + r_code = f""" + library(CatsCradle) + library(Seurat) + + # 1. Load Data + spatial_data <- readRDS("{input_path}") + + # 2. Build Neighborhoods + nb_obj <- CatsCradle::spatialToNeighborhoods( + object = spatial_data, + radius = {radius}, + cell_type_col = "{cell_type_col}" + ) + saveRDS(nb_obj, paste0("{output_prefix}", "_neighborhoods.rds")) + + # 3. Gene Centric Analysis + gene_obj <- CatsCradle::geneCentricSeurat(spatial_data) + saveRDS(gene_obj, paste0("{output_prefix}", "_gene_centric.rds")) + + # 4. Discover Gene Clusters (Internal CatsCradle method) + # This typically involves standard Seurat clustering on the gene-centric object + gene_obj <- Seurat::FindVariableFeatures(gene_obj) + gene_obj <- Seurat::ScaleData(gene_obj) + gene_obj <- Seurat::RunPCA(gene_obj) + gene_obj <- Seurat::FindNeighbors(gene_obj) + gene_obj <- Seurat::FindClusters(gene_obj) + saveRDS(gene_obj, paste0("{output_prefix}", "_gene_clusters.rds")) + """ + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_code) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [ + f"{output_prefix}_neighborhoods.rds", + f"{output_prefix}_gene_centric.rds", + f"{output_prefix}_gene_clusters.rds" + ] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": " ".join(e.cmd) + } + finally: + if 'tmp_path' in locals() and Path(tmp_path).exists(): + Path(tmp_path).unlink() \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-catscradle/app/bioconductor-catscradle_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-catscradle/app/bioconductor-catscradle_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..048562c616c70f78bc6328887d0068ca23ef7262 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-catscradle/app/bioconductor-catscradle_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-catscradle/app/bioconductor-catscradle_server.py') +SERVER_NAME = 'biosci_bioconductor_catscradle' + + +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-catscradle/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-catscradle/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-catscradle/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-catscradle/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-catscradle/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d730384b0f7f5e35a4f9c96890d4ba2612be1eaa --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-catscradle/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-catscradle: + build: . + image: mcp-bioconductor-catscradle:latest + container_name: mcp-bioconductor-catscradle + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-catscradle + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-catscradle/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-catscradle/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c46cd1636494f83da0ae619d694ce46850c60680 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-catscradle/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-catscradle + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-catscradle/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-catscradle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-catscradle/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cdi/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cdi/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f03c7ddd953af303b50ef962b89004ab4ab409b6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cdi/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-cdi via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-cdi -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-cdi_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-cdi_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-cdi_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cdi/app/bioconductor-cdi_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cdi/app/bioconductor-cdi_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c11fbb58bd5afc733daf6d2a9676e73f4fb83cce --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cdi/app/bioconductor-cdi_server.py @@ -0,0 +1,355 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Dict, List, Literal, Optional + +# NOTE: The mcp import is commented out as per the instructions, +# but would be required in a real-world MCP environment. +# import mcp + + +@mcp.tool() +def cdi_calculate( + data: Path, + cl: Path, + ncore: int = 1, + stat: Literal["sum", "ks"] = "sum", + output_filename: str = "cdi_results.json", +) -> Dict: + """ + Calculates the Clustering Deviation Index (CDI) from a count matrix and cluster labels. + + This function takes a gene expression matrix (genes as rows, cells as columns) and a + corresponding file of cell cluster assignments to compute the CDI and an associated p-value. + + Args: + data: Path to the input single-cell expression matrix. + Expected format is a CSV/TSV file where rows are genes and columns are cells. + The first column should contain gene names. + cl: Path to a file containing cell cluster labels. + Expected format is a single-column text file with one cluster label per line, + corresponding to the cells in the data matrix. + ncore: Number of cores to use for parallel processing. + stat: The statistic to evaluate the deviation. Can be 'sum' (default) or 'ks'. + output_filename: The name for the output JSON file containing the results. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output JSON file. + """ + # --- Input Validation --- + if not data.is_file(): + raise FileNotFoundError(f"Input data file not found: {data}") + if not cl.is_file(): + raise FileNotFoundError(f"Input cluster labels file not found: {cl}") + if ncore <= 0: + raise ValueError("ncore must be a positive integer.") + + output_path = Path(output_filename) + + r_script_content = f""" + # Load necessary libraries + library(CDI) + library(jsonlite) + + # --- Read Inputs --- + # Assuming data is CSV with a header and gene names in the first column + data_matrix <- as.matrix(read.csv("{data.resolve()}", row.names=1, header=TRUE, check.names=FALSE)) + + # Assuming cl is a single-column text file without a header + cl_vector <- read.table("{cl.resolve()}", header=FALSE)$V1 + + # --- Run CDI Calculation --- + result <- CDI( + data = data_matrix, + cl = cl_vector, + ncore = {ncore}, + stat = "{stat}" + ) + + # --- Save Results --- + # Convert the list to a JSON object and write to file + write_json(result, "{output_path.resolve()}", auto_unbox = TRUE) + """ + + with tempfile.NamedTemporaryFile(mode="w", suffix=".R", delete=False) as tmp_r_script: + tmp_r_script.write(r_script_content) + r_script_path = tmp_r_script.name + + command = ["Rscript", r_script_path] + command_str = " ".join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"results_json": str(output_path.resolve())}, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "CDI execution failed.", + "return_code": e.returncode, + } + finally: + Path(r_script_path).unlink() + + +@mcp.tool() +def cdi_calculate_from_seurat( + seurat_object: Path, + ncore: int = 1, + stat: Literal["sum", "ks"] = "sum", + output_filename: str = "cdi_seurat_results.json", +) -> Dict: + """ + Calculates CDI directly from a Seurat object. + + This function uses a pre-processed Seurat object (saved as an .rds file) to compute + the CDI and an associated p-value. It extracts the count data and cluster + identities directly from the object. + + Args: + seurat_object: Path to the input Seurat object, saved in .rds format. + ncore: Number of cores to use for parallel processing. + stat: The statistic to evaluate the deviation. Can be 'sum' (default) or 'ks'. + output_filename: The name for the output JSON file containing the results. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output JSON file. + """ + # --- Input Validation --- + if not seurat_object.is_file(): + raise FileNotFoundError(f"Input Seurat object file not found: {seurat_object}") + if ncore <= 0: + raise ValueError("ncore must be a positive integer.") + + output_path = Path(output_filename) + + r_script_content = f""" + # Load necessary libraries + library(CDI) + library(Seurat) + library(jsonlite) + + # --- Read Input Object --- + seurat_obj <- readRDS("{seurat_object.resolve()}") + + # --- Run CDI Calculation --- + result <- CDI_seurat( + data = seurat_obj, + ncore = {ncore}, + stat = "{stat}" + ) + + # --- Save Results --- + write_json(result, "{output_path.resolve()}", auto_unbox = TRUE) + """ + + with tempfile.NamedTemporaryFile(mode="w", suffix=".R", delete=False) as tmp_r_script: + tmp_r_script.write(r_script_content) + r_script_path = tmp_r_script.name + + command = ["Rscript", r_script_path] + command_str = " ".join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"results_json": str(output_path.resolve())}, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "CDI Seurat execution failed.", + "return_code": e.returncode, + } + finally: + Path(r_script_path).unlink() + + +@mcp.tool() +def cdi_calculate_from_sce( + sce_object: Path, + ncore: int = 1, + stat: Literal["sum", "ks"] = "sum", + output_filename: str = "cdi_sce_results.json", +) -> Dict: + """ + Calculates CDI directly from a SingleCellExperiment object. + + This function uses a pre-processed SingleCellExperiment object (saved as an .rds file) + to compute the CDI and an associated p-value. + + Args: + sce_object: Path to the input SingleCellExperiment object, saved in .rds format. + ncore: Number of cores to use for parallel processing. + stat: The statistic to evaluate the deviation. Can be 'sum' (default) or 'ks'. + output_filename: The name for the output JSON file containing the results. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output JSON file. + """ + # --- Input Validation --- + if not sce_object.is_file(): + raise FileNotFoundError(f"Input SingleCellExperiment object file not found: {sce_object}") + if ncore <= 0: + raise ValueError("ncore must be a positive integer.") + + output_path = Path(output_filename) + + r_script_content = f""" + # Load necessary libraries + library(CDI) + library(SingleCellExperiment) + library(jsonlite) + + # --- Read Input Object --- + sce_obj <- readRDS("{sce_object.resolve()}") + + # --- Run CDI Calculation --- + result <- CDI_sce( + data = sce_obj, + ncore = {ncore}, + stat = "{stat}" + ) + + # --- Save Results --- + write_json(result, "{output_path.resolve()}", auto_unbox = TRUE) + """ + + with tempfile.NamedTemporaryFile(mode="w", suffix=".R", delete=False) as tmp_r_script: + tmp_r_script.write(r_script_content) + r_script_path = tmp_r_script.name + + command = ["Rscript", r_script_path] + command_str = " ".join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"results_json": str(output_path.resolve())}, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "CDI SingleCellExperiment execution failed.", + "return_code": e.returncode, + } + finally: + Path(r_script_path).unlink() + + +@mcp.tool() +def cdi_plot( + data: Path, + cl: Path, + ncore: int = 1, + stat: Literal["sum", "ks"] = "sum", + output_plot: str = "cdi_plot.pdf", +) -> Dict: + """ + Generates a ggplot object visualizing the CDI calculation. + + This function produces a plot showing the deviation of gene expression within clusters + compared to the expected distribution, which is the basis for the CDI metric. + + Args: + data: Path to the input single-cell expression matrix (genes as rows, cells as columns). + cl: Path to a file containing cell cluster labels. + ncore: Number of cores to use for parallel processing. + stat: The statistic to evaluate the deviation. Can be 'sum' (default) or 'ks'. + output_plot: The filename for the output plot (e.g., 'cdi_plot.pdf', 'cdi_plot.png'). + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output plot file. + """ + # --- Input Validation --- + if not data.is_file(): + raise FileNotFoundError(f"Input data file not found: {data}") + if not cl.is_file(): + raise FileNotFoundError(f"Input cluster labels file not found: {cl}") + if ncore <= 0: + raise ValueError("ncore must be a positive integer.") + + output_path = Path(output_plot) + + r_script_content = f""" + # Load necessary libraries + library(CDI) + library(ggplot2) + + # --- Read Inputs --- + data_matrix <- as.matrix(read.csv("{data.resolve()}", row.names=1, header=TRUE, check.names=FALSE)) + cl_vector <- read.table("{cl.resolve()}", header=FALSE)$V1 + + # --- Generate Plot Object --- + cdi_plot_object <- plot_CDI( + data = data_matrix, + cl = cl_vector, + ncore = {ncore}, + stat = "{stat}" + ) + + # --- Save Plot --- + ggsave("{output_path.resolve()}", plot = cdi_plot_object) + """ + + with tempfile.NamedTemporaryFile(mode="w", suffix=".R", delete=False) as tmp_r_script: + tmp_r_script.write(r_script_content) + r_script_path = tmp_r_script.name + + command = ["Rscript", r_script_path] + command_str = " ".join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"plot": str(output_path.resolve())}, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "CDI plot generation failed.", + "return_code": e.returncode, + } + finally: + Path(r_script_path).unlink() \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cdi/app/bioconductor-cdi_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cdi/app/bioconductor-cdi_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..eaf89793326869c5fb6766794683f3d0363bee5b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cdi/app/bioconductor-cdi_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-cdi/app/bioconductor-cdi_server.py') +SERVER_NAME = 'biosci_bioconductor_cdi' + + +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-cdi/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cdi/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cdi/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cdi/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cdi/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f5159743db8d68c1c4d6f5cb619166901051f302 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cdi/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-cdi: + build: . + image: mcp-bioconductor-cdi:latest + container_name: mcp-bioconductor-cdi + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-cdi + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cdi/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cdi/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bb7ddb0b1e2b0d28305e544ca5c6bd0398dae9b8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cdi/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-cdi + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cdi/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cdi/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cdi/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellhashr/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellhashr/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..15b333b3d4fcf707b628791bbe0019901a9b4213 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellhashr/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-cellhashr via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-cellhashr -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-cellhashr_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-cellhashr_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-cellhashr_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellhashr/app/bioconductor-cellhashr_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellhashr/app/bioconductor-cellhashr_server.py new file mode 100644 index 0000000000000000000000000000000000000000..781674eb4e04f33f9c31aa56e5fba2e6ce45d75e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellhashr/app/bioconductor-cellhashr_server.py @@ -0,0 +1,448 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# @mcp.tool() +def process_count_matrix( + raw_count_data: Path, + output_rds_path: Path, + min_count_per_cell: int = 5, + barcode_whitelist: Optional[List[str]] = None, +): + """ + Parses CITE-seq-Count output and filters cells by total counts. + + This function wraps the cellhashR::ProcessCountMatrix function. It reads a raw + count matrix (typically from CITE-seq-Count), filters out cells with fewer + than min_count_per_cell reads, and saves the resulting data object as an + RDS file for use in downstream cellhashR functions. + + Args: + raw_count_data: Path to the raw count data directory (e.g., 'myCountDir/umi_count'). + output_rds_path: Path to save the output R data object (.rds file). + min_count_per_cell: The minimum total hashing counts for a cell to be retained. + barcode_whitelist: An optional list of HTO barcodes to include. If provided, + all other barcodes will be discarded. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path + to the output RDS file. + """ + if not raw_count_data.is_dir(): + raise FileNotFoundError(f"Input directory not found: {raw_count_data}") + if min_count_per_cell < 0: + raise ValueError("min_count_per_cell must be a non-negative integer.") + + r_script_parts = [ + "library(cellhashR)", + f"barcodeData <- ProcessCountMatrix(rawCountData = '{raw_count_data.resolve()}', minCountPerCell = {min_count_per_cell}", + ] + + if barcode_whitelist: + r_vector = 'c(' + ', '.join(f'"{b}"' for b in barcode_whitelist) + ')' + r_script_parts.append(f", barcodeWhitelist = {r_vector}") + + r_script_parts.append(")") + r_script_parts.append(f"saveRDS(barcodeData, file = '{output_rds_path.resolve()}')") + + r_script = "\n".join(r_script_parts) + command = ["Rscript", "-"] + + try: + with tempfile.NamedTemporaryFile(mode='w', delete=True, suffix=".R") as r_script_file: + r_script_file.write(r_script) + r_script_file.flush() + + # The command is Rscript + # We use input= to pass the script content via stdin + process = subprocess.run( + command, + input=r_script, + text=True, + capture_output=True, + check=True + ) + + return { + "command_executed": f"Rscript <<< '{r_script}'", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_rds_path.resolve())] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript <<< '{r_script}'", + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } + +# @mcp.tool() +def plot_normalization_qc( + barcode_data_rds: Path, + output_plot_path: Path, +): + """ + Generates QC plots for barcode normalization from a cellhashR data object. + + This function wraps cellhashR::PlotNormalizationQC. It reads an RDS file + generated by process_count_matrix and creates a set of QC plots, saving + them to a specified file (e.g., PDF or PNG). + + Args: + barcode_data_rds: Path to the input RDS file from process_count_matrix. + output_plot_path: Path to save the output plot file (e.g., 'qc_plot.pdf'). + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path + to the output plot file. + """ + if not barcode_data_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {barcode_data_rds}") + + r_script = f""" + library(cellhashR) + library(ggplot2) + barcodeData <- readRDS('{barcode_data_rds.resolve()}') + p <- PlotNormalizationQC(barcodeData) + ggsave('{output_plot_path.resolve()}', plot = p, width = 10, height = 8) + """ + command = ["Rscript", "-"] + + try: + process = subprocess.run( + command, + input=r_script, + text=True, + capture_output=True, + check=True + ) + + return { + "command_executed": f"Rscript <<< '{r_script}'", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_plot_path.resolve())] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript <<< '{r_script}'", + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } + +# @mcp.tool() +def generate_cell_hashing_calls( + barcode_matrix_rds: Path, + output_calls_path: Path, + methods: Optional[List[str]] = None, + raw_feature_matrix_h5: Optional[Path] = None, + methods_for_consensus: Optional[List[str]] = None, + majority_consensus_threshold: Optional[float] = None, + caller_disagreement_threshold: Optional[float] = None, +): + """ + Generates cell hashing calls using one or more demultiplexing algorithms. + + This function wraps cellhashR::GenerateCellHashingCalls. It runs various + demultiplexing methods and produces a unified table with the results of + each caller and a consensus call. + + Args: + barcode_matrix_rds: Path to the input RDS file from process_count_matrix. + output_calls_path: Path to save the output calls as a TSV file. + methods: A list of demultiplexing algorithms to run. Available methods include: + 'bff_raw', 'bff_cluster', 'gmm_demux', 'demuxem', 'demuxmix', + 'multiseq', 'htodemux', 'hasheddrops'. + Defaults to ['bff_cluster', 'htodemux']. + raw_feature_matrix_h5: Path to the 10x h5 gene expression counts file. + Required if using 'demuxem' or 'demuxmix'. + methods_for_consensus: A subset of 'methods' to use for the consensus call. + If None, all methods are used. + majority_consensus_threshold: If not None, a call is made if the fraction of + callers agreeing on the top call exceeds this value. + caller_disagreement_threshold: If provided, any caller with a disagreement rate + above this threshold will be dropped and the + consensus re-calculated. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path + to the output calls file. + """ + if not barcode_matrix_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {barcode_matrix_rds}") + + if methods is None: + methods = ['bff_cluster', 'htodemux'] + + demux_methods_req_h5 = {'demuxem', 'demuxmix'} + if any(m in demux_methods_req_h5 for m in methods): + if raw_feature_matrix_h5 is None: + raise ValueError("raw_feature_matrix_h5 is required for 'demuxem' or 'demuxmix' methods.") + if not raw_feature_matrix_h5.is_file(): + raise FileNotFoundError(f"H5 file not found: {raw_feature_matrix_h5}") + + r_methods_vector = 'c(' + ', '.join(f'"{m}"' for m in methods) + ')' + + r_script_parts = [ + "library(cellhashR)", + f"barcodeMatrix <- readRDS('{barcode_matrix_rds.resolve()}')", + f"calls <- GenerateCellHashingCalls(barcodeMatrix = barcodeMatrix, methods = {r_methods_vector}", + ] + + if raw_feature_matrix_h5: + r_script_parts.append(f", rawFeatureMatrixH5 = '{raw_feature_matrix_h5.resolve()}'") + if methods_for_consensus: + r_consensus_vector = 'c(' + ', '.join(f'"{m}"' for m in methods_for_consensus) + ')' + r_script_parts.append(f", methodsForConsensus = {r_consensus_vector}") + if majority_consensus_threshold is not None: + r_script_parts.append(f", majorityConsensusThreshold = {majority_consensus_threshold}") + if caller_disagreement_threshold is not None: + r_script_parts.append(f", callerDisagreementThreshold = {caller_disagreement_threshold}") + + r_script_parts.append(")") + r_script_parts.append(f"write.table(calls, file = '{output_calls_path.resolve()}', sep = '\\t', quote = FALSE, row.names = FALSE)") + + r_script = "\n".join(r_script_parts) + command = ["Rscript", "-"] + + try: + process = subprocess.run( + command, + input=r_script, + text=True, + capture_output=True, + check=True + ) + + return { + "command_executed": f"Rscript <<< '{r_script}'", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_calls_path.resolve())] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript <<< '{r_script}'", + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } + +# @mcp.tool() +def summarize_cells_by_classification( + calls_file: Path, + barcode_matrix_rds: Path, + output_summary_path: Path, +): + """ + Generates a text summary of cell classifications. + + This function wraps cellhashR::SummarizeCellsByClassification. It reads the + calls file and the original barcode matrix to produce a summary, which is + saved to a text file. + + Args: + calls_file: Path to the TSV file of cell hashing calls from generate_cell_hashing_calls. + barcode_matrix_rds: Path to the input RDS file from process_count_matrix. + output_summary_path: Path to save the output summary text file. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path + to the output summary file. + """ + if not calls_file.is_file(): + raise FileNotFoundError(f"Calls file not found: {calls_file}") + if not barcode_matrix_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {barcode_matrix_rds}") + + r_script = f""" + library(cellhashR) + calls <- read.table('{calls_file.resolve()}', header = TRUE, sep = '\\t', check.names = FALSE) + barcodeMatrix <- readRDS('{barcode_matrix_rds.resolve()}') + summary_output <- capture.output(SummarizeCellsByClassification(calls = calls, barcodeMatrix = barcodeMatrix)) + writeLines(summary_output, '{output_summary_path.resolve()}') + """ + command = ["Rscript", "-"] + + try: + process = subprocess.run( + command, + input=r_script, + text=True, + capture_output=True, + check=True + ) + + return { + "command_executed": f"Rscript <<< '{r_script}'", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_summary_path.resolve())] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript <<< '{r_script}'", + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } + +# @mcp.tool() +def get_example_markdown( + output_rmd_path: Path, +): + """ + Exports a template RMarkdown file outlining the default cellhashR workflow. + + This function wraps cellhashR::GetExampleMarkdown. The resulting Rmd file can be + run interactively or headlessly as part of a pipeline. + + Args: + output_rmd_path: The destination path for the template RMarkdown file. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path + to the output Rmd file. + """ + r_script = f""" + library(cellhashR) + GetExampleMarkdown(dest = '{output_rmd_path.resolve()}') + """ + command = ["Rscript", "-"] + + try: + process = subprocess.run( + command, + input=r_script, + text=True, + capture_output=True, + check=True + ) + + return { + "command_executed": f"Rscript <<< '{r_script}'", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_rmd_path.resolve())] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript <<< '{r_script}'", + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } + +# @mcp.tool() +def call_and_generate_report( + raw_count_data: Path, + report_file: Path, + call_file: Path, + title: Optional[str] = None, + barcode_whitelist: Optional[List[str]] = None, + min_count_per_cell: int = 5, + methods: Optional[List[str]] = None, + raw_feature_matrix_h5: Optional[Path] = None, + methods_for_consensus: Optional[List[str]] = None, + majority_consensus_threshold: Optional[float] = None, + caller_disagreement_threshold: Optional[float] = None, +): + """ + Runs the complete cellhashR workflow and generates an HTML QC report. + + This function is a high-level wrapper around the entire cellhashR pipeline, + producing a TSV of calls and a comprehensive HTML report. It combines the + functionality of several other tools into a single step. + + Args: + raw_count_data: Path to the raw count data directory. + report_file: Path to save the output HTML report. + call_file: Path to save the output calls TSV file. + title: An optional title for the report. + barcode_whitelist: An optional list of HTO barcodes to include. + min_count_per_cell: The minimum total hashing counts for a cell to be retained. + methods: A list of demultiplexing algorithms to run. Defaults to + ['bff_cluster', 'htodemux', 'multiseq']. + raw_feature_matrix_h5: Path to the 10x h5 gene expression counts file. + Required if using 'demuxem' or 'demuxmix'. + methods_for_consensus: A subset of 'methods' to use for the consensus call. + majority_consensus_threshold: Threshold for making a consensus call. + caller_disagreement_threshold: Threshold for dropping a discordant caller. + + Returns: + A dictionary containing the command executed, stdout, stderr, and paths + to the output report and call files. + """ + if not raw_count_data.is_dir(): + raise FileNotFoundError(f"Input directory not found: {raw_count_data}") + if min_count_per_cell < 0: + raise ValueError("min_count_per_cell must be a non-negative integer.") + + if methods is None: + methods = ['bff_cluster', 'htodemux', 'multiseq'] + + demux_methods_req_h5 = {'demuxem', 'demuxmix'} + if any(m in demux_methods_req_h5 for m in methods): + if raw_feature_matrix_h5 is None: + raise ValueError("raw_feature_matrix_h5 is required for 'demuxem' or 'demuxmix' methods.") + if not raw_feature_matrix_h5.is_file(): + raise FileNotFoundError(f"H5 file not found: {raw_feature_matrix_h5}") + + r_script_parts = [ + "library(cellhashR)", + f"CallAndGenerateReport(rawCountData = '{raw_count_data.resolve()}', reportFile = '{report_file.resolve()}', callFile = '{call_file.resolve()}', minCountPerCell = {min_count_per_cell}", + ] + + if title: + r_script_parts.append(f", title = '{title}'") + if barcode_whitelist: + r_vector = 'c(' + ', '.join(f'"{b}"' for b in barcode_whitelist) + ')' + r_script_parts.append(f", barcodeWhitelist = {r_vector}") + if methods: + r_vector = 'c(' + ', '.join(f'"{m}"' for m in methods) + ')' + r_script_parts.append(f", methods = {r_vector}") + if raw_feature_matrix_h5: + r_script_parts.append(f", rawFeatureMatrixH5 = '{raw_feature_matrix_h5.resolve()}'") + if methods_for_consensus: + r_vector = 'c(' + ', '.join(f'"{m}"' for m in methods_for_consensus) + ')' + r_script_parts.append(f", methodsForConsensus = {r_vector}") + if majority_consensus_threshold is not None: + r_script_parts.append(f", majorityConsensusThreshold = {majority_consensus_threshold}") + if caller_disagreement_threshold is not None: + r_script_parts.append(f", callerDisagreementThreshold = {caller_disagreement_threshold}") + + r_script_parts.append(")") + r_script = "\n".join(r_script_parts) + command = ["Rscript", "-"] + + try: + process = subprocess.run( + command, + input=r_script, + text=True, + capture_output=True, + check=True + ) + + return { + "command_executed": f"Rscript <<< '{r_script}'", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(report_file.resolve()), str(call_file.resolve())] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript <<< '{r_script}'", + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellhashr/app/bioconductor-cellhashr_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellhashr/app/bioconductor-cellhashr_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6fbf1775b6fb0efdc294f32750529a5c8ba77587 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellhashr/app/bioconductor-cellhashr_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-cellhashr/app/bioconductor-cellhashr_server.py') +SERVER_NAME = 'biosci_bioconductor_cellhashr' + + +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-cellhashr/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellhashr/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellhashr/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellhashr/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellhashr/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..4335d28fb1a12f3432c47924b84445f09056434f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellhashr/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-cellhashr: + build: . + image: mcp-bioconductor-cellhashr:latest + container_name: mcp-bioconductor-cellhashr + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-cellhashr + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellhashr/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellhashr/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7c3f7d013f8e45029b854456545426302952c694 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellhashr/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-cellhashr + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellhashr/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellhashr/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellhashr/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellid/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellid/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fe989065a06a14a78840560dd420a1b13cad37f1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellid/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-cellid via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-cellid -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-cellid_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-cellid_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-cellid_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellid/app/bioconductor-cellid_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellid/app/bioconductor-cellid_server.py new file mode 100644 index 0000000000000000000000000000000000000000..120fd7c15988b989d30c90681a9c25200604244a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellid/app/bioconductor-cellid_server.py @@ -0,0 +1,280 @@ +import subprocess +import os +from pathlib import Path +from typing import Optional, List, Union +import tempfile + +def run_r_command(script_content: str): + """Helper function to execute R code via Rscript""" + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(script_content) + tmp_path = tmp.name + + try: + result = subprocess.run( + ["Rscript", tmp_path], + capture_output=True, + text=True, + check=True + ) + return result.stdout, result.stderr + except subprocess.CalledProcessError as e: + raise RuntimeError(f"R execution failed: {e.stderr}\nStdout: {e.stdout}") + finally: + if os.path.exists(tmp_path): + os.remove(tmp_path) + +@mcp.tool() +def cellid_run_mca( + input_rds: str, + output_rds: str, + nmcs: int = 50, + assay: str = "RNA", + slot: str = "counts", + features: Optional[List[str]] = None +): + """ + Performs Multiple Correspondence Analysis (MCA) on a SingleCellExperiment or Seurat object. + MCA allows for the simultaneous representation of cells and genes in a common low-dimensional space. + """ + input_path = Path(input_rds) + output_path = Path(output_rds) + + if not input_path.exists(): + return {"error": f"Input file {input_rds} not found."} + + if nmcs <= 0: + return {"error": "nmcs must be a positive integer."} + + features_r = "NULL" + if features: + features_formatted = ", ".join([f"'{f}'" for f in features]) + features_r = f"c({features_formatted})" + + r_script = f""" + library(CelliD) + library(Seurat) + library(SingleCellExperiment) + + obj <- readRDS("{input_path}") + + # Run MCA + obj <- RunMCA(obj, nmcs = {nmcs}, assay = "{assay}", slot = "{slot}", features = {features_r}) + + saveRDS(obj, "{output_path}") + """ + + try: + stdout, stderr = run_r_command(r_script) + return { + "command_executed": "RunMCA", + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_path)] + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def cellid_get_cell_gene_set( + input_rds: str, + output_csv: str, + dims: int = 50, + n_features: int = 200 +): + """ + Extracts the top gene signatures for each individual cell based on MCA coordinates. + """ + input_path = Path(input_rds) + output_path = Path(output_csv) + + if not input_path.exists(): + return {"error": f"Input file {input_rds} not found."} + + if dims <= 0 or n_features <= 0: + return {"error": "dims and n_features must be positive integers."} + + r_script = f""" + library(CelliD) + library(Seurat) + library(SingleCellExperiment) + library(data.table) + + obj <- readRDS("{input_path}") + + # Extract gene sets per cell + # dims is treated as 1:dims + gene_sets <- GetCellGeneSet(obj, dims = 1:{dims}, n.features = {n_features}) + + # Convert list to a data table for export + # Each column is a cell, rows are top genes + max_len <- max(sapply(gene_sets, length)) + dt <- as.data.frame(lapply(gene_sets, function(x) c(x, rep(NA, max_len - length(x))))) + + write.csv(dt, "{output_path}", row.names = FALSE) + """ + + try: + stdout, stderr = run_r_command(r_script) + return { + "command_executed": "GetCellGeneSet", + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_path)] + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def cellid_run_cell_hgt( + input_rds: str, + pathways_gmt: str, + output_rds: str, + dims: int = 50, + n_features: int = 200, + min_size: int = 5 +): + """ + Performs cell-type assignment or functional enrichment using a Hypergeometric Test (HGT). + Matches per-cell gene signatures against a reference database (GMT format). + """ + input_path = Path(input_rds) + gmt_path = Path(pathways_gmt) + output_path = Path(output_rds) + + if not input_path.exists(): + return {"error": f"Input RDS {input_rds} not found."} + if not gmt_path.exists(): + return {"error": f"GMT file {pathways_gmt} not found."} + + r_script = f""" + library(CelliD) + library(Seurat) + library(SingleCellExperiment) + library(fgsea) + + obj <- readRDS("{input_path}") + pathways <- gmtPathways("{gmt_path}") + + # Run Hypergeometric Test + # Returns a matrix of -log10(p-value) + hgt_matrix <- RunCellHGT(obj, pathways = pathways, dims = 1:{dims}, n.features = {n_features}, minSize = {min_size}) + + # If Seurat, we can add it as an assay or metadata + if(inherits(obj, "Seurat")) {{ + obj[["HGT"]] <- CreateAssayObject(counts = hgt_matrix) + }} else {{ + # For SCE, add to altExp + altExp(obj, "HGT") <- SummarizedExperiment(assays = list(counts = hgt_matrix)) + }} + + saveRDS(obj, "{output_path}") + """ + + try: + stdout, stderr = run_r_command(r_script) + return { + "command_executed": "RunCellHGT", + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_path)] + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def cellid_run_gsea( + input_rds: str, + pathways_gmt: str, + output_rds: str, + dims: int = 50 +): + """ + Performs Gene Set Enrichment Analysis (GSEA) on cells using the MCA gene rankings. + """ + input_path = Path(input_rds) + gmt_path = Path(pathways_gmt) + output_path = Path(output_rds) + + if not input_path.exists(): + return {"error": f"Input RDS {input_rds} not found."} + if not gmt_path.exists(): + return {"error": f"GMT file {pathways_gmt} not found."} + + r_script = f""" + library(CelliD) + library(Seurat) + library(SingleCellExperiment) + library(fgsea) + + obj <- readRDS("{input_path}") + pathways <- gmtPathways("{gmt_path}") + + # Run GSEA + # This calculates enrichment scores for each cell and each pathway + gsea_res <- RunGSEA(obj, pathways = pathways, dims = 1:{dims}) + + # Save results (usually returns a matrix of NES) + if(inherits(obj, "Seurat")) {{ + obj[["GSEA"]] <- CreateAssayObject(counts = gsea_res) + }} else {{ + altExp(obj, "GSEA") <- SummarizedExperiment(assays = list(counts = gsea_res)) + }} + + saveRDS(obj, "{output_path}") + """ + + try: + stdout, stderr = run_r_command(r_script) + return { + "command_executed": "RunGSEA", + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_path)] + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def cellid_run_group_mca( + input_rds: str, + group_by: str, + output_rds: str, + nmcs: int = 50, + assay: str = "RNA", + slot: str = "counts" +): + """ + Performs MCA on grouped cells (e.g., by cluster or cell type) rather than individual cells. + Useful for extracting group-specific gene signatures. + """ + input_path = Path(input_rds) + output_path = Path(output_rds) + + if not input_path.exists(): + return {"error": f"Input file {input_rds} not found."} + + r_script = f""" + library(CelliD) + library(Seurat) + library(SingleCellExperiment) + + obj <- readRDS("{input_path}") + + # Run Group MCA + # This aggregates cells by the specified metadata column before MCA + group_mca <- RunGroupMCA(obj, group.by = "{group_by}", nmcs = {nmcs}, assay = "{assay}", slot = "{slot}") + + saveRDS(group_mca, "{output_path}") + """ + + try: + stdout, stderr = run_r_command(r_script) + return { + "command_executed": "RunGroupMCA", + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_path)] + } + except Exception as e: + return {"error": str(e)} \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellid/app/bioconductor-cellid_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellid/app/bioconductor-cellid_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..85aa4f4e18ee53ac062287a5f718e0ec276ea561 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellid/app/bioconductor-cellid_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-cellid/app/bioconductor-cellid_server.py') +SERVER_NAME = 'biosci_bioconductor_cellid' + + +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-cellid/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellid/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..1314ea956fa156847970266461a3cfd9e0b3637f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellid/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-cellid: + build: . + image: mcp-bioconductor-cellid:latest + container_name: mcp-bioconductor-cellid + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-cellid + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellid/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellid/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f08c7d868e99c3a997a959a96e68214878543b56 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellid/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-cellid + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellid/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellid/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellid/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellmigration/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellmigration/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..993aab057245ddc0d90f7ad4bfda9cc195b99040 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellmigration/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-cellmigration via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-cellmigration -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-cellmigration_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-cellmigration_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-cellmigration_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellmigration/app/bioconductor-cellmigration_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellmigration/app/bioconductor-cellmigration_server.py new file mode 100644 index 0000000000000000000000000000000000000000..50a3013c0cf7a29a9f9e8af0e0e05aa6b0efc0b4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellmigration/app/bioconductor-cellmigration_server.py @@ -0,0 +1,206 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided by the MCP framework. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +@mcp.tool() +def run_cellmigration_analysis( + input_file: Path, + output_dir: Path, + delta_t: float = 1.0, + x_microns: float = 1.0, + y_microns: float = 1.0, + plot_format: str = "png", + plot_width: int = 7, + plot_height: int = 7, + plot_dpi: int = 300, + generate_displacement_plot: bool = True, + generate_speed_plot: bool = True, + generate_rose_plot: bool = True, + generate_angle_plot: bool = True, + generate_straighness_plot: bool = True, + generate_persistence_ratio_plot: bool = True, + generate_displacement_ratio_plot: bool = True, + generate_persistence_plot: bool = True, + generate_cumulative_plot: bool = True, + generate_cumulative_hist_plot: bool = True, + generate_single_cell_plot: bool = True, + generate_all_cells_plot: bool = True, +) -> Dict[str, Any]: + """ + Performs a complete cell migration analysis using the Bioconductor cellmigration package. + + This tool reads ImageJ trajectory data, performs a comprehensive analysis, + and generates a variety of plots and a summary statistics CSV file. + It requires R and the 'cellmigration' Bioconductor package to be installed. + + Args: + input_file: Path to the input data file from ImageJ's manual tracking plugin. + output_dir: Path to the directory where output files will be saved. + delta_t: Time interval between frames (dt). + x_microns: Pixel to micron conversion factor for the x-axis (x.scale). + y_microns: Pixel to micron conversion factor for the y-axis (y.scale). + plot_format: The format for the output plots ('png' or 'pdf'). + plot_width: Width of the plots in inches. + plot_height: Height of the plots in inches. + plot_dpi: Resolution for PNG plots in dots per inch. + generate_displacement_plot: Generate a displacement plot. + generate_speed_plot: Generate a speed plot. + generate_rose_plot: Generate a rose plot of cell turning angles. + generate_angle_plot: Generate a plot of cell turning angles. + generate_straighness_plot: Generate a plot of cell trajectory straightness. + generate_persistence_ratio_plot: Generate a persistence ratio plot. + generate_displacement_ratio_plot: Generate a displacement ratio plot. + generate_persistence_plot: Generate a persistence time plot. + generate_cumulative_plot: Generate a cumulative plot. + generate_cumulative_hist_plot: Generate a cumulative plot with a histogram. + generate_single_cell_plot: Generate a plot for each single cell trajectory. + generate_all_cells_plot: Generate a plot showing all cell trajectories. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + if delta_t <= 0: + raise ValueError("delta_t must be a positive number.") + if x_microns <= 0 or y_microns <= 0: + raise ValueError("x_microns and y_microns must be positive numbers.") + if plot_format not in ["png", "pdf"]: + raise ValueError("plot_format must be either 'png' or 'pdf'.") + if plot_width <= 0 or plot_height <= 0 or plot_dpi <= 0: + raise ValueError("Plot dimensions and DPI must be positive integers.") + + # --- File Path Handling --- + try: + output_dir.mkdir(parents=True, exist_ok=True) + except OSError as e: + raise OSError(f"Could not create output directory: {output_dir}. Error: {e}") + + # --- R Script Generation --- + # Using absolute paths to avoid issues with working directories + abs_input_file = input_file.resolve() + abs_output_dir = output_dir.resolve() + + # Helper function to generate R plotting code + def get_plot_code(plot_name: str, plot_function: str) -> str: + return f""" + cat("Generating {plot_name} plot...\\n") + if (plot_format == "png") {{ + png(file.path("{abs_output_dir}", "{plot_name}.png"), width=plot_width, height=plot_height, units="in", res=plot_dpi) + }} else {{ + pdf(file.path("{abs_output_dir}", "{plot_name}.pdf"), width=plot_width, height=plot_height) + }} + {plot_function}(analysis_results) + dev.off() + """ + + r_script_content = f""" + # Load the library, with error handling + if (!requireNamespace("cellmigration", quietly = TRUE)) {{ + stop("The 'cellmigration' package is not installed. Please install it from Bioconductor.", call. = FALSE) + }} + library(cellmigration) + + # --- Parameters --- + inputFile <- "{abs_input_file}" + outputDir <- "{abs_output_dir}" + dt <- {delta_t} + x_scale <- {x_microns} + y_scale <- {y_microns} + plot_format <- "{plot_format}" + plot_width <- {plot_width} + plot_height <- {plot_height} + plot_dpi <- {plot_dpi} + + # --- Main Analysis --- + cat("Reading ImageJ data from:", inputFile, "\\n") + ij_data <- read.ijdata(inputFile, dt=dt, x.scale=x_scale, y.scale=y_scale) + + cat("Analyzing trajectories...\\n") + analysis_results <- analyze.trajectories(ij_data) + + cat("Saving analysis summary...\\n") + write.csv(analysis_results$results, file=file.path(outputDir, "analysis_summary.csv"), row.names = FALSE) + + # --- Plotting --- + if ({str(generate_displacement_plot).upper()}) {{{get_plot_code('displacement', 'plot.displacement')}}} + if ({str(generate_speed_plot).upper()}) {{{get_plot_code('speed', 'plot.speed')}}} + if ({str(generate_rose_plot).upper()}) {{{get_plot_code('rose', 'plot.rose')}}} + if ({str(generate_angle_plot).upper()}) {{{get_plot_code('angle', 'plot.angle')}}} + if ({str(generate_straighness_plot).upper()}) {{{get_plot_code('straighness', 'plot.straighness')}}} + if ({str(generate_persistence_ratio_plot).upper()}) {{{get_plot_code('persistence_ratio', 'plot.persistence.ratio')}}} + if ({str(generate_displacement_ratio_plot).upper()}) {{{get_plot_code('displacement_ratio', 'plot.displacement.ratio')}}} + if ({str(generate_persistence_plot).upper()}) {{{get_plot_code('persistence', 'plot.persistence')}}} + if ({str(generate_cumulative_plot).upper()}) {{{get_plot_code('cumulative', 'plot.cummulative.plot')}}} + if ({str(generate_cumulative_hist_plot).upper()}) {{{get_plot_code('cumulative_hist', 'plot.cummulative.plot.and.hist')}}} + if ({str(generate_single_cell_plot).upper()}) {{{get_plot_code('single_cell', 'plot.single.cell')}}} + if ({str(generate_all_cells_plot).upper()}) {{{get_plot_code('all_cells', 'plot.all.cells')}}} + + cat("Analysis complete.\\n") + """ + + # --- Subprocess Execution --- + command = [] + stdout_str, stderr_str = "", "" + output_files = [] + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = r_script_file.name + + command = ["Rscript", r_script_path] + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + stdout_str = process.stdout + stderr_str = process.stderr + + # Collect output files + output_files = [str(p) for p in abs_output_dir.glob('*')] + + except FileNotFoundError: + stderr_str = "Error: 'Rscript' command not found. Please ensure R is installed and in your system's PATH." + return { + "command_executed": " ".join(command), + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": [] + } + except subprocess.CalledProcessError as e: + stderr_str = f"Error executing R script. Return code: {e.returncode}\n" + stderr_str += f"STDOUT:\n{e.stdout}\n" + stderr_str += f"STDERR:\n{e.stderr}\n" + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": stderr_str, + "output_files": [] + } + finally: + # Clean up the temporary R script + if 'r_script_path' in locals() and Path(r_script_path).exists(): + Path(r_script_path).unlink() + + # --- Structured Result Return --- + return { + "command_executed": " ".join(command), + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": output_files + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellmigration/app/bioconductor-cellmigration_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellmigration/app/bioconductor-cellmigration_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9b9eeb2dae5d8342a59d432bbfe6eadc197d1360 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellmigration/app/bioconductor-cellmigration_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-cellmigration/app/bioconductor-cellmigration_server.py') +SERVER_NAME = 'biosci_bioconductor_cellmigration' + + +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-cellmigration/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellmigration/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellmigration/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellmigration/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellmigration/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7f4acd6d9e372f1235703cd470b334ec2d42b41a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellmigration/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-cellmigration: + build: . + image: mcp-bioconductor-cellmigration:latest + container_name: mcp-bioconductor-cellmigration + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-cellmigration + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellmigration/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellmigration/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..68005d17f772be1b4e208089f2d55879ebadc3d0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellmigration/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-cellmigration + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellmigration/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellmigration/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cellmigration/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterfoldsimilarity/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterfoldsimilarity/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c965ca0990e7554e9ff5d7271b78850a73b387f8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterfoldsimilarity/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-clusterfoldsimilarity via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-clusterfoldsimilarity -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-clusterfoldsimilarity_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-clusterfoldsimilarity_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-clusterfoldsimilarity_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterfoldsimilarity/app/bioconductor-clusterfoldsimilarity_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterfoldsimilarity/app/bioconductor-clusterfoldsimilarity_server.py new file mode 100644 index 0000000000000000000000000000000000000000..dfdff77611a00b9e3610924b9301136d29c6c7e4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterfoldsimilarity/app/bioconductor-clusterfoldsimilarity_server.py @@ -0,0 +1,182 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, Dict, Any, List + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided by the MCP framework. +def mcp_tool_placeholder(*args, **kwargs): + def decorator(func): + return func + return decorator + +mcp = type('mcp', (), {'tool': mcp_tool_placeholder}) + +@mcp.tool() +def cluster_fold_similarity( + fold_changes_file: Path, + sample_col: str, + cluster_col: str, + log_fc_col: str, + gene_col: str, + output_matrix_file: str = "similarity_matrix.csv", + n_top: int = 50, + top_by: str = "p_val_adj", + p_val_adj_cutoff: float = 0.05, + log_fc_cutoff: float = 0.25, + num_cores: Optional[int] = None, +) -> Dict[str, Any]: + """ + Calculates a similarity matrix between single-cell clusters from different samples + based on the fold changes of shared features. + + This tool wraps the `clusterFoldSimilarity` function from the R/Bioconductor package + ClusterFoldSimilarity. It takes a table of pre-computed fold changes as input. + + Args: + fold_changes_file: Path to the input file containing fold change data. + The file should be a tab-separated (TSV) or comma-separated (CSV) + table with a header. + sample_col: Name of the column that identifies the sample or dataset. + cluster_col: Name of the column that identifies the cluster. + log_fc_col: Name of the column with the log2 fold change values. + gene_col: Name of the column with the gene or feature names. + output_matrix_file: Name for the output CSV file containing the similarity matrix. + Defaults to "similarity_matrix.csv". + n_top: Number of top genes (ranked by `top_by` column) to use for the calculation. + Defaults to 50. + top_by: The column to use for ranking top genes. Defaults to "p_val_adj". + p_val_adj_cutoff: Adjusted p-value cutoff for filtering genes. Defaults to 0.05. + log_fc_cutoff: Log2 fold change cutoff for filtering genes. Defaults to 0.25. + num_cores: Number of cores to use for parallel processing. If not provided, + computation will be run serially. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list + of output file paths. + """ + # --- Input Validation --- + if not fold_changes_file.is_file(): + raise FileNotFoundError(f"Input file not found: {fold_changes_file}") + + if n_top <= 0: + raise ValueError("n_top must be a positive integer.") + + if p_val_adj_cutoff < 0: + raise ValueError("p_val_adj_cutoff must be non-negative.") + + if log_fc_cutoff < 0: + raise ValueError("log_fc_cutoff must be non-negative.") + + if num_cores is not None and num_cores <= 0: + raise ValueError("num_cores must be a positive integer if specified.") + + # --- R Script Generation --- + # Convert Python None to R's NULL for the script + num_cores_r = "NULL" if num_cores is None else str(num_cores) + + r_script_content = f""" + # Load necessary libraries + if (!requireNamespace("ClusterFoldSimilarity", quietly = TRUE)) {{ + stop("Package ClusterFoldSimilarity is not installed.") + }} + if (!requireNamespace("BiocParallel", quietly = TRUE)) {{ + stop("Package BiocParallel is not installed.") + }} + library(ClusterFoldSimilarity) + library(BiocParallel) + + # --- Parameters from Python --- + fold_changes_file <- "{fold_changes_file.resolve()}" + sample_col <- "{sample_col}" + cluster_col <- "{cluster_col}" + log_fc_col <- "{log_fc_col}" + gene_col <- "{gene_col}" + n_top <- {n_top} + top_by <- "{top_by}" + p_val_adj_cutoff <- {p_val_adj_cutoff} + log_fc_cutoff <- {log_fc_cutoff} + num_cores <- {num_cores_r} + output_file <- "{Path(output_matrix_file).resolve()}" + + # --- Main Logic --- + # Set up parallel processing backend + if (!is.null(num_cores) && num_cores > 1) {{ + bpparam <- MulticoreParam(workers = num_cores) + }} else {{ + bpparam <- SerialParam() + }} + + # Read the input data. read.delim is flexible for both CSV and TSV. + # We use tryCatch to handle potential parsing errors. + fold_changes_data <- tryCatch({{ + # First attempt with tab, common for bioinformatics + read.delim(fold_changes_file, sep = "\\t", header = TRUE, stringsAsFactors = FALSE, check.names = FALSE) + }}, error = function(e) {{ + # Fallback to comma if tab fails + read.delim(fold_changes_file, sep = ",", header = TRUE, stringsAsFactors = FALSE, check.names = FALSE) + }}) + + # Run the core function + cat("Calculating cluster fold similarity...\\n") + similarity_matrix <- clusterFoldSimilarity( + scObject = fold_changes_data, + sample_col = sample_col, + cluster_col = cluster_col, + log_FC_col = log_fc_col, + gene_col = gene_col, + n_top = n_top, + top_by = top_by, + p_val_adj_cutoff = p_val_adj_cutoff, + logFC_cutoff = log_fc_cutoff, + BPPARAM = bpparam + ) + + # Save the output matrix to a CSV file + cat(paste("Writing similarity matrix to:", output_file, "\\n")) + write.csv(similarity_matrix, file = output_file, row.names = TRUE, quote = FALSE) + + cat("Analysis complete.\\n") + """ + + # --- Subprocess Execution --- + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_script: + tmp_script.write(r_script_content) + script_path = tmp_script.name + + command = ["Rscript", script_path] + command_executed = " ".join(command) + + try: + result = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + stdout = result.stdout + stderr = result.stderr + except FileNotFoundError: + # This error occurs if 'Rscript' is not in the system's PATH + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + # This error occurs if the R script itself fails + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + "output_files": [], + } + finally: + # Clean up the temporary R script file + Path(script_path).unlink() + + output_files: List[str] = [str(Path(output_matrix_file).resolve())] + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterfoldsimilarity/app/bioconductor-clusterfoldsimilarity_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterfoldsimilarity/app/bioconductor-clusterfoldsimilarity_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..44588d24a35cb25a59a3b7b626562ede2408396d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterfoldsimilarity/app/bioconductor-clusterfoldsimilarity_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-clusterfoldsimilarity/app/bioconductor-clusterfoldsimilarity_server.py') +SERVER_NAME = 'biosci_bioconductor_clusterfoldsimilarity' + + +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-clusterfoldsimilarity/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterfoldsimilarity/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterfoldsimilarity/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterfoldsimilarity/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterfoldsimilarity/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b36e4770cf4e0f1bc677e32d925ef1998f2e44fa --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterfoldsimilarity/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-clusterfoldsimilarity: + build: . + image: mcp-bioconductor-clusterfoldsimilarity:latest + container_name: mcp-bioconductor-clusterfoldsimilarity + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-clusterfoldsimilarity + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterfoldsimilarity/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterfoldsimilarity/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4ae34182f783369a158a1f59e460c17c69ec6650 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterfoldsimilarity/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-clusterfoldsimilarity + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterfoldsimilarity/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterfoldsimilarity/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterfoldsimilarity/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterprofiler/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterprofiler/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7d41084c084df555cc75c188a61714a0ec681547 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterprofiler/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-clusterprofiler via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-clusterprofiler -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-clusterprofiler_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-clusterprofiler_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-clusterprofiler_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterprofiler/app/bioconductor-clusterprofiler_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterprofiler/app/bioconductor-clusterprofiler_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2ae885a230f21315ec5a915bed5b4442935fb6a7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterprofiler/app/bioconductor-clusterprofiler_server.py @@ -0,0 +1,504 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Literal + +# Assume mcp is available in the execution environment +# from mcp import tool as mcp_tool +# For standalone execution, we can create a dummy decorator +class mcp: + def tool(func): + return func + +def _run_r_script( + r_script_content: str, + output_prefix: str, + temp_dir: Path, +) -> dict: + """ + Helper function to execute an R script and handle I/O and errors. + + Args: + r_script_content: A string containing the R code to execute. + output_prefix: The prefix for naming output files. + temp_dir: The temporary directory to run the script and store results. + + Returns: + A dictionary containing the results of the execution. + """ + r_script_path = temp_dir / "clusterprofiler_script.R" + r_script_path.write_text(r_script_content) + + cmd = ["Rscript", str(r_script_path)] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + cwd=temp_dir, + ) + + output_files = [ + str(p) for p in temp_dir.glob(f"{Path(output_prefix).name}*") + if p.is_file() + ] + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: Rscript not found. Please ensure R is installed and in your system's PATH.", + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + + +@mcp.tool +def enrich_go( + gene_file: Path, + orgdb: str, + output_prefix: str, + keyType: str = "ENTREZID", + ont: Literal["BP", "MF", "CC", "ALL"] = "BP", + pvalue_cutoff: float = 0.05, + qvalue_cutoff: float = 0.2, + p_adjust_method: Literal["holm", "hochberg", "hommel", "bonferroni", "BH", "BY", "fdr", "none"] = "BH", + universe_file: Optional[Path] = None, + min_gs_size: int = 10, + max_gs_size: int = 500, + readable: bool = False, +) -> dict: + """ + Performs Gene Ontology (GO) over-representation analysis using clusterProfiler::enrichGO. + + Args: + gene_file: Path to a file containing a list of gene IDs, one per line. + orgdb: Name of the organism annotation package (e.g., 'org.Hs.eg.db'). + output_prefix: Prefix for the output files (e.g., 'my_analysis_go'). + keyType: The type of gene IDs in the input file (e.g., 'ENTREZID', 'SYMBOL'). + ont: The GO ontology to test ('BP', 'MF', 'CC', or 'ALL'). + pvalue_cutoff: Cutoff for p-value. + qvalue_cutoff: Cutoff for q-value. + p_adjust_method: Method for p-value adjustment. + universe_file: Optional path to a file containing background/universe gene IDs. + min_gs_size: Minimum size of geneset for testing. + max_gs_size: Maximum size of geneset for testing. + readable: If True, maps gene IDs to gene names. + + Returns: + A dictionary containing execution details and paths to result files. + """ + if not gene_file.is_file(): + raise FileNotFoundError(f"Input gene file not found: {gene_file}") + if universe_file and not universe_file.is_file(): + raise FileNotFoundError(f"Universe file not found: {universe_file}") + if pvalue_cutoff < 0 or pvalue_cutoff > 1: + raise ValueError("pvalue_cutoff must be between 0 and 1.") + if qvalue_cutoff < 0 or qvalue_cutoff > 1: + raise ValueError("qvalue_cutoff must be between 0 and 1.") + + with tempfile.TemporaryDirectory() as temp_dir_str: + temp_dir = Path(temp_dir_str) + output_path_prefix = temp_dir / output_prefix + + universe_r_code = f'universe = readLines("{universe_file.resolve()}"),' if universe_file else "" + + r_script = f""" + # Ensure required packages are installed + if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager") + packages <- c("clusterProfiler", "enrichplot", "ggplot2", "{orgdb}") + for (pkg in packages) {{ + if (!requireNamespace(pkg, quietly = TRUE)) BiocManager::install(pkg, update=FALSE) + }} + + library(clusterProfiler) + library(enrichplot) + library(ggplot2) + library({orgdb}, character.only = TRUE) + + genes <- readLines("{gene_file.resolve()}") + + ego <- enrichGO( + gene = genes, + OrgDb = {orgdb}, + keyType = "{keyType}", + ont = "{ont}", + pvalueCutoff = {pvalue_cutoff}, + pAdjustMethod = "{p_adjust_method}", + {universe_r_code} + qvalueCutoff = {qvalue_cutoff}, + minGSSize = {min_gs_size}, + maxGSSize = {max_gs_size}, + readable = {"TRUE" if readable else "FALSE"} + ) + + if (!is.null(ego) && nrow(as.data.frame(ego)) > 0) {{ + write.csv(as.data.frame(ego), file = "{output_path_prefix}_results.csv", row.names = FALSE) + + p1 <- barplot(ego, showCategory=20) + ggsave("{output_path_prefix}_barplot.png", plot=p1, width=12, height=10) + + p2 <- dotplot(ego, showCategory=20) + ggsave("{output_path_prefix}_dotplot.png", plot=p2, width=12, height=10) + }} else {{ + print("No significant enrichment found.") + file.create("{output_path_prefix}_no_results.txt") + }} + """ + return _run_r_script(r_script, str(output_path_prefix), temp_dir) + + +@mcp.tool +def enrich_kegg( + gene_file: Path, + organism: str, + output_prefix: str, + keyType: str = "kegg", + pvalue_cutoff: float = 0.05, + qvalue_cutoff: float = 0.2, + p_adjust_method: Literal["holm", "hochberg", "hommel", "bonferroni", "BH", "BY", "fdr", "none"] = "BH", + universe_file: Optional[Path] = None, + min_gs_size: int = 10, + max_gs_size: int = 500, +) -> dict: + """ + Performs KEGG pathway over-representation analysis using clusterProfiler::enrichKEGG. + + Args: + gene_file: Path to a file containing a list of gene IDs, one per line. + organism: KEGG organism code (e.g., 'hsa' for human, 'mmu' for mouse). + output_prefix: Prefix for the output files (e.g., 'my_analysis_kegg'). + keyType: The type of gene IDs, 'kegg' is recommended. + pvalue_cutoff: Cutoff for p-value. + qvalue_cutoff: Cutoff for q-value. + p_adjust_method: Method for p-value adjustment. + universe_file: Optional path to a file containing background/universe gene IDs. + min_gs_size: Minimum size of geneset for testing. + max_gs_size: Maximum size of geneset for testing. + + Returns: + A dictionary containing execution details and paths to result files. + """ + if not gene_file.is_file(): + raise FileNotFoundError(f"Input gene file not found: {gene_file}") + if universe_file and not universe_file.is_file(): + raise FileNotFoundError(f"Universe file not found: {universe_file}") + if pvalue_cutoff < 0 or pvalue_cutoff > 1: + raise ValueError("pvalue_cutoff must be between 0 and 1.") + if qvalue_cutoff < 0 or qvalue_cutoff > 1: + raise ValueError("qvalue_cutoff must be between 0 and 1.") + + with tempfile.TemporaryDirectory() as temp_dir_str: + temp_dir = Path(temp_dir_str) + output_path_prefix = temp_dir / output_prefix + + universe_r_code = f'universe = readLines("{universe_file.resolve()}"),' if universe_file else "" + + r_script = f""" + if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager") + packages <- c("clusterProfiler", "enrichplot", "ggplot2") + for (pkg in packages) {{ + if (!requireNamespace(pkg, quietly = TRUE)) BiocManager::install(pkg, update=FALSE) + }} + + library(clusterProfiler) + library(enrichplot) + library(ggplot2) + + genes <- readLines("{gene_file.resolve()}") + + ekegg <- enrichKEGG( + gene = genes, + organism = "{organism}", + keyType = "{keyType}", + pvalueCutoff = {pvalue_cutoff}, + pAdjustMethod = "{p_adjust_method}", + {universe_r_code} + qvalueCutoff = {qvalue_cutoff}, + minGSSize = {min_gs_size}, + maxGSSize = {max_gs_size} + ) + + if (!is.null(ekegg) && nrow(as.data.frame(ekegg)) > 0) {{ + write.csv(as.data.frame(ekegg), file = "{output_path_prefix}_results.csv", row.names = FALSE) + + p1 <- barplot(ekegg, showCategory=20) + ggsave("{output_path_prefix}_barplot.png", plot=p1, width=12, height=10) + + p2 <- dotplot(ekegg, showCategory=20) + ggsave("{output_path_prefix}_dotplot.png", plot=p2, width=12, height=10) + }} else {{ + print("No significant enrichment found.") + file.create("{output_path_prefix}_no_results.txt") + }} + """ + return _run_r_script(r_script, str(output_path_prefix), temp_dir) + + +@mcp.tool +def gse_go( + ranked_gene_file: Path, + orgdb: str, + output_prefix: str, + keyType: str = "ENTREZID", + ont: Literal["BP", "MF", "CC", "ALL"] = "BP", + n_perms: int = 1000, + min_gs_size: int = 10, + max_gs_size: int = 500, + pvalue_cutoff: float = 0.05, + p_adjust_method: Literal["holm", "hochberg", "hommel", "bonferroni", "BH", "BY", "fdr", "none"] = "BH", + verbose: bool = True, + seed: bool = False, +) -> dict: + """ + Performs Gene Set Enrichment Analysis (GSEA) on GO terms using clusterProfiler::gseGO. + + Args: + ranked_gene_file: Path to a 2-column CSV file (no header) with gene ID and a numeric ranking metric (e.g., log2FoldChange). + orgdb: Name of the organism annotation package (e.g., 'org.Hs.eg.db'). + output_prefix: Prefix for the output files (e.g., 'my_gsea_go'). + keyType: The type of gene IDs in the input file. + ont: The GO ontology to test ('BP', 'MF', 'CC', or 'ALL'). + n_perms: Number of permutations for GSEA. + min_gs_size: Minimum size of geneset for testing. + max_gs_size: Maximum size of geneset for testing. + pvalue_cutoff: Cutoff for p-value. + p_adjust_method: Method for p-value adjustment. + verbose: If True, show progress messages. + seed: If True, sets a random seed for reproducibility. + + Returns: + A dictionary containing execution details and paths to result files. + """ + if not ranked_gene_file.is_file(): + raise FileNotFoundError(f"Input gene file not found: {ranked_gene_file}") + + with tempfile.TemporaryDirectory() as temp_dir_str: + temp_dir = Path(temp_dir_str) + output_path_prefix = temp_dir / output_prefix + + r_script = f""" + if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager") + packages <- c("clusterProfiler", "enrichplot", "ggplot2", "DOSE", "{orgdb}") + for (pkg in packages) {{ + if (!requireNamespace(pkg, quietly = TRUE)) BiocManager::install(pkg, update=FALSE) + }} + + library(clusterProfiler) + library(enrichplot) + library(ggplot2) + library({orgdb}, character.only = TRUE) + + df <- read.csv("{ranked_gene_file.resolve()}", header=FALSE) + geneList <- df[,2] + names(geneList) <- as.character(df[,1]) + geneList <- sort(geneList, decreasing = TRUE) + + gse <- gseGO( + geneList = geneList, + OrgDb = {orgdb}, + ont = "{ont}", + keyType = "{keyType}", + nPerm = {n_perms}, + minGSSize = {min_gs_size}, + maxGSSize = {max_gs_size}, + pvalueCutoff = {pvalue_cutoff}, + pAdjustMethod = "{p_adjust_method}", + verbose = {"TRUE" if verbose else "FALSE"}, + seed = {"TRUE" if seed else "FALSE"} + ) + + if (!is.null(gse) && nrow(as.data.frame(gse)) > 0) {{ + write.csv(as.data.frame(gse), file = "{output_path_prefix}_results.csv", row.names = FALSE) + + p1 <- ridgeplot(gse) + ggsave("{output_path_prefix}_ridgeplot.png", plot=p1, width=12, height=10) + + # GSEA plot for top pathways + gseaplot(gse, geneSetID = 1, title = gse$Description[1]) + ggsave("{output_path_prefix}_gseaplot_top1.png", width=10, height=8) + }} else {{ + print("No significant enrichment found.") + file.create("{output_path_prefix}_no_results.txt") + }} + """ + return _run_r_script(r_script, str(output_path_prefix), temp_dir) + + +@mcp.tool +def gse_kegg( + ranked_gene_file: Path, + organism: str, + output_prefix: str, + keyType: str = "kegg", + n_perms: int = 1000, + min_gs_size: int = 10, + max_gs_size: int = 500, + pvalue_cutoff: float = 0.05, + p_adjust_method: Literal["holm", "hochberg", "hommel", "bonferroni", "BH", "BY", "fdr", "none"] = "BH", + verbose: bool = True, +) -> dict: + """ + Performs Gene Set Enrichment Analysis (GSEA) on KEGG pathways using clusterProfiler::gseKEGG. + + Args: + ranked_gene_file: Path to a 2-column CSV file (no header) with gene ID and a numeric ranking metric. + organism: KEGG organism code (e.g., 'hsa' for human). + output_prefix: Prefix for the output files (e.g., 'my_gsea_kegg'). + keyType: The type of gene IDs in the input file. + n_perms: Number of permutations for GSEA. + min_gs_size: Minimum size of geneset for testing. + max_gs_size: Maximum size of geneset for testing. + pvalue_cutoff: Cutoff for p-value. + p_adjust_method: Method for p-value adjustment. + verbose: If True, show progress messages. + + Returns: + A dictionary containing execution details and paths to result files. + """ + if not ranked_gene_file.is_file(): + raise FileNotFoundError(f"Input gene file not found: {ranked_gene_file}") + + with tempfile.TemporaryDirectory() as temp_dir_str: + temp_dir = Path(temp_dir_str) + output_path_prefix = temp_dir / output_prefix + + r_script = f""" + if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager") + packages <- c("clusterProfiler", "enrichplot", "ggplot2", "DOSE") + for (pkg in packages) {{ + if (!requireNamespace(pkg, quietly = TRUE)) BiocManager::install(pkg, update=FALSE) + }} + + library(clusterProfiler) + library(enrichplot) + library(ggplot2) + + df <- read.csv("{ranked_gene_file.resolve()}", header=FALSE) + geneList <- df[,2] + names(geneList) <- as.character(df[,1]) + geneList <- sort(geneList, decreasing = TRUE) + + gsek <- gseKEGG( + geneList = geneList, + organism = "{organism}", + keyType = "{keyType}", + nPerm = {n_perms}, + minGSSize = {min_gs_size}, + maxGSSize = {max_gs_size}, + pvalueCutoff = {pvalue_cutoff}, + pAdjustMethod = "{p_adjust_method}", + verbose = {"TRUE" if verbose else "FALSE"} + ) + + if (!is.null(gsek) && nrow(as.data.frame(gsek)) > 0) {{ + write.csv(as.data.frame(gsek), file = "{output_path_prefix}_results.csv", row.names = FALSE) + + p1 <- ridgeplot(gsek) + ggsave("{output_path_prefix}_ridgeplot.png", plot=p1, width=12, height=10) + }} else {{ + print("No significant enrichment found.") + file.create("{output_path_prefix}_no_results.txt") + }} + """ + return _run_r_script(r_script, str(output_path_prefix), temp_dir) + + +@mcp.tool +def compare_clusters_go( + gene_clusters_file: Path, + orgdb: str, + output_prefix: str, + keyType: str = "ENTREZID", + ont: Literal["BP", "MF", "CC"] = "BP", + pvalue_cutoff: float = 0.05, + qvalue_cutoff: float = 0.2, + p_adjust_method: Literal["holm", "hochberg", "hommel", "bonferroni", "BH", "BY", "fdr", "none"] = "BH", + min_gs_size: int = 10, + max_gs_size: int = 500, + readable: bool = False, +) -> dict: + """ + Compares GO enrichment across multiple gene clusters using clusterProfiler::compareCluster. + + Args: + gene_clusters_file: Path to a 2-column CSV file (no header) with cluster name and gene ID. + orgdb: Name of the organism annotation package (e.g., 'org.Hs.eg.db'). + output_prefix: Prefix for the output files. + keyType: The type of gene IDs in the input file. + ont: The GO ontology to test ('BP', 'MF', or 'CC'). + pvalue_cutoff: Cutoff for p-value. + qvalue_cutoff: Cutoff for q-value. + p_adjust_method: Method for p-value adjustment. + min_gs_size: Minimum size of geneset for testing. + max_gs_size: Maximum size of geneset for testing. + readable: If True, maps gene IDs to gene names. + + Returns: + A dictionary containing execution details and paths to result files. + """ + if not gene_clusters_file.is_file(): + raise FileNotFoundError(f"Input gene clusters file not found: {gene_clusters_file}") + + with tempfile.TemporaryDirectory() as temp_dir_str: + temp_dir = Path(temp_dir_str) + output_path_prefix = temp_dir / output_prefix + + r_script = f""" + if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager") + packages <- c("clusterProfiler", "enrichplot", "ggplot2", "{orgdb}") + for (pkg in packages) {{ + if (!requireNamespace(pkg, quietly = TRUE)) BiocManager::install(pkg, update=FALSE) + }} + + library(clusterProfiler) + library(enrichplot) + library(ggplot2) + library({orgdb}, character.only = TRUE) + + df <- read.csv("{gene_clusters_file.resolve()}", header=FALSE) + colnames(df) <- c("cluster", "gene") + + # Convert dataframe to the named list format required by compareCluster + gene_clusters <- split(df$gene, df$cluster) + + comp_result <- compareCluster( + geneClusters = gene_clusters, + fun = "enrichGO", + OrgDb = {orgdb}, + keyType = "{keyType}", + ont = "{ont}", + pvalueCutoff = {pvalue_cutoff}, + qvalueCutoff = {qvalue_cutoff}, + pAdjustMethod = "{p_adjust_method}", + minGSSize = {min_gs_size}, + maxGSSize = {max_gs_size}, + readable = {"TRUE" if readable else "FALSE"} + ) + + if (!is.null(comp_result) && nrow(as.data.frame(comp_result)) > 0) {{ + write.csv(as.data.frame(comp_result), file = "{output_path_prefix}_results.csv", row.names = FALSE) + + p1 <- dotplot(comp_result, showCategory=15) + theme(axis.text.x = element_text(angle = 45, hjust = 1)) + ggsave("{output_path_prefix}_dotplot.png", plot=p1, width=14, height=12) + }} else {{ + print("No significant enrichment found across clusters.") + file.create("{output_path_prefix}_no_results.txt") + }} + """ + return _run_r_script(r_script, str(output_path_prefix), temp_dir) diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterprofiler/app/bioconductor-clusterprofiler_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterprofiler/app/bioconductor-clusterprofiler_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c6bff28b233e3a2c553cd371b0f4099b341cd94d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterprofiler/app/bioconductor-clusterprofiler_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-clusterprofiler/app/bioconductor-clusterprofiler_server.py') +SERVER_NAME = 'biosci_bioconductor_clusterprofiler' + + +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-clusterprofiler/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterprofiler/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterprofiler/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterprofiler/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterprofiler/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..39aa3d40e374e62eb9e1d8a6d78f7d881fd28827 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterprofiler/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-clusterprofiler: + build: . + image: mcp-bioconductor-clusterprofiler:latest + container_name: mcp-bioconductor-clusterprofiler + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-clusterprofiler + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterprofiler/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterprofiler/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..716938ee6f00676545d461f0de082e3386ecb6a1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterprofiler/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-clusterprofiler + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterprofiler/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterprofiler/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clusterprofiler/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clustsignal/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clustsignal/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6fae5fb2e1686893a0b9d9f0ed3b4cd9fc2d59ae --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clustsignal/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-clustsignal via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-clustsignal -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-clustsignal_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-clustsignal_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-clustsignal_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clustsignal/app/bioconductor-clustsignal_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clustsignal/app/bioconductor-clustsignal_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a199706a53202b8ee1029869aa44559ede4e0440 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clustsignal/app/bioconductor-clustsignal_server.py @@ -0,0 +1,411 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, Dict, Any, List, Union + +# This is a placeholder for the actual MCP decorator. +# In a real MCP environment, this would be `from mcp import tool`. +class mcp: + @staticmethod + def tool(): + def decorator(f): + return f + return decorator + +# R script templates +R_SCRIPT_HEADER = """ +# Install packages if not already present +if (!requireNamespace("optparse", quietly = TRUE)) install.packages("optparse", repos="http://cran.us.r-project.org") +if (!requireNamespace("BiocManager", quietly = TRUE)) install.packages("BiocManager", repos="http://cran.us.r-project.org") +if (!requireNamespace("clustsig", quietly = TRUE)) BiocManager::install("clustsig", update=FALSE, ask=FALSE) + +library(optparse) +library(clustsig) +""" + +R_SCRIPT_SIG_CLUST = R_SCRIPT_HEADER + """ +# Define command-line options +option_list <- list( + make_option(c("-i", "--input"), type="character", default=NULL, help="Input data matrix file (CSV/TSV, rows=samples, cols=features)"), + make_option(c("-o", "--out_prefix"), type="character", default="clustsig_results", help="Output file prefix"), + make_option(c("-k", "--num_clusters"), type="integer", default=NULL, help="Number of clusters (k)"), + make_option(c("--nsim"), type="integer", default=1000, help="Number of simulations"), + make_option(c("--nrep"), type="integer", default=1, help="Number of replicates for each simulation"), + make_option(c("--labflag"), type="integer", default=0, help="Flag for data with known labels (0 or 1)"), + make_option(c("--label_file"), type="character", default=NULL, help="File with integer labels for columns (required if labflag=1)"), + make_option(c("--icovest"), type="integer", default=1, help="Covariance matrix estimation method (1, 2, or 3)"), + make_option(c("--input_sep"), type="character", default="\\t", help="Input file separator ('\\t' or ',')"), + make_option(c("--input_header"), type="logical", default=TRUE, help="Does the input file have a header?") +) + +opt_parser <- OptionParser(option_list=option_list) +opt <- parse_args(opt_parser) + +# Validate required arguments +if (is.null(opt$input) || is.null(opt$num_clusters)) { + print_help(opt_parser) + stop("Input data matrix file and number of clusters must be supplied.", call.=FALSE) +} + +# Read input data +x <- as.matrix(read.table(opt$input, header=opt$input_header, sep=opt$input_sep, row.names=1, check.names=FALSE)) + +# Handle labels +label_data <- 0 +if (opt$labflag == 1) { + if (is.null(opt$label_file)) stop("Label file must be provided when labflag is 1.", call.=FALSE) + label_data <- as.integer(read.table(opt$label_file, header=FALSE)[,1]) + if (length(label_data) != ncol(x)) stop("Number of labels must match the number of columns in the data matrix.", call.=FALSE) +} + +# Run sig.clust +set.seed(123) # for reproducibility +results <- sig.clust(x=x, k=opt$num_clusters, nsim=opt$nsim, nrep=opt$nrep, labflag=opt$labflag, label=label_data, icovest=opt$icovest) + +# Save results +p_value_file <- file.path(dirname(opt$out_prefix), paste0(basename(opt$out_prefix), "_p_value.txt")) +ci_file <- file.path(dirname(opt$out_prefix), paste0(basename(opt$out_prefix), "_cluster_indices.txt")) +ci_sim_file <- file.path(dirname(opt$out_prefix), paste0(basename(opt$out_prefix), "_sim_cluster_indices.csv")) +eigval_orig_file <- file.path(dirname(opt$out_prefix), paste0(basename(opt$out_prefix), "_orig_eigenvalues.txt")) +eigval_sim_file <- file.path(dirname(opt$out_prefix), paste0(basename(opt$out_prefix), "_sim_eigenvalues.csv")) + +write.table(results$p.value, file=p_value_file, col.names=FALSE, row.names=FALSE) +write.table(results$ci, file=ci_file, col.names=FALSE, row.names=FALSE) +write.csv(results$ci.sim, file=ci_sim_file, row.names=FALSE) +write.table(results$eigval.orig, file=eigval_orig_file, col.names=FALSE, row.names=FALSE) +write.csv(results$eigval.sim, file=eigval_sim_file, row.names=FALSE) + +cat("All results saved.\\n") +""" + +R_SCRIPT_RECLUSTER = R_SCRIPT_HEADER + """ +option_list <- list( + make_option(c("-i", "--input"), type="character", default=NULL, help="Input data matrix file"), + make_option(c("-o", "--out_prefix"), type="character", default="recluster_results", help="Output file prefix"), + make_option(c("-k", "--num_clusters"), type="integer", default=NULL, help="Number of clusters (k)"), + make_option(c("--mat"), type="character", default="pearson", help="Distance matrix method"), + make_option(c("--method"), type="character", default="average", help="Clustering method"), + make_option(c("--input_sep"), type="character", default="\\t", help="Input file separator ('\\t' or ',')"), + make_option(c("--input_header"), type="logical", default=TRUE, help="Does the input file have a header?") +) + +opt_parser <- OptionParser(option_list=option_list) +opt <- parse_args(opt_parser) + +if (is.null(opt$input) || is.null(opt$num_clusters)) { + print_help(opt_parser) + stop("Input file and number of clusters must be supplied.", call.=FALSE) +} + +x <- as.matrix(read.table(opt$input, header=opt$input_header, sep=opt$input_sep, row.names=1, check.names=FALSE)) +results <- recluster(x=x, k=opt$num_clusters, mat=opt$mat, method=opt$method) + +ci_file <- file.path(dirname(opt$out_prefix), paste0(basename(opt$out_prefix), "_cluster_indices.txt")) +sh_file <- file.path(dirname(opt$out_prefix), paste0(basename(opt$out_prefix), "_silhouette_width.txt")) + +write.table(results$ci, file=ci_file, col.names=FALSE, row.names=FALSE) +write.table(results$sh, file=sh_file, col.names=FALSE, row.names=FALSE) + +cat("Results saved.\\n") +""" + +R_SCRIPT_SIM_SIG = R_SCRIPT_HEADER + """ +option_list <- list( + make_option(c("-o", "--out_prefix"), type="character", default="sim_sig_data", help="Output file prefix"), + make_option(c("-n", "--num_samples"), type="integer", default=NULL, help="Number of samples (rows)"), + make_option(c("-p", "--num_features"), type="integer", default=NULL, help="Number of features (columns)"), + make_option(c("--p_sig"), type="integer", default=NULL, help="Number of significant features"), + make_option(c("--s_val"), type="double", default=1.0, help="Signal value"), + make_option(c("--v_sig"), type="double", default=1.0, help="Variance of significant features"), + make_option(c("--lab"), type="integer", default=0, help="Flag to return labels (0 or 1)") +) + +opt_parser <- OptionParser(option_list=option_list) +opt <- parse_args(opt_parser) + +if (is.null(opt$num_samples) || is.null(opt$num_features) || is.null(opt$p_sig)) { + print_help(opt_parser) + stop("Number of samples, features, and significant features must be supplied.", call.=FALSE) +} + +set.seed(123) +results <- sim.sig(n=opt$num_samples, p=opt$num_features, p.sig=opt$p_sig, s.val=opt$s_val, v.sig=opt$v_sig, lab=opt$lab) + +matrix_file <- file.path(dirname(opt$out_prefix), paste0(basename(opt$out_prefix), "_matrix.csv")) + +if (opt$lab == 1) { + label_file <- file.path(dirname(opt$out_prefix), paste0(basename(opt$out_prefix), "_labels.txt")) + write.csv(results$x, file=matrix_file, row.names=FALSE) + write.table(results$label, file=label_file, col.names=FALSE, row.names=FALSE) +} else { + write.csv(results, file=matrix_file, row.names=FALSE) +} + +cat("Simulated data saved.\\n") +""" + +R_SCRIPT_SIM_NULL = R_SCRIPT_HEADER + """ +option_list <- list( + make_option(c("-o", "--out_prefix"), type="character", default="sim_null_data", help="Output file prefix"), + make_option(c("-n", "--num_samples"), type="integer", default=NULL, help="Number of samples (rows)"), + make_option(c("-p", "--num_features"), type="integer", default=NULL, help="Number of features (columns)"), + make_option(c("--lab"), type="integer", default=0, help="Flag to return labels (0 or 1)") +) + +opt_parser <- OptionParser(option_list=option_list) +opt <- parse_args(opt_parser) + +if (is.null(opt$num_samples) || is.null(opt$num_features)) { + print_help(opt_parser) + stop("Number of samples and features must be supplied.", call.=FALSE) +} + +set.seed(123) +results <- sim.null(n=opt$num_samples, p=opt$num_features, lab=opt$lab) + +matrix_file <- file.path(dirname(opt$out_prefix), paste0(basename(opt$out_prefix), "_matrix.csv")) + +if (opt$lab == 1) { + label_file <- file.path(dirname(opt$out_prefix), paste0(basename(opt$out_prefix), "_labels.txt")) + write.csv(results$x, file=matrix_file, row.names=FALSE) + write.table(results$label, file=label_file, col.names=FALSE, row.names=FALSE) +} else { + write.csv(results, file=matrix_file, row.names=FALSE) +} + +cat("Simulated data saved.\\n") +""" + +def _run_r_script( + script_content: str, + args: List[str], + output_dir: Path, +) -> Dict[str, Union[str, List[str]]]: + """Helper function to run an R script in a temporary directory.""" + script_path = output_dir / "script.R" + with open(script_path, "w") as f: + f.write(script_content) + + cmd = ["Rscript", str(script_path)] + args + + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + cwd=output_dir, + ) + + output_files = [str(p) for p in output_dir.glob("*") if p.is_file() and p.name != "script.R"] + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode, + } + + +@mcp.tool() +def sig_clust( + input_matrix: Path, + num_clusters: int, + output_prefix: str, + nsim: int = 1000, + nrep: int = 1, + labflag: int = 0, + label_file: Optional[Path] = None, + icovest: int = 1, + input_separator: str = "tab", + input_header: bool = True, +) -> Dict[str, Any]: + """ + Performs Significant Cluster Analysis using the clustsig R package. + + This tool assesses the statistical significance of clustering results on a dataset. + It compares the within-cluster sum of squares of the data to that of simulated null data. + """ + # Input validation + if not input_matrix.is_file(): + raise FileNotFoundError(f"Input file not found: {input_matrix}") + if num_clusters <= 0: + raise ValueError("Number of clusters must be a positive integer.") + if nsim <= 0: + raise ValueError("Number of simulations (nsim) must be a positive integer.") + if nrep <= 0: + raise ValueError("Number of replicates (nrep) must be a positive integer.") + if labflag not in [0, 1]: + raise ValueError("labflag must be 0 or 1.") + if labflag == 1: + if label_file is None: + raise ValueError("label_file is required when labflag is 1.") + if not label_file.is_file(): + raise FileNotFoundError(f"Label file not found: {label_file}") + if icovest not in [1, 2, 3]: + raise ValueError("icovest must be 1, 2, or 3.") + if input_separator not in ["tab", "comma"]: + raise ValueError("input_separator must be 'tab' or 'comma'.") + + sep_map = {"tab": "\\t", "comma": ","} + + with tempfile.TemporaryDirectory() as tempdir: + workdir = Path(tempdir) + + args = [ + "--input", str(input_matrix.resolve()), + "--out_prefix", str(workdir / output_prefix), + "--num_clusters", str(num_clusters), + "--nsim", str(nsim), + "--nrep", str(nrep), + "--labflag", str(labflag), + "--icovest", str(icovest), + "--input_sep", sep_map[input_separator], + ] + if input_header: + args.append("--input_header") + if label_file: + args.extend(["--label_file", str(label_file.resolve())]) + + result = _run_r_script(R_SCRIPT_SIG_CLUST, args, workdir) + + return result + + +@mcp.tool() +def recluster( + input_matrix: Path, + num_clusters: int, + output_prefix: str, + mat: str = "pearson", + method: str = "average", + input_separator: str = "tab", + input_header: bool = True, +) -> Dict[str, Any]: + """ + Performs hierarchical clustering and calculates cluster indices and silhouette widths. + + This is a utility function from the clustsig package for performing clustering. + """ + # Input validation + if not input_matrix.is_file(): + raise FileNotFoundError(f"Input file not found: {input_matrix}") + if num_clusters <= 0: + raise ValueError("Number of clusters must be a positive integer.") + + valid_mats = ["pearson", "spearman", "kendall", "euclidean"] + if mat not in valid_mats: + raise ValueError(f"Invalid distance matrix method '{mat}'. Must be one of {valid_mats}.") + + valid_methods = ["average", "ward", "single", "complete", "mcquitty", "median", "centroid"] + if method not in valid_methods: + raise ValueError(f"Invalid clustering method '{method}'. Must be one of {valid_methods}.") + + if input_separator not in ["tab", "comma"]: + raise ValueError("input_separator must be 'tab' or 'comma'.") + + sep_map = {"tab": "\\t", "comma": ","} + + with tempfile.TemporaryDirectory() as tempdir: + workdir = Path(tempdir) + + args = [ + "--input", str(input_matrix.resolve()), + "--out_prefix", str(workdir / output_prefix), + "--num_clusters", str(num_clusters), + "--mat", mat, + "--method", method, + "--input_sep", sep_map[input_separator], + ] + if input_header: + args.append("--input_header") + + result = _run_r_script(R_SCRIPT_RECLUSTER, args, workdir) + + return result + + +@mcp.tool() +def sim_sig( + num_samples: int, + num_features: int, + p_sig: int, + output_prefix: str, + s_val: float = 1.0, + v_sig: float = 1.0, + lab: int = 0, +) -> Dict[str, Any]: + """ + Generates simulated data from a multivariate normal distribution with a signal. + + This function is useful for creating test datasets with a known cluster structure. + """ + # Input validation + if num_samples <= 0: + raise ValueError("Number of samples must be a positive integer.") + if num_features <= 0: + raise ValueError("Number of features must be a positive integer.") + if not (0 < p_sig <= num_features): + raise ValueError("Number of significant features (p_sig) must be positive and not exceed num_features.") + if lab not in [0, 1]: + raise ValueError("lab must be 0 or 1.") + + with tempfile.TemporaryDirectory() as tempdir: + workdir = Path(tempdir) + + args = [ + "--out_prefix", str(workdir / output_prefix), + "--num_samples", str(num_samples), + "--num_features", str(num_features), + "--p_sig", str(p_sig), + "--s_val", str(s_val), + "--v_sig", str(v_sig), + "--lab", str(lab), + ] + + result = _run_r_script(R_SCRIPT_SIM_SIG, args, workdir) + + return result + + +@mcp.tool() +def sim_null( + num_samples: int, + num_features: int, + output_prefix: str, + lab: int = 0, +) -> Dict[str, Any]: + """ + Generates simulated data from a multivariate normal distribution with no signal (null). + + This function is useful for creating null datasets for comparison or testing. + """ + # Input validation + if num_samples <= 0: + raise ValueError("Number of samples must be a positive integer.") + if num_features <= 0: + raise ValueError("Number of features must be a positive integer.") + if lab not in [0, 1]: + raise ValueError("lab must be 0 or 1.") + + with tempfile.TemporaryDirectory() as tempdir: + workdir = Path(tempdir) + + args = [ + "--out_prefix", str(workdir / output_prefix), + "--num_samples", str(num_samples), + "--num_features", str(num_features), + "--lab", str(lab), + ] + + result = _run_r_script(R_SCRIPT_SIM_NULL, args, workdir) + + return result \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clustsignal/app/bioconductor-clustsignal_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clustsignal/app/bioconductor-clustsignal_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..42fc040ca81d9ccd170bbd60cfb342f471930e82 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clustsignal/app/bioconductor-clustsignal_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-clustsignal/app/bioconductor-clustsignal_server.py') +SERVER_NAME = 'biosci_bioconductor_clustsignal' + + +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-clustsignal/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clustsignal/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clustsignal/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clustsignal/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clustsignal/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..dcf3656fcb1e73c28f2f9f64498f92d8c965e8ef --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clustsignal/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-clustsignal: + build: . + image: mcp-bioconductor-clustsignal:latest + container_name: mcp-bioconductor-clustsignal + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-clustsignal + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clustsignal/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clustsignal/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..895bc594dd965d7a7f30b72fff8b40038ccbd010 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clustsignal/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-clustsignal + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clustsignal/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clustsignal/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-clustsignal/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-complexheatmap/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-complexheatmap/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1e1a9b49fc7ea6267c7df02b1ad96b7d47557d59 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-complexheatmap/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-complexheatmap via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-complexheatmap -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-complexheatmap_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-complexheatmap_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-complexheatmap_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-complexheatmap/app/bioconductor-complexheatmap_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-complexheatmap/app/bioconductor-complexheatmap_server.py new file mode 100644 index 0000000000000000000000000000000000000000..13eb2fc613ca373632e91c88799a7aac944e96a7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-complexheatmap/app/bioconductor-complexheatmap_server.py @@ -0,0 +1,225 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided. +def mcp_tool_decorator_placeholder(*args, **kwargs): + def decorator(func): + return func + return decorator + +mcp = type("mcp", (), {"tool": mcp_tool_decorator_placeholder}) + + +@mcp.tool() +def make_complex_heatmap( + matrix_file: Path, + output_file_prefix: str, + output_format: str = "png", + file_separator: str = "comma", + name: str = "heatmap", + cluster_rows: bool = True, + cluster_columns: bool = True, + show_row_names: bool = True, + show_column_names: bool = True, + row_names_font_size: int = 10, + column_names_font_size: int = 10, + clustering_distance_rows: str = "euclidean", + clustering_distance_columns: str = "euclidean", + clustering_method_rows: str = "complete", + clustering_method_columns: str = "complete", + row_dend_side: str = "left", + column_dend_side: str = "top", + show_heatmap_legend: bool = True, + heatmap_legend_title: Optional[str] = None, + row_title: Optional[str] = None, + column_title: Optional[str] = None, + color_min: str = "blue", + color_mid: str = "white", + color_max: str = "red", + break_min: Optional[float] = None, + break_mid: float = 0.0, + break_max: Optional[float] = None, + na_col: str = "grey", + output_width_in: int = 8, + output_height_in: int = 8, + output_res_dpi: int = 300, +) -> dict: + """ + Generates a complex heatmap using the R package ComplexHeatmap. + + This tool takes a numerical matrix as input and produces a heatmap image. + The input file should be a text file (CSV or TSV) where the first column + contains row names and the first row contains column names. + + Args: + matrix_file: Path to the input data matrix (CSV or TSV). + output_file_prefix: Prefix for the output heatmap file. + output_format: Format of the output image. Valid choices: 'png', 'pdf', 'svg'. + file_separator: Separator used in the matrix file. Valid choices: 'comma', 'tab'. + name: Name of the heatmap, used as the default legend title. + cluster_rows: Whether to perform clustering on rows. + cluster_columns: Whether to perform clustering on columns. + show_row_names: Whether to display row names on the heatmap. + show_column_names: Whether to display column names on the heatmap. + row_names_font_size: Font size for row names. + column_names_font_size: Font size for column names. + clustering_distance_rows: Distance measure for row clustering. + clustering_distance_columns: Distance measure for column clustering. + clustering_method_rows: Method for row clustering. + clustering_method_columns: Method for column clustering. + row_dend_side: Position of the row dendrogram. Valid choices: 'left', 'right'. + column_dend_side: Position of the column dendrogram. Valid choices: 'top', 'bottom'. + show_heatmap_legend: Whether to display the heatmap legend. + heatmap_legend_title: Title for the heatmap legend. Defaults to the 'name' parameter. + row_title: Title for the rows. + column_title: Title for the columns. + color_min: Color for the minimum value in the heatmap. + color_mid: Color for the middle value in the heatmap. + color_max: Color for the maximum value in the heatmap. + break_min: Value corresponding to the minimum color. Defaults to the matrix minimum. + break_mid: Value corresponding to the middle color. + break_max: Value corresponding to the maximum color. Defaults to the matrix maximum. + na_col: Color for NA (missing) values. + output_width_in: Width of the output image in inches. + output_height_in: Height of the output image in inches. + output_res_dpi: Resolution (DPI) for PNG output. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not matrix_file.is_file(): + raise FileNotFoundError(f"Input file not found: {matrix_file}") + + valid_formats = ["png", "pdf", "svg"] + if output_format not in valid_formats: + raise ValueError(f"output_format must be one of {valid_formats}, not '{output_format}'") + + valid_separators = ["comma", "tab"] + if file_separator not in valid_separators: + raise ValueError(f"file_separator must be one of {valid_separators}, not '{file_separator}'") + + valid_row_dend_sides = ["left", "right"] + if row_dend_side not in valid_row_dend_sides: + raise ValueError(f"row_dend_side must be one of {valid_row_dend_sides}, not '{row_dend_side}'") + + valid_col_dend_sides = ["top", "bottom"] + if column_dend_side not in valid_col_dend_sides: + raise ValueError(f"column_dend_side must be one of {valid_col_dend_sides}, not '{column_dend_side}'") + + if output_width_in <= 0 or output_height_in <= 0 or output_res_dpi <= 0: + raise ValueError("Output dimensions and resolution must be positive.") + + # --- R Script Generation --- + output_file = Path(f"{output_file_prefix}.{output_format}") + + sep = "," if file_separator == "comma" else "\\t" + + r_script_lines = [ + "library(ComplexHeatmap)", + "library(circlize)", + "", + f'mat <- as.matrix(read.csv("{matrix_file}", row.names=1, header=TRUE, sep="{sep}"))', + "", + "# Define color mapping function", + "mat_min <- min(mat, na.rm = TRUE)", + "mat_max <- max(mat, na.rm = TRUE)", + ] + + break_min_r = str(break_min) if break_min is not None else "mat_min" + break_max_r = str(break_max) if break_max is not None else "mat_max" + + r_script_lines.append( + f'col_fun = colorRamp2(c({break_min_r}, {break_mid}, {break_max_r}), c("{color_min}", "{color_mid}", "{color_max}"))' + ) + + r_script_lines.append("") + r_script_lines.append("# Open graphics device") + if output_format == "png": + r_script_lines.append(f'png("{output_file}", width={output_width_in}, height={output_height_in}, units="in", res={output_res_dpi})') + elif output_format == "pdf": + r_script_lines.append(f'pdf("{output_file}", width={output_width_in}, height={output_height_in})') + elif output_format == "svg": + r_script_lines.append(f'svg("{output_file}", width={output_width_in}, height={output_height_in})') + + # Build Heatmap function arguments + ht_params = [ + "mat", + f'name = "{name}"', + "col = col_fun", + f'na_col = "{na_col}"', + f"cluster_rows = {str(cluster_rows).upper()}", + f"cluster_columns = {str(cluster_columns).upper()}", + f"show_row_names = {str(show_row_names).upper()}", + f"show_column_names = {str(show_column_names).upper()}", + f'row_names_gp = gpar(fontsize = {row_names_font_size})', + f'column_names_gp = gpar(fontsize = {column_names_font_size})', + f'clustering_distance_rows = "{clustering_distance_rows}"', + f'clustering_distance_columns = "{clustering_distance_columns}"', + f'clustering_method_rows = "{clustering_method_rows}"', + f'clustering_method_columns = "{clustering_method_columns}"', + f'row_dend_side = "{row_dend_side}"', + f'column_dend_side = "{column_dend_side}"', + f"show_heatmap_legend = {str(show_heatmap_legend).upper()}", + ] + + if row_title: + ht_params.append(f'row_title = "{row_title}"') + if column_title: + ht_params.append(f'column_title = "{column_title}"') + if heatmap_legend_title: + ht_params.append(f'heatmap_legend_param = list(title = "{heatmap_legend_title}")') + + r_script_lines.append("") + r_script_lines.append("# Create and draw the heatmap") + r_script_lines.append(f"ht = Heatmap({', '.join(ht_params)})") + r_script_lines.append("draw(ht)") + r_script_lines.append("") + r_script_lines.append("# Close the graphics device") + r_script_lines.append("dev.off()") + + r_script = "\n".join(r_script_lines) + + # --- Subprocess Execution --- + command_executed = "" + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_script: + tmp_script.write(r_script) + script_path = tmp_script.name + + command = ["Rscript", script_path] + command_executed = " ".join(command) + + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + # Provide more context in case of an R error + error_message = ( + f"R script execution failed with exit code {e.returncode}.\n" + f"Command: {command_executed}\n" + f"R Script Content:\n---\n{r_script}\n---\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) + raise RuntimeError(error_message) from e + finally: + # Clean up the temporary script file + if 'script_path' in locals() and Path(script_path).exists(): + Path(script_path).unlink() + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file)] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-complexheatmap/app/bioconductor-complexheatmap_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-complexheatmap/app/bioconductor-complexheatmap_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6ea4a427925b30f7a44aa5d1b1c3dd2589f37a20 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-complexheatmap/app/bioconductor-complexheatmap_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-complexheatmap/app/bioconductor-complexheatmap_server.py') +SERVER_NAME = 'biosci_bioconductor_complexheatmap' + + +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-complexheatmap/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-complexheatmap/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-complexheatmap/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-complexheatmap/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-complexheatmap/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..abf545b662467e8085f4cce746121deafc82b593 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-complexheatmap/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-complexheatmap: + build: . + image: mcp-bioconductor-complexheatmap:latest + container_name: mcp-bioconductor-complexheatmap + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-complexheatmap + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-complexheatmap/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-complexheatmap/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0081bc8f415129604bd28e7791cccea6de50469e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-complexheatmap/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-complexheatmap + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-complexheatmap/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-complexheatmap/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-complexheatmap/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-concordexr/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-concordexr/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1c6ea7c8b91b141d18da6d241b21b2fe2e0440a8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-concordexr/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-concordexr via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-concordexr -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-concordexr_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-concordexr_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-concordexr_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-concordexr/app/bioconductor-concordexr_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-concordexr/app/bioconductor-concordexr_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e1b553e9f10a96a65b53696eea39809bdc611b61 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-concordexr/app/bioconductor-concordexr_server.py @@ -0,0 +1,221 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# Mock the decorator for standalone execution +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def compute_concordex( + data_file: Path, + ranks_file: Path, + indices_file: Path, + output_dir: Path, + data_type: str = "counts", + abundance_min: float = 1.0, + abundance_max: Optional[float] = None, + sample_min: float = 0.0, + sample_max: Optional[float] = None, + filter_perc: float = 0.0, + filter_count: int = 0, + plot: bool = True, + plot_format: str = "png", + plot_width: int = 10, + plot_height: int = 10, + export: bool = True, + export_rds: bool = True, +): + """ + Computes the Concordance Index (Concordex) using the concordexR package. + + This tool wraps the `computeConcordex` function. It takes expression/count data, + pre-computed ranks, and sample indices to calculate concordex scores. It can + filter data, generate plots, and export results to files. + + Args: + data_file: Path to the input data file (e.g., counts matrix). Assumed to be a tab-separated file with a header and row names in the first column. + ranks_file: Path to the ranks file. Assumed to be a tab-separated file with a header and row names in the first column. + indices_file: Path to the indices file. Assumed to be a single-column, tab-separated file without a header. + output_dir: Path to the directory where output files will be saved. + data_type: The type of data in `data_file`. Must be either 'counts' or 'ranks'. + abundance_min: The minimum abundance of a feature to be included in the analysis. + abundance_max: The maximum abundance of a feature. If None, no upper limit is applied. + sample_min: The minimum value of a sample to be included. + sample_max: The maximum value of a sample. If None, no upper limit is applied. + filter_perc: The percentage of samples a feature must be present in to be retained. Value must be between 0.0 and 1.0. + filter_count: The minimum number of counts a feature must have across all samples to be retained. + plot: If True, generate concordex plots. + plot_format: The format for the output plots (e.g., 'png', 'pdf', 'svg'). + plot_width: The width of the output plots in inches. + plot_height: The height of the output plots in inches. + export: If True, export the concordex results to text files. + export_rds: If True, save the final concordex R object to an .rds file for later use (e.g., with plot_concordex). + """ + # Input validation + if not data_file.is_file(): + raise FileNotFoundError(f"Input data file not found: {data_file}") + if not ranks_file.is_file(): + raise FileNotFoundError(f"Ranks file not found: {ranks_file}") + if not indices_file.is_file(): + raise FileNotFoundError(f"Indices file not found: {indices_file}") + + if data_type not in ["counts", "ranks"]: + raise ValueError("data_type must be either 'counts' or 'ranks'.") + if not (0.0 <= filter_perc <= 1.0): + raise ValueError("filter_perc must be between 0.0 and 1.0.") + if filter_count < 0: + raise ValueError("filter_count must be a non-negative integer.") + if plot_format not in ["png", "pdf", "svg", "jpeg", "tiff"]: + raise ValueError(f"Unsupported plot format: {plot_format}") + + output_dir.mkdir(parents=True, exist_ok=True) + + # Build the R script + r_script_lines = [ + "library(concordexR)", + f'data <- read.table("{data_file.resolve()}", header=TRUE, sep="\\t", row.names=1, check.names=FALSE)', + f'ranks <- read.table("{ranks_file.resolve()}", header=TRUE, sep="\\t", row.names=1, check.names=FALSE)', + f'indices_df <- read.table("{indices_file.resolve()}", header=FALSE, sep="\\t")', + "indices <- as.list(indices_df$V1)", + "concordex_result <- computeConcordex(", + " data = data,", + " ranks = ranks,", + " indices = indices,", + f' type = "{data_type}",', + f" abundance.min = {abundance_min},", + f" abundance.max = {abundance_max if abundance_max is not None else 'Inf'},", + f" sample.min = {sample_min},", + f" sample.max = {sample_max if sample_max is not None else 'Inf'},", + f" filter.perc = {filter_perc},", + f" filter.count = {filter_count},", + f' output.dir = "{output_dir.resolve()}",', + f" plot = {'TRUE' if plot else 'FALSE'},", + f' plot.format = "{plot_format}",', + f" plot.width = {plot_width},", + f" plot.height = {plot_height},", + f" export = {'TRUE' if export else 'FALSE'}", + ")", + ] + + if export_rds: + rds_path = output_dir.resolve() / "concordex_object.rds" + r_script_lines.append(f'saveRDS(concordex_result, file = "{rds_path}")') + + r_script = "\n".join(r_script_lines) + + # Use a temporary file for the R script + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as f: + f.write(r_script) + r_script_path = Path(f.name) + + cmd = ["Rscript", str(r_script_path)] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + output_files = [str(p) for p in output_dir.glob("**/*") if p.is_file()] + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"R script execution failed with return code {e.returncode}.\n" + f"Command: {command_executed}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) from e + finally: + r_script_path.unlink() + +@mcp.tool +def plot_concordex( + concordex_object_file: Path, + output_dir: Path, + plot_format: str = "png", + plot_width: int = 10, + plot_height: int = 10, +): + """ + Generates plots from a pre-computed concordex object. + + This tool wraps the `plotConcordex` function from the concordexR package. + It takes an .rds file containing a concordex object (generated by the + compute_concordex tool) and creates visualization plots. + + Args: + concordex_object_file: Path to the .rds file containing the concordex object. + output_dir: Path to the directory where output plots will be saved. + plot_format: The format for the output plots (e.g., 'png', 'pdf', 'svg'). + plot_width: The width of the output plots in inches. + plot_height: The height of the output plots in inches. + """ + # Input validation + if not concordex_object_file.is_file(): + raise FileNotFoundError(f"Concordex object file not found: {concordex_object_file}") + if concordex_object_file.suffix != ".rds": + raise ValueError("concordex_object_file must be an .rds file.") + if plot_format not in ["png", "pdf", "svg", "jpeg", "tiff"]: + raise ValueError(f"Unsupported plot format: {plot_format}") + + output_dir.mkdir(parents=True, exist_ok=True) + + # Build the R script + r_script_lines = [ + "library(concordexR)", + f'concordex_obj <- readRDS("{concordex_object_file.resolve()}")', + "plotConcordex(", + " concordex.object = concordex_obj,", + f' output.dir = "{output_dir.resolve()}",', + f' plot.format = "{plot_format}",', + f" plot.width = {plot_width},", + f" plot.height = {plot_height}", + ")", + ] + r_script = "\n".join(r_script_lines) + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as f: + f.write(r_script) + r_script_path = Path(f.name) + + cmd = ["Rscript", str(r_script_path)] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + output_files = [str(p) for p in output_dir.glob("**/*") if p.is_file()] + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"R script execution failed with return code {e.returncode}.\n" + f"Command: {command_executed}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) from e + finally: + r_script_path.unlink() \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-concordexr/app/bioconductor-concordexr_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-concordexr/app/bioconductor-concordexr_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1d2aeba621510072cfb8af0fb3c0a1462ea348f7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-concordexr/app/bioconductor-concordexr_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-concordexr/app/bioconductor-concordexr_server.py') +SERVER_NAME = 'biosci_bioconductor_concordexr' + + +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-concordexr/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-concordexr/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-concordexr/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-concordexr/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-concordexr/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..8b5291f8e0b390b106dfec8b76ba69c2afb93482 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-concordexr/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-concordexr: + build: . + image: mcp-bioconductor-concordexr:latest + container_name: mcp-bioconductor-concordexr + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-concordexr + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-concordexr/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-concordexr/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bb7159d75e2835693c1a0bd67e14b3e286680365 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-concordexr/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-concordexr + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-concordexr/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-concordexr/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-concordexr/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cotan/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cotan/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6b14e58239c11775ee3f73d0f681b3b3ddf905b8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cotan/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-cotan via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-cotan -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-cotan_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-cotan_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-cotan_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cotan/app/bioconductor-cotan_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cotan/app/bioconductor-cotan_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fff61195e76d7223b6423248202059f92ff91d47 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cotan/app/bioconductor-cotan_server.py @@ -0,0 +1,208 @@ +import subprocess +import tempfile +import textwrap +from pathlib import Path +from typing import List, Optional, Dict, Any + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided by the MCP framework. +class mcp: + @staticmethod + def tool(func): + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + return wrapper + +@mcp.tool +def run_cotan_analysis( + raw_count_matrix: Path, + output_dir: Path, + min_reads_per_cell: int = 1000, + min_cells_per_gene: int = 3, + num_cores: int = 1, + run_gdi: bool = True, + run_clustering: bool = True, + num_clusters: int = 10, + save_cotan_object: bool = True, +) -> Dict[str, Any]: + """ + Performs a complete COTAN analysis for single-cell gene co-expression. + + This tool takes a raw UMI count matrix and runs the standard COTAN workflow, + which includes data cleaning, dispersion estimation, co-expression calculation, + Global Differentiation Index (GDI) analysis, and hierarchical clustering of genes. + + Args: + raw_count_matrix: Path to the input raw count matrix file (CSV format). + Rows should represent genes and columns represent cells. + The first column should contain gene names. + output_dir: Path to the directory where output files will be saved. + min_reads_per_cell: Minimum number of reads for a cell to be kept during cleaning. + min_cells_per_gene: Minimum number of cells where a gene must be expressed to be kept. + num_cores: Number of CPU cores to use for parallelizable steps. + run_gdi: If True, calculates the Global Differentiation Index (GDI) for all genes. + run_clustering: If True, performs hierarchical clustering on the gene co-expression matrix. + num_clusters: The number of clusters to create if `run_clustering` is True. + save_cotan_object: If True, saves the final COTAN R object as an RDS file for further analysis. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a list of output file paths. + """ + # --- Input Validation --- + if not raw_count_matrix.is_file(): + raise FileNotFoundError(f"Input file not found: {raw_count_matrix}") + if min_reads_per_cell <= 0: + raise ValueError("min_reads_per_cell must be a positive integer.") + if min_cells_per_gene <= 0: + raise ValueError("min_cells_per_gene must be a positive integer.") + if num_cores <= 0: + raise ValueError("num_cores must be a positive integer.") + if run_clustering and num_clusters <= 1: + raise ValueError("num_clusters must be greater than 1 for clustering.") + + # --- File Path Handling --- + try: + output_dir.mkdir(parents=True, exist_ok=True) + except OSError as e: + raise OSError(f"Could not create output directory {output_dir}: {e}") + + output_files = [] + + # --- R Script Generation --- + # Note: R booleans are TRUE/FALSE + r_script_content = textwrap.dedent(f""" + # Load necessary libraries + library(COTAN) + library(Matrix) + + print("Starting COTAN analysis workflow...") + + # --- Parameters --- + raw_count_matrix_path <- "{raw_count_matrix.resolve()}" + output_dir_path <- "{output_dir.resolve()}" + min_reads <- {min_reads_per_cell} + min_cells <- {min_cells_per_gene} + num_cores <- {num_cores} + run_gdi_calc <- {"TRUE" if run_gdi else "FALSE"} + run_clust <- {"TRUE" if run_clustering else "FALSE"} + k_clusters <- {num_clusters} + save_obj <- {"TRUE" if save_cotan_object else "FALSE"} + + # --- Data Loading --- + print(paste("Loading raw count matrix from:", raw_count_matrix_path)) + # Using data.table for fast reading, assuming it's installed as a dependency + # or falling back to read.csv + if (requireNamespace("data.table", quietly = TRUE)) {{ + raw_data <- data.table::fread(raw_count_matrix_path, data.table = FALSE) + rownames(raw_data) <- raw_data[,1] + raw_data[,1] <- NULL + }} else {{ + raw_data <- read.csv(raw_count_matrix_path, header = TRUE, row.names = 1, check.names = FALSE) + }} + raw_data <- as.matrix(raw_data) + print("Data loaded successfully.") + + # --- COTAN Object Creation and Cleaning --- + obj <- COTAN(raw = raw_data) + print("COTAN object created.") + + obj <- clean(obj, min.reads = min_reads, min.cells = min_cells, calcExtraData = FALSE) + print("Data cleaning complete.") + + # --- Core Analysis --- + print("Estimating dispersion...") + obj <- estimateDispersion(obj, cores = num_cores) + + print("Calculating co-expression matrix...") + obj <- calculateCoex(obj, cores = num_cores) + + coex_df <- as.data.frame(as.matrix(getCoex(obj))) + coex_path <- file.path(output_dir_path, "coex_matrix.csv") + write.csv(coex_df, file = coex_path) + print(paste("Co-expression matrix saved to:", coex_path)) + + # --- GDI Calculation --- + if (run_gdi_calc) {{ + print("Calculating Global Differentiation Index (GDI)...") + obj <- calculateGDI(obj) + gdi_df <- getGDI(obj) + gdi_path <- file.path(output_dir_path, "gdi_table.csv") + write.csv(gdi_df, file = gdi_path) + print(paste("GDI table saved to:", gdi_path)) + }} + + # --- Clustering --- + if (run_clust) {{ + print("Performing hierarchical clustering on genes...") + coex_dist <- as.dist(1 - getCoex(obj)) + hc <- hclust(coex_dist, method = "ward.D2") + clusters <- cutree(hc, k = k_clusters) + clusters_df <- data.frame(gene = names(clusters), cluster = clusters) + clusters_path <- file.path(output_dir_path, "gene_clusters.csv") + write.csv(clusters_df, file = clusters_path, row.names = FALSE) + print(paste("Gene clusters saved to:", clusters_path)) + }} + + # --- Save Final Object --- + if (save_obj) {{ + rds_path <- file.path(output_dir_path, "cotan_object.rds") + saveRDS(obj, file = rds_path) + print(paste("COTAN object saved to:", rds_path)) + }} + + print("COTAN analysis completed successfully.") + """) + + # --- Subprocess Execution --- + with tempfile.TemporaryDirectory() as temp_dir: + script_path = Path(temp_dir) / "run_cotan.R" + with open(script_path, "w") as f: + f.write(r_script_content) + + command = ["Rscript", str(script_path)] + command_str = " ".join(command) + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + stdout = process.stdout + stderr = process.stderr + + # --- Collect Output Files --- + output_files.append(str(output_dir / "coex_matrix.csv")) + if run_gdi: + output_files.append(str(output_dir / "gdi_table.csv")) + if run_clustering: + output_files.append(str(output_dir / "gene_clusters.csv")) + if save_cotan_object: + output_files.append(str(output_dir / "cotan_object.rds")) + + # Verify that files were actually created + output_files = [p for p in output_files if Path(p).exists()] + + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: Rscript not found. Please ensure R is installed and in your PATH.", + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + + # --- Structured Result Return --- + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cotan/app/bioconductor-cotan_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cotan/app/bioconductor-cotan_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..61397d80050f14705c67e20056692a6ae60d239c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cotan/app/bioconductor-cotan_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-cotan/app/bioconductor-cotan_server.py') +SERVER_NAME = 'biosci_bioconductor_cotan' + + +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-cotan/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cotan/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e40f8dacf3543248285cbdb9e68bac1fd70bcf77 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cotan/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-cotan: + build: . + image: mcp-bioconductor-cotan:latest + container_name: mcp-bioconductor-cotan + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-cotan + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cotan/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cotan/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..618896ac7d6d52c72c4937dca331e04fd907f73d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cotan/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-cotan + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cotan/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cotan/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-cotan/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-csoa/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-csoa/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3c2e24f3b644ec3185df397f30d71a8ab7bd41ff --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-csoa/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-csoa via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-csoa -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-csoa_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-csoa_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-csoa_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-csoa/app/bioconductor-csoa_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-csoa/app/bioconductor-csoa_server.py new file mode 100644 index 0000000000000000000000000000000000000000..043835d369c56c9a7a39694761365d742eebbae9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-csoa/app/bioconductor-csoa_server.py @@ -0,0 +1,226 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# This is a placeholder for the actual MCP decorator. +# The code is written to be compatible with the MCP framework. +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def csoa_analysis( + expression_file: Path, + genesets_file: Path, + groups_file: Path, + output_prefix: str, + min_size: int = 5, + max_size: Optional[int] = None, + nperm: int = 1000, + p_value_cutoff: float = 0.05, + p_adj_method: str = "BH", + verbose: bool = True, + selected_gs: Optional[str] = None, +): + """ + Performs Clustered Subtype Ontological Analysis (CSOA) using the Bioconductor 'csoa' package. + + This tool takes an expression matrix, gene sets, and sample group information to identify + gene sets that are significantly enriched in different sample subtypes. It generates an + HTML report and saves the full analysis results as an RDS object. + + Args: + expression_file: Path to the expression data file (TSV format, with genes in rows + and samples in columns. The first column should be gene identifiers). + genesets_file: Path to the gene sets file in GMT format. + groups_file: Path to the sample groups file (TSV format with a header, containing two + columns: SampleID and Group). + output_prefix: Prefix for the output files (e.g., 'my_analysis'). This will generate + 'my_analysis_report.html' and 'my_analysis_results.rds'. + min_size: Minimum size of a gene set to be considered for analysis. + max_size: Maximum size of a gene set to be considered. If not provided, no upper + limit is imposed. + nperm: Number of permutations to perform for significance testing. + p_value_cutoff: P-value cutoff for determining significance. + p_adj_method: Method for multiple testing correction. Must be one of 'holm', 'hochberg', + 'hommel', 'bonferroni', 'BH', 'BY', 'fdr', 'none'. + verbose: If True, enables verbose output during the analysis. + selected_gs: A comma-separated string of specific gene set names to analyze. If not + provided, all gene sets in the GMT file are used. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a list of + generated output files. + """ + # --- Input Validation --- + if not expression_file.is_file(): + raise FileNotFoundError(f"Expression file not found: {expression_file}") + if not genesets_file.is_file(): + raise FileNotFoundError(f"Gene sets file not found: {genesets_file}") + if not groups_file.is_file(): + raise FileNotFoundError(f"Groups file not found: {groups_file}") + + if min_size <= 0: + raise ValueError("min_size must be a positive integer.") + if max_size is not None and max_size < min_size: + raise ValueError("max_size cannot be smaller than min_size.") + if nperm <= 0: + raise ValueError("nperm (number of permutations) must be a positive integer.") + if not (0.0 < p_value_cutoff <= 1.0): + raise ValueError("p_value_cutoff must be between 0 and 1.") + + allowed_adj_methods = ['holm', 'hochberg', 'hommel', 'bonferroni', 'BH', 'BY', 'fdr', 'none'] + if p_adj_method not in allowed_adj_methods: + raise ValueError(f"p_adj_method must be one of {allowed_adj_methods}, but got '{p_adj_method}'.") + + if not output_prefix: + raise ValueError("output_prefix cannot be empty.") + + # --- R Script for Execution --- + # This self-contained R script acts as a command-line wrapper for the csoa library functions. + r_script_content = """ + # Autogenerated R script to run CSOA analysis + suppressPackageStartupMessages(library(argparse)) + suppressPackageStartupMessages(library(csoa)) + suppressPackageStartupMessages(library(Biobase)) + suppressPackageStartupMessages(library(GSEABase)) + + parser <- ArgumentParser(description="Run Clustered Subtype Ontological Analysis (CSOA)") + parser$add_argument("--expression", type="character", required=TRUE, help="Path to the expression data file.") + parser$add_argument("--genesets", type="character", required=TRUE, help="Path to the gene sets file (GMT format).") + parser$add_argument("--groups", type="character", required=TRUE, help="Path to the sample groups file.") + parser$add_argument("--output_prefix", type="character", required=TRUE, help="Prefix for output files.") + parser$add_argument("--min_size", type="integer", default=5, help="Minimum size of a gene set.") + parser$add_argument("--max_size", type="integer", default=NULL, help="Maximum size of a gene set.") + parser$add_argument("--nperm", type="integer", default=1000, help="Number of permutations.") + parser$add_argument("--p_value_cutoff", type="double", default=0.05, help="P-value cutoff.") + parser$add_argument("--p_adj_method", type="character", default="BH", help="P-value adjustment method.") + parser$add_argument("--selected_gs", type="character", default=NULL, help="Comma-separated list of selected gene sets.") + parser$add_argument("--verbose", action="store_true", default=FALSE, help="Enable verbose output.") + args <- parser$parse_args() + + tryCatch({ + if (args$verbose) cat("Loading expression data from:", args$expression, "\\n") + expr_data <- read.delim(args$expression, row.names=1, check.names=FALSE, sep="\\t") + expr_matrix <- as.matrix(expr_data) + + if (args$verbose) cat("Loading sample groups from:", args$groups, "\\n") + groups_data <- read.delim(args$groups, header=TRUE, stringsAsFactors=FALSE, sep="\\t") + + if (ncol(groups_data) < 2) { + stop("Groups file must have at least two columns: SampleID and Group.") + } + + sample_order <- match(colnames(expr_matrix), groups_data[,1]) + if (any(is.na(sample_order))) { + missing_samples <- colnames(expr_matrix)[is.na(sample_order)] + stop(paste("Sample names in groups file do not match all sample names in expression file. Missing:", paste(missing_samples, collapse=", "))) + } + groups_ordered <- groups_data[sample_order, ] + groups_vector <- as.factor(groups_ordered[,2]) + names(groups_vector) <- groups_ordered[,1] + + eset <- ExpressionSet(assayData=expr_matrix) + pData(eset)$groups <- groups_vector + + if (args$verbose) cat("Loading gene sets from:", args$genesets, "\\n") + gsets <- getGmt(args$genesets) + + selected_gs_vector <- NULL + if (!is.null(args$selected_gs)) { + selected_gs_vector <- trimws(strsplit(args$selected_gs, ",")[[1]]) + } + + max_size_val <- if (is.null(args$max_size)) Inf else args$max_size + + if (args$verbose) cat("Running CSOA analysis...\\n") + csoa_res <- csoa( + eset = eset, gsets = gsets, groups = "groups", + min.size = args$min_size, max.size = max_size_val, + nperm = args$nperm, selected.gs = selected_gs_vector, + p.value.cutoff = args$p_value_cutoff, p.adj.method = args$p_adj_method, + verbose = args$verbose + ) + if (args$verbose) cat("CSOA analysis complete.\\n") + + report_file <- paste0(args$output_prefix, "_report.html") + if (args$verbose) cat("Generating HTML report to:", report_file, "\\n") + csoa_report(csoa_res, file=report_file) + + rds_file <- paste0(args$output_prefix, "_results.rds") + if (args$verbose) cat("Saving CSOA results object to:", rds_file, "\\n") + saveRDS(csoa_res, file=rds_file) + + cat("Workflow finished successfully.\\n") + }, error = function(e) { + message("An error occurred during CSOA execution:") + message(conditionMessage(e)) + quit(status=1) + }) + """ + + # --- Command Construction and Execution --- + r_script_path = None + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_path = Path(r_script_file.name) + r_script_file.write(r_script_content) + + cmd = [ + "Rscript", str(r_script_path), + "--expression", str(expression_file.resolve()), + "--genesets", str(genesets_file.resolve()), + "--groups", str(groups_file.resolve()), + "--output_prefix", output_prefix, + "--min_size", str(min_size), + "--nperm", str(nperm), + "--p_value_cutoff", str(p_value_cutoff), + "--p_adj_method", p_adj_method, + ] + + if max_size is not None: + cmd.extend(["--max_size", str(max_size)]) + if selected_gs: + cmd.extend(["--selected_gs", selected_gs]) + if verbose: + cmd.append("--verbose") + + command_executed = " ".join(cmd) + + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + + # --- Collect Output --- + output_files: List[str] = [] + report_path = Path(f"{output_prefix}_report.html") + rds_path = Path(f"{output_prefix}_results.rds") + + if report_path.is_file(): + output_files.append(str(report_path)) + if rds_path.is_file(): + output_files.append(str(rds_path)) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd) if 'cmd' in locals() else "Command construction failed", + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"CSOA execution failed with return code {e.returncode}", + "output_files": [] + } + finally: + # Clean up the temporary R script + if r_script_path and r_script_path.exists(): + r_script_path.unlink() \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-csoa/app/bioconductor-csoa_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-csoa/app/bioconductor-csoa_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..934fa832bf383e19a3bf8bdac92504e0a4544484 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-csoa/app/bioconductor-csoa_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-csoa/app/bioconductor-csoa_server.py') +SERVER_NAME = 'biosci_bioconductor_csoa' + + +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-csoa/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-csoa/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-csoa/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-csoa/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-csoa/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c4eb958baf0cf83bd29d20caf2f3a04b56dc068e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-csoa/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-csoa: + build: . + image: mcp-bioconductor-csoa:latest + container_name: mcp-bioconductor-csoa + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-csoa + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-csoa/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-csoa/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fdc168854e55c9573fcb5dab265bfba7f0768b48 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-csoa/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-csoa + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-csoa/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-csoa/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-csoa/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ctsv/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ctsv/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..eb724cc9838a8a6772f972aac6a8cd14be1ef854 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ctsv/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-ctsv via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-ctsv -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-ctsv_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-ctsv_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-ctsv_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ctsv/app/bioconductor-ctsv_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ctsv/app/bioconductor-ctsv_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3590e28feae32d47c0d425f843afcc1628700247 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ctsv/app/bioconductor-ctsv_server.py @@ -0,0 +1,246 @@ +import subprocess +import tempfile +import textwrap +import re +from pathlib import Path +from typing import Optional, Dict, Any + +# This is a placeholder for the actual decorator as per the user's request. +# In a real MCP environment, you would use `from mcp import mcp`. +def tool(*args, **kwargs): + def decorator(f): + return f + return decorator + +mcp = type("mcp", (), {"tool": tool}) + +# Define allowed values for specific string parameters to ensure validity +ALLOWED_DIST_METHODS = ["dtw_basic", "dtw", "sbd", "fourier", "euclidean"] +ALLOWED_CENTROID_METHODS = ["dba", "pam", "mean", "median", "shape"] +ALLOWED_NORM_METHODS = ["zscore", "minmax", "none"] +ALLOWED_STEP_PATTERNS = [ + "symmetric1", "symmetricP1", "symmetric2", "symmetricP2", + "asymmetric", "asymmetricP0", "asymmetricP05", "asymmetricP1", "asymmetricP2" +] +ALLOWED_K_METHODS = ["all", "silhouette", "elbow", "gap_stat"] + +@mcp.tool() +def run_ctsv( + input_file: Path, + output_dir: Path, + n_clusters: Optional[int] = None, + k_list: Optional[str] = None, + output_prefix: str = "ctsv_results", + dist_method: str = "dtw_basic", + centroid_method: str = "dba", + norm_method: str = "zscore", + step_pattern: str = "symmetricP2", + window_size: Optional[int] = None, + seed: int = 1234, + k_method: str = "all", +) -> Dict[str, Any]: + """ + Performs clustering of temporal signals in raster data using the 'ctsv' R package. + + This tool wraps the core functions of the 'ctsv' Bioconductor package. It can either + run clustering for a fixed number of clusters (by setting 'n_clusters') or automatically + determine the optimal number of clusters from a given range (by setting 'k_list'). + + Args: + input_file: Path to the input raster file (e.g., GeoTIFF stack). + output_dir: Path to the directory where output files will be saved. + n_clusters: The fixed number of clusters to create. Mutually exclusive with 'k_list'. + k_list: A range of cluster numbers to test for automatic selection (e.g., "2:10"). + Mutually exclusive with 'n_clusters'. + output_prefix: Prefix for all output files. + dist_method: The distance method for comparing time series. + centroid_method: The method for calculating cluster centroids. + norm_method: The normalization method to apply to the time series. + step_pattern: The step pattern for Dynamic Time Warping (DTW). + window_size: The window size for DTW, constraining the warping path. + seed: An integer for the random number generator to ensure reproducibility. + k_method: The method for selecting the optimal number of clusters when 'k_list' is used. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a + structured dictionary of output file paths. + """ + # 1. Input Validation + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + if (n_clusters is None and k_list is None) or (n_clusters is not None and k_list is not None): + raise ValueError("Exactly one of 'n_clusters' or 'k_list' must be provided.") + + if n_clusters is not None and n_clusters <= 1: + raise ValueError("'n_clusters' must be an integer greater than 1.") + + if k_list is not None: + if not re.match(r"^\d+:\d+$", k_list): + raise ValueError("Invalid 'k_list' format. Expected 'start:end', e.g., '2:10'.") + start, end = map(int, k_list.split(':')) + if start < 2 or start >= end: + raise ValueError("'k_list' range must start at 2 or greater and be an increasing range.") + + if dist_method not in ALLOWED_DIST_METHODS: + raise ValueError(f"Invalid 'dist_method'. Choose from: {', '.join(ALLOWED_DIST_METHODS)}") + if centroid_method not in ALLOWED_CENTROID_METHODS: + raise ValueError(f"Invalid 'centroid_method'. Choose from: {', '.join(ALLOWED_CENTROID_METHODS)}") + if norm_method not in ALLOWED_NORM_METHODS: + raise ValueError(f"Invalid 'norm_method'. Choose from: {', '.join(ALLOWED_NORM_METHODS)}") + if step_pattern not in ALLOWED_STEP_PATTERNS: + raise ValueError(f"Invalid 'step_pattern'. Choose from: {', '.join(ALLOWED_STEP_PATTERNS)}") + if k_list is not None and k_method not in ALLOWED_K_METHODS: + raise ValueError(f"Invalid 'k_method'. Choose from: {', '.join(ALLOWED_K_METHODS)}") + + if window_size is not None and window_size <= 0: + raise ValueError("'window_size' must be a positive integer.") + + # 2. R Script Generation + # We embed parameters directly into the script to avoid shell quoting issues. + r_script_content = textwrap.dedent(f""" + # Suppress package startup messages for cleaner output + suppressPackageStartupMessages(library(ctsv)) + suppressPackageStartupMessages(library(raster)) + suppressPackageStartupMessages(library(dtw)) + + # --- Parameters --- + input_file_path <- "{str(input_file.resolve())}" + output_dir_path <- "{str(output_dir.resolve())}" + output_prefix_str <- "{output_prefix}" + n_clusters_val <- {n_clusters if n_clusters is not None else 'NULL'} + k_list_str <- {"'{k_list}'" if k_list is not None else 'NULL'} + dist_method_str <- "{dist_method}" + centroid_method_str <- "{centroid_method}" + norm_method_str <- "{norm_method}" + step_pattern_str <- "{step_pattern}" + window_size_val <- {window_size if window_size is not None else 'NULL'} + seed_val <- {seed} + k_method_str <- "{k_method}" + + # Set seed for reproducibility + set.seed(seed_val) + + # Load input data + message("Loading input data from: ", input_file_path) + input_data <- tryCatch({{ + raster::stack(input_file_path) + }}, error = function(e) {{ + stop("Failed to load input file. Ensure it is a valid raster format. Error: ", e$message) + }}) + + # Map step pattern string to dtw object + step_pattern_obj <- switch(step_pattern_str, + "symmetric1" = dtw::symmetric1, "symmetricP1" = dtw::symmetricP1, + "symmetric2" = dtw::symmetricP2, "symmetricP2" = dtw::symmetricP2, + "asymmetric" = dtw::asymmetric, "asymmetricP0" = dtw::asymmetricP0, + "asymmetricP05" = dtw::asymmetricP05, "asymmetricP1" = dtw::asymmetricP1, + "asymmetricP2" = dtw::asymmetricP2, + dtw::symmetricP2 # Default + ) + + # Decide whether to run ctsv or ctsv_auto + if (!is.null(n_clusters_val)) {{ + message("Running ctsv with n_clusters = ", n_clusters_val) + result <- ctsv( + x = input_data, n_clusters = n_clusters_val, dist_method = dist_method_str, + centroid_method = centroid_method_str, norm_method = norm_method_str, + step_pattern = step_pattern_obj, window_size = window_size_val, seed = seed_val + ) + }} else if (!is.null(k_list_str)) {{ + message("Running ctsv_auto with k_list = ", k_list_str) + k_vector <- eval(parse(text=k_list_str)) + result <- ctsv_auto( + x = input_data, k_list = k_vector, dist_method = dist_method_str, + centroid_method = centroid_method_str, norm_method = norm_method_str, + step_pattern = step_pattern_obj, window_size = window_size_val, + seed = seed_val, k_method = k_method_str + ) + }} else {{ + stop("Internal error: Neither n_clusters nor k_list was provided to the R script.") + }} + + # Create output directory + dir.create(output_dir_path, showWarnings = FALSE, recursive = TRUE) + + # --- Save outputs --- + clustered_raster_path <- file.path(output_dir_path, paste0(output_prefix_str, "_clustered_raster.tif")) + raster::writeRaster(result$clustered_raster, filename=clustered_raster_path, overwrite=TRUE) + message("SUCCESS: Saved clustered raster to: ", clustered_raster_path) + + profiles_plot_path <- file.path(output_dir_path, paste0(output_prefix_str, "_profiles.png")) + png(profiles_plot_path, width=800, height=600) + plot(ctsv_get_profiles(result)) + dev.off() + message("SUCCESS: Saved profiles plot to: ", profiles_plot_path) + + members_df <- ctsv_get_members(result) + members_csv_path <- file.path(output_dir_path, paste0(output_prefix_str, "_members.csv")) + write.csv(members_df, file=members_csv_path, row.names=FALSE) + message("SUCCESS: Saved cluster members to: ", members_csv_path) + + if (!is.null(k_list_str)) {{ + validation_plot_path <- file.path(output_dir_path, paste0(output_prefix_str, "_k_validation.png")) + png(validation_plot_path, width=800, height=600) + plot(result$k_validation) + dev.off() + message("SUCCESS: Saved k validation plot to: ", validation_plot_path) + }} + + message("Processing complete.") + """) + + # 3. Subprocess Execution + r_script_path = "" + try: + output_dir.mkdir(parents=True, exist_ok=True) + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, dir=output_dir) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = r_script_file.name + + cmd = ["Rscript", r_script_path] + command_executed = " ".join(cmd) + + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + cwd=output_dir, + ) + + # 4. Collect and Verify Output Files + output_files_map = { + "clustered_raster": output_dir / f"{output_prefix}_clustered_raster.tif", + "profiles_plot": output_dir / f"{output_prefix}_profiles.png", + "cluster_members": output_dir / f"{output_prefix}_members.csv", + } + if k_list is not None: + output_files_map["k_validation_plot"] = output_dir / f"{output_prefix}_k_validation.png" + + # Verify that all expected files were created + missing_files = [str(p) for p in output_files_map.values() if not p.exists()] + if missing_files: + raise RuntimeError(f"R script finished, but expected output files are missing: {', '.join(missing_files)}") + + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {key: str(path) for key, path in output_files_map.items()} + } + + except FileNotFoundError: + raise RuntimeError("Rscript command not found. Please ensure R is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + error_message = ( + f"R script execution failed with exit code {e.returncode}.\n" + f"Stderr:\n{e.stderr}\n" + f"Stdout:\n{e.stdout}" + ) + raise RuntimeError(error_message) from e + finally: + # Clean up the temporary R script + if r_script_path and Path(r_script_path).exists(): + Path(r_script_path).unlink() \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ctsv/app/bioconductor-ctsv_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ctsv/app/bioconductor-ctsv_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..39fc8154eeed234f123498a89fc67c8d7cc7fcbd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ctsv/app/bioconductor-ctsv_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-ctsv/app/bioconductor-ctsv_server.py') +SERVER_NAME = 'biosci_bioconductor_ctsv' + + +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-ctsv/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ctsv/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ctsv/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ctsv/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ctsv/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..9ff81c86eee540a7c6bf6a8d1be45b64e058c6b9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ctsv/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-ctsv: + build: . + image: mcp-bioconductor-ctsv:latest + container_name: mcp-bioconductor-ctsv + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-ctsv + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ctsv/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ctsv/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6db1e33d080c74872941d56c7234ca6d659a2fdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ctsv/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-ctsv + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ctsv/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ctsv/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ctsv/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-curatedatlasqueryr/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-curatedatlasqueryr/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..02ebac92236f7770576c155e661a1d5f225a564f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-curatedatlasqueryr/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-curatedatlasqueryr via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-curatedatlasqueryr -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-curatedatlasqueryr_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-curatedatlasqueryr_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-curatedatlasqueryr_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-curatedatlasqueryr/app/bioconductor-curatedatlasqueryr_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-curatedatlasqueryr/app/bioconductor-curatedatlasqueryr_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fba227c296e1c6ba5ac77c184fc065684f5a51ef --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-curatedatlasqueryr/app/bioconductor-curatedatlasqueryr_server.py @@ -0,0 +1,248 @@ +import subprocess +import os +import json +from pathlib import Path +from typing import Optional, List, Union + +def _run_r_command(r_code: str) -> dict: + """Helper to execute R code and handle errors.""" + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "stdout": result.stdout, + "stderr": result.stderr, + "success": True + } + except subprocess.CalledProcessError as e: + return { + "stdout": e.stdout, + "stderr": e.stderr, + "success": False, + "error": str(e) + } + +@mcp.tool() +def get_metadata( + output_csv: str, + force_update: bool = False +) -> dict: + """ + Retrieves the full metadata table from curatedAtlasQueryR and saves it as a CSV file. + + Args: + output_csv: Path where the metadata CSV will be saved. + force_update: If True, forces a re-download of the metadata from the remote source. + """ + output_path = Path(output_csv).resolve() + force_r = "TRUE" if force_update else "FALSE" + + r_code = f""" + suppressPackageStartupMessages(library(curatedAtlasQueryR)) + meta <- get_metadata(force = {force_r}) + write.csv(as.data.frame(meta), file = '{str(output_path)}', row.names = FALSE) + """ + + res = _run_r_command(r_code) + + return { + "command_executed": f"curatedAtlasQueryR::get_metadata(force={force_r})", + "stdout": res["stdout"], + "stderr": res["stderr"], + "output_files": [str(output_path)] if output_path.exists() else [], + "status": "success" if res["success"] else "failed" + } + +@mcp.tool() +def list_metadata_fields() -> dict: + """ + Lists all available columns/fields in the curatedAtlasQueryR metadata. + """ + r_code = """ + suppressPackageStartupMessages(library(curatedAtlasQueryR)) + meta <- get_metadata() + cat(paste(colnames(meta), collapse = "\n")) + """ + + res = _run_r_command(r_code) + + if res["success"]: + fields = res["stdout"].strip().split("\n") + return { + "command_executed": "colnames(get_metadata())", + "available_fields": fields, + "stdout": res["stdout"] + } + else: + return { + "error": "Failed to list fields", + "stderr": res["stderr"] + } + +@mcp.tool() +def search_metadata( + query: str, + output_csv: str, + fields: Optional[List[str]] = None +) -> dict: + """ + Searches the curatedAtlasQueryR metadata for specific terms across all or specified fields. + + Args: + query: The search term or regex pattern to look for. + output_csv: Path to save the filtered metadata results. + fields: Optional list of specific metadata columns to search within. + """ + output_path = Path(output_csv).resolve() + + # Handle fields list for R without backslashes in f-string + if fields: + fields_list_str = ", ".join([f"'{f}'" for f in fields]) + fields_r = f"c({fields_list_str})" + else: + fields_r = "NULL" + + r_code = f""" + suppressPackageStartupMessages(library(curatedAtlasQueryR)) + meta <- get_metadata() + search_cols <- {fields_r} + if (is.null(search_cols)) search_cols <- colnames(meta) + + # Filter rows where any of the selected columns match the query + matches <- apply(meta[, search_cols, drop = FALSE], 1, function(row) {{ + any(grepl("{query}", as.character(row), ignore.case = TRUE)) + }}) + + search_res <- meta[matches, ] + write.csv(as.data.frame(search_res), file = '{str(output_path)}', row.names = FALSE) + """ + + res = _run_r_command(r_code) + + return { + "command_executed": f"Searching metadata for '{query}' in fields {fields_r}", + "stdout": res["stdout"], + "stderr": res["stderr"], + "output_files": [str(output_path)] if output_path.exists() else [] + } + +@mcp.tool() +def query_metadata_custom( + r_filter_expression: str, + output_csv: str +) -> dict: + """ + Performs a custom R-style filter on the metadata table using dplyr syntax. + + Args: + r_filter_expression: An R logical expression string (e.g., "tissue == 'liver' & disease == 'normal'"). + output_csv: Path to save the filtered metadata. + """ + output_path = Path(output_csv).resolve() + + r_code = f""" + suppressPackageStartupMessages(library(curatedAtlasQueryR)) + suppressPackageStartupMessages(library(dplyr)) + meta <- get_metadata() + filtered_meta <- meta %>% filter({r_filter_expression}) + write.csv(as.data.frame(filtered_meta), file = '{str(output_path)}', row.names = FALSE) + """ + + res = _run_r_command(r_code) + + return { + "command_executed": f"Metadata filter: {r_filter_expression}", + "stdout": res["stdout"], + "stderr": res["stderr"], + "output_files": [str(output_path)] if output_path.exists() else [] + } + +@mcp.tool() +def get_atlas_data( + sample_ids: List[str], + output_rds: str +) -> dict: + """ + Downloads single-cell data (SingleCellExperiment) for specified sample IDs. + + Args: + sample_ids: A list of sample_id strings to download. + output_rds: Path to save the resulting SingleCellExperiment object (.rds). + """ + output_path = Path(output_rds).resolve() + + if not sample_ids: + return {"error": "No sample_ids provided."} + + ids_list_str = ", ".join([f"'{i}'" for i in sample_ids]) + ids_r = f"c({ids_list_str})" + + r_code = f""" + suppressPackageStartupMessages(library(curatedAtlasQueryR)) + suppressPackageStartupMessages(library(SingleCellExperiment)) + + meta <- get_metadata() + selected_meta <- meta[meta$sample_id %in% {ids_r}, ] + + if(nrow(selected_meta) == 0) stop("No matching sample IDs found in metadata.") + + sce <- get_data(selected_meta) + saveRDS(sce, file = '{str(output_path)}') + """ + + res = _run_r_command(r_code) + + return { + "command_executed": f"curatedAtlasQueryR::get_data() for {len(sample_ids)} samples", + "stdout": res["stdout"], + "stderr": res["stderr"], + "output_files": [str(output_path)] if output_path.exists() else [] + } + +@mcp.tool() +def get_gene_expression( + sample_ids: List[str], + genes: List[str], + output_rds: str +) -> dict: + """ + Retrieves gene expression data for specific genes across specified samples. + + Args: + sample_ids: A list of sample_id strings. + genes: A list of gene symbols or IDs to retrieve. + output_rds: Path to save the resulting SummarizedExperiment object (.rds). + """ + output_path = Path(output_rds).resolve() + + if not sample_ids or not genes: + return {"error": "Both sample_ids and genes must be provided."} + + ids_list_str = ", ".join([f"'{i}'" for i in sample_ids]) + genes_list_str = ", ".join([f"'{g}'" for g in genes]) + + r_code = f""" + suppressPackageStartupMessages(library(curatedAtlasQueryR)) + suppressPackageStartupMessages(library(SummarizedExperiment)) + + meta <- get_metadata() + selected_meta <- meta[meta$sample_id %in% c({ids_list_str}), ] + + if(nrow(selected_meta) == 0) stop("No matching sample IDs found in metadata.") + + se <- get_gene_expression(selected_meta, genes = c({genes_list_str})) + saveRDS(se, file = '{str(output_path)}') + """ + + res = _run_r_command(r_code) + + return { + "command_executed": f"curatedAtlasQueryR::get_gene_expression() for {len(genes)} genes", + "stdout": res["stdout"], + "stderr": res["stderr"], + "output_files": [str(output_path)] if output_path.exists() else [] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-curatedatlasqueryr/app/bioconductor-curatedatlasqueryr_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-curatedatlasqueryr/app/bioconductor-curatedatlasqueryr_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..59071fbb2bb10a4f5ffe6cc5976bf509c144ff2b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-curatedatlasqueryr/app/bioconductor-curatedatlasqueryr_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-curatedatlasqueryr/app/bioconductor-curatedatlasqueryr_server.py') +SERVER_NAME = 'biosci_bioconductor_curatedatlasqueryr' + + +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-curatedatlasqueryr/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-curatedatlasqueryr/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-curatedatlasqueryr/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-curatedatlasqueryr/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-curatedatlasqueryr/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..61ced17959568e3d32fc631fcbb885443248c4d9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-curatedatlasqueryr/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-curatedatlasqueryr: + build: . + image: mcp-bioconductor-curatedatlasqueryr:latest + container_name: mcp-bioconductor-curatedatlasqueryr + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-curatedatlasqueryr + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-curatedatlasqueryr/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-curatedatlasqueryr/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4ebc5295ee989236a3cdfaf8847d8072211ef33 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-curatedatlasqueryr/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-curatedatlasqueryr + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-curatedatlasqueryr/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-curatedatlasqueryr/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-curatedatlasqueryr/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dada2/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dada2/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c72b1a621246143f17e51744c1fe5c08dd7d79a6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dada2/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-dada2 via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-dada2 -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-dada2_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-dada2_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-dada2_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dada2/app/bioconductor-dada2_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dada2/app/bioconductor-dada2_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b8b7eaf785aec94e0a613e0b9fc634b7b9f49516 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dada2/app/bioconductor-dada2_server.py @@ -0,0 +1,754 @@ +import subprocess +import tempfile +import os +from pathlib import Path +from typing import List, Optional, Union + +# Helper function to run R scripts +def _run_r_script(r_script_content: str, output_dir: Path) -> dict: + """ + Executes an R script using Rscript. + """ + # Ensure the output directory exists for temporary files + output_dir.mkdir(parents=True, exist_ok=True) + + temp_r_script_path: Optional[Path] = None + try: + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".R", dir=output_dir) as temp_r_script: + temp_r_script.write(r_script_content) + temp_r_script_path = Path(temp_r_script.name) + + command = ["Rscript", str(temp_r_script_path)] + + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + encoding="utf-8" + ) + stdout = process.stdout + stderr = process.stderr + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": [], # This will be populated by individual tool functions + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command) if 'command' in locals() else "Rscript execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed with exit code {e.returncode}", + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": " ".join(command) if 'command' in locals() else "Rscript execution failed", + "stdout": "", + "stderr": "Rscript command not found. Please ensure R is installed and in your PATH.", + "error": "Rscript not found", + "output_files": [], + } + except Exception as e: + return { + "command_executed": " ".join(command) if 'command' in locals() else "Rscript execution failed", + "stdout": "", + "stderr": str(e), + "error": f"An unexpected error occurred: {e}", + "output_files": [], + } + finally: + if temp_r_script_path and temp_r_script_path.exists(): + os.remove(temp_r_script_path) + +@mcp.tool() +def filter_and_trim( + fwd_reads: List[Path], + output_dir: Path, + rev_reads: Optional[List[Path]] = None, + trunc_len_f: Optional[int] = None, + trunc_len_r: Optional[int] = None, + trim_left_f: int = 0, + trim_left_r: int = 0, + max_n: int = 0, + max_ee_f: float = 2.0, + max_ee_r: float = 2.0, + trunc_q: int = 2, + rm_phix: bool = True, + compress: bool = True, + multithread: Union[bool, int] = False, + verbose: bool = False, +) -> dict: + """ + Performs quality filtering and trimming of raw sequencing reads using dada2's filterAndTrim. + + Args: + fwd_reads: A list of paths to forward FASTQ files. + output_dir: Directory to save filtered FASTQ files. + rev_reads: An optional list of paths to reverse FASTQ files (for paired-end data). + Must be the same length as fwd_reads if provided. + trunc_len_f: Truncate forward reads after this many bases. Reads shorter than this are discarded. + trunc_len_r: Truncate reverse reads after this many bases. Reads shorter than this are discarded. + trim_left_f: Number of nucleotides to remove from the start of each forward read. + trim_left_r: Number of nucleotides to remove from the start of each reverse read. + max_n: After truncation, reads with more than max_n N's will be discarded. + max_ee_f: Forward reads with an expected error rate higher than max_ee_f will be discarded. + max_ee_r: Reverse reads with an expected error rate higher than max_ee_r will be discarded. + trunc_q: Truncate reads at the first instance of a quality score less than or equal to trunc_q. + rm_phix: If TRUE, phiX reads are removed. + compress: If TRUE, the output files are gzipped. + multithread: If TRUE, multithreading is enabled. Can also be an integer specifying number of threads. + verbose: If TRUE, print verbose output. + + Returns: + A dictionary containing command execution details, stdout, stderr, and paths to output files. + """ + # Input validation + if not fwd_reads: + raise ValueError("fwd_reads cannot be empty.") + for f_read in fwd_reads: + if not f_read.is_file(): + raise FileNotFoundError(f"Forward read file not found: {f_read}") + if rev_reads: + if len(fwd_reads) != len(rev_reads): + raise ValueError("Number of forward and reverse read files must be the same.") + for r_read in rev_reads: + if not r_read.is_file(): + raise FileNotFoundError(f"Reverse read file not found: {r_read}") + if not output_dir.is_dir(): + output_dir.mkdir(parents=True, exist_ok=True) + + # Prepare R script content + r_script_lines = [ + "library(dada2)", + "fwd_reads <- c(" + ", ".join([f'"{str(p)}"' for p in fwd_reads]) + ")", + "output_dir <- '" + str(output_dir) + "'", + "filt_fwd_paths <- file.path(output_dir, paste0(basename(fwd_reads), '.filtered.fastq.gz'))", + ] + + filter_params = [] + + # Handle paired-end specific parameters (truncLen, trimLeft, maxEE) + if rev_reads: + r_script_lines.append("rev_reads <- c(" + ", ".join([f'"{str(p)}"' for p in rev_reads]) + ")") + r_script_lines.append("filt_rev_paths <- file.path(output_dir, paste0(basename(rev_reads), '.filtered.fastq.gz'))") + + trunc_len_arg_f = "NA" if trunc_len_f is None else str(trunc_len_f) + trunc_len_arg_r = "NA" if trunc_len_r is None else str(trunc_len_r) + if trunc_len_f is not None or trunc_len_r is not None: + filter_params.append(f"truncLen=c({trunc_len_arg_f}, {trunc_len_arg_r})") + + if trim_left_f != 0 or trim_left_r != 0: + filter_params.append(f"trimLeft=c({trim_left_f}, {trim_left_r})") + + if max_ee_f != 2.0 or max_ee_r != 2.0: + filter_params.append(f"maxEE=c({max_ee_f}, {max_ee_r})") + else: # Single-end + if trunc_len_f is not None: + filter_params.append(f"truncLen={trunc_len_f}") + if trim_left_f != 0: + filter_params.append(f"trimLeft={trim_left_f}") + if max_ee_f != 2.0: + filter_params.append(f"maxEE={max_ee_f}") + + # Handle common parameters + if max_n != 0: + filter_params.append(f"maxN={max_n}") + if trunc_q != 2: + filter_params.append(f"truncQ={trunc_q}") + if not rm_phix: + filter_params.append("rm.phix=FALSE") + if not compress: + filter_params.append("compress=FALSE") + if multithread: + if isinstance(multithread, bool): + filter_params.append("multithread=TRUE") + else: + filter_params.append(f"multithread={multithread}") + if verbose: + filter_params.append("verbose=TRUE") + + if rev_reads: + r_script_lines.append( + f"out <- filterAndTrim(fwd_reads, filt_fwd_paths, rev_reads, filt_rev_paths, {', '.join(filter_params)})" + ) + output_files = [output_dir / Path(f_read.name + ".filtered.fastq.gz") for f_read in fwd_reads] + \ + [output_dir / Path(r_read.name + ".filtered.fastq.gz") for r_read in rev_reads] + else: + r_script_lines.append( + f"out <- filterAndTrim(fwd_reads, filt_fwd_paths, {', '.join(filter_params)})" + ) + output_files = [output_dir / Path(f_read.name + ".filtered.fastq.gz") for f_read in fwd_reads] + + r_script_content = "\n".join(r_script_lines) + + result = _run_r_script(r_script_content, output_dir) + result["output_files"] = [str(p) for p in output_files] + return result + +@mcp.tool() +def learn_errors( + filtered_reads: List[Path], + output_error_file: Path, + nbases: int = 100000000, + randomize: bool = True, + multithread: Union[bool, int] = False, + verbose: bool = False, +) -> dict: + """ + Learns the error rates from a subset of filtered reads using dada2's learnErrors. + + Args: + filtered_reads: A list of paths to filtered FASTQ files. + output_error_file: Path to save the learned error model (RDS file). + nbases: The minimum number of bases to use for error rate learning. + randomize: If TRUE, the order of samples is randomized before learning errors. + multithread: If TRUE, multithreading is enabled. Can also be an integer specifying number of threads. + verbose: If TRUE, print verbose output. + + Returns: + A dictionary containing command execution details, stdout, stderr, and the path to the output error model file. + """ + # Input validation + if not filtered_reads: + raise ValueError("filtered_reads cannot be empty.") + for f_read in filtered_reads: + if not f_read.is_file(): + raise FileNotFoundError(f"Filtered read file not found: {f_read}") + if output_error_file.suffix != ".rds": + raise ValueError("output_error_file must have a .rds extension.") + if nbases <= 0: + raise ValueError("nbases must be a positive integer.") + output_error_file.parent.mkdir(parents=True, exist_ok=True) + + # Prepare R script content + r_script_lines = [ + "library(dada2)", + "filtered_reads <- c(" + ", ".join([f'"{str(p)}"' for p in filtered_reads]) + ")", + "err_file <- '" + str(output_error_file) + "'", + ] + + learn_params = [ + f"nbases={nbases}", + f"randomize={str(randomize).upper()}", + ] + if multithread: + if isinstance(multithread, bool): + learn_params.append("multithread=TRUE") + else: + learn_params.append(f"multithread={multithread}") + if verbose: + learn_params.append("verbose=TRUE") + + r_script_lines.append( + f"err <- learnErrors(filtered_reads, {', '.join(learn_params)})" + ) + r_script_lines.append(f"saveRDS(err, file=err_file)") + + r_script_content = "\n".join(r_script_lines) + + result = _run_r_script(r_script_content, output_error_file.parent) + result["output_files"] = [str(output_error_file)] + return result + +@mcp.tool() +def dada_denoise( + filtered_reads: List[Path], + error_model_file: Path, + output_dada_file: Path, + pool: Union[bool, str] = False, # Can be TRUE, FALSE, or "pseudo" + multithread: Union[bool, int] = False, + verbose: bool = False, +) -> dict: + """ + Applies the DADA2 denoising algorithm to filtered reads using a learned error model. + + Args: + filtered_reads: A list of paths to filtered FASTQ files. + error_model_file: Path to the learned error model (RDS file) from learn_errors. + output_dada_file: Path to save the denoised sequence object (RDS file). + pool: If TRUE, all samples are pooled together for denoising. If "pseudo", pseudo-pooling is used. + If FALSE, samples are denoised independently. + multithread: If TRUE, multithreading is enabled. Can also be an integer specifying number of threads. + verbose: If TRUE, print verbose output. + + Returns: + A dictionary containing command execution details, stdout, stderr, and the path to the output denoised object file. + """ + # Input validation + if not filtered_reads: + raise ValueError("filtered_reads cannot be empty.") + for f_read in filtered_reads: + if not f_read.is_file(): + raise FileNotFoundError(f"Filtered read file not found: {f_read}") + if not error_model_file.is_file(): + raise FileNotFoundError(f"Error model file not found: {error_model_file}") + if error_model_file.suffix != ".rds": + raise ValueError("error_model_file must have a .rds extension.") + if output_dada_file.suffix != ".rds": + raise ValueError("output_dada_file must have a .rds extension.") + if isinstance(pool, str) and pool not in ["pseudo"]: + raise ValueError(f"Invalid string value for 'pool': {pool}. Must be 'pseudo'.") + output_dada_file.parent.mkdir(parents=True, exist_ok=True) + + # Prepare R script content + r_script_lines = [ + "library(dada2)", + "filtered_reads <- c(" + ", ".join([f'"{str(p)}"' for p in filtered_reads]) + ")", + "err <- readRDS('" + str(error_model_file) + "')", + "dada_file <- '" + str(output_dada_file) + "'", + ] + + dada_params = [ + "err=err", + ] + if isinstance(pool, bool): + dada_params.append(f"pool={str(pool).upper()}") + elif pool == "pseudo": + dada_params.append('pool="pseudo"') + + if multithread: + if isinstance(multithread, bool): + dada_params.append("multithread=TRUE") + else: + dada_params.append(f"multithread={multithread}") + if verbose: + dada_params.append("verbose=TRUE") + + r_script_lines.append( + f"dada_out <- dada(filtered_reads, {', '.join(dada_params)})" + ) + r_script_lines.append(f"saveRDS(dada_out, file=dada_file)") + + r_script_content = "\n".join(r_script_lines) + + result = _run_r_script(r_script_content, output_dada_file.parent) + result["output_files"] = [str(output_dada_file)] + return result + +@mcp.tool() +def merge_paired_reads( + dada_fwd_file: Path, + dada_rev_file: Path, + filtered_fwd_paths: List[Path], + filtered_rev_paths: List[Path], + output_merged_file: Path, + min_overlap: int = 12, + max_mismatch: int = 0, + verbose: bool = False, +) -> dict: + """ + Merges paired-end reads that have been denoised by dada2. + + Args: + dada_fwd_file: Path to the denoised forward sequence object (RDS file) from dada_denoise. + dada_rev_file: Path to the denoised reverse sequence object (RDS file) from dada_denoise. + filtered_fwd_paths: A list of paths to the *filtered* forward FASTQ files (used for sample names). + filtered_rev_paths: A list of paths to the *filtered* reverse FASTQ files (used for sample names). + output_merged_file: Path to save the merged sequence object (RDS file). + min_overlap: The minimum number of overlapping bases required to merge a read pair. + max_mismatch: The maximum number of mismatches allowed in the overlap region. + verbose: If TRUE, print verbose output. + + Returns: + A dictionary containing command execution details, stdout, stderr, and the path to the output merged object file. + """ + # Input validation + if not dada_fwd_file.is_file(): + raise FileNotFoundError(f"Denoised forward file not found: {dada_fwd_file}") + if dada_fwd_file.suffix != ".rds": + raise ValueError("dada_fwd_file must have a .rds extension.") + if not dada_rev_file.is_file(): + raise FileNotFoundError(f"Denoised reverse file not found: {dada_rev_file}") + if dada_rev_file.suffix != ".rds": + raise ValueError("dada_rev_file must have a .rds extension.") + if not filtered_fwd_paths or not filtered_rev_paths: + raise ValueError("filtered_fwd_paths and filtered_rev_paths cannot be empty.") + if len(filtered_fwd_paths) != len(filtered_rev_paths): + raise ValueError("Number of filtered forward and reverse read files must be the same.") + for f_read in filtered_fwd_paths: + if not f_read.is_file(): + raise FileNotFoundError(f"Filtered forward read file not found: {f_read}") + for r_read in filtered_rev_paths: + if not r_read.is_file(): + raise FileNotFoundError(f"Filtered reverse read file not found: {r_read}") + if output_merged_file.suffix != ".rds": + raise ValueError("output_merged_file must have a .rds extension.") + if min_overlap < 0: + raise ValueError("min_overlap cannot be negative.") + if max_mismatch < 0: + raise ValueError("max_mismatch cannot be negative.") + output_merged_file.parent.mkdir(parents=True, exist_ok=True) + + # Extract sample names from filtered file paths + sample_names = [] + for f_path in filtered_fwd_paths: + # Attempt to remove common suffixes to get a clean sample name + name = f_path.name + name = name.replace(".filtered.fastq.gz", "").replace(".fastq.gz", "") + name = name.replace("_R1", "").replace("_1", "").replace("_fwd", "") + sample_names.append(name) + + # Prepare R script content + r_script_lines = [ + "library(dada2)", + "dada_fwd <- readRDS('" + str(dada_fwd_file) + "')", + "dada_rev <- readRDS('" + str(dada_rev_file) + "')", + "sample_names <- c(" + ", ".join([f'"{s}"' for s in sample_names]) + ")", + "names(dada_fwd) <- sample_names", + "names(dada_rev) <- sample_names", + "merged_file <- '" + str(output_merged_file) + "'", + "filtered_fwd_paths <- c(" + ", ".join([f'"{str(p)}"' for p in filtered_fwd_paths]) + ")", + "filtered_rev_paths <- c(" + ", ".join([f'"{str(p)}"' for p in filtered_rev_paths]) + ")", + ] + + merge_params = [ + f"minOverlap={min_overlap}", + f"maxMismatch={max_mismatch}", + ] + if verbose: + merge_params.append("verbose=TRUE") + + r_script_lines.append( + f"mergers <- mergePairs(dada_fwd, filtered_fwd_paths, dada_rev, filtered_rev_paths, {', '.join(merge_params)})" + ) + r_script_lines.append(f"saveRDS(mergers, file=merged_file)") + + r_script_content = "\n".join(r_script_lines) + + result = _run_r_script(r_script_content, output_merged_file.parent) + result["output_files"] = [str(output_merged_file)] + return result + +@mcp.tool() +def make_sequence_table( + dada_objects_files: List[Path], + output_seq_table_file: Path, + output_seq_table_csv: Optional[Path] = None, + samples_names: Optional[List[str]] = None, + verbose: bool = False, +) -> dict: + """ + Constructs an amplicon sequence variant (ASV) table from denoised or merged sequence objects. + + Args: + dada_objects_files: A list of paths to denoised (from dada_denoise) or merged (from merge_paired_reads) + sequence object RDS files. + output_seq_table_file: Path to save the ASV table (RDS file). + output_seq_table_csv: Optional path to save the ASV table as a CSV file. + samples_names: Optional list of sample names corresponding to the dada_objects_files. + If None, names are inferred from the RDS filenames. + verbose: If TRUE, print verbose output. + + Returns: + A dictionary containing command execution details, stdout, stderr, and paths to output files. + """ + # Input validation + if not dada_objects_files: + raise ValueError("dada_objects_files cannot be empty.") + for obj_file in dada_objects_files: + if not obj_file.is_file(): + raise FileNotFoundError(f"Dada object file not found: {obj_file}") + if obj_file.suffix != ".rds": + raise ValueError(f"Dada object file {obj_file} must have a .rds extension.") + if output_seq_table_file.suffix != ".rds": + raise ValueError("output_seq_table_file must have a .rds extension.") + output_seq_table_file.parent.mkdir(parents=True, exist_ok=True) + if output_seq_table_csv: + if output_seq_table_csv.suffix != ".csv": + raise ValueError("output_seq_table_csv must have a .csv extension.") + output_seq_table_csv.parent.mkdir(parents=True, exist_ok=True) + if samples_names and len(samples_names) != len(dada_objects_files): + raise ValueError("Number of sample names must match number of dada object files.") + + # Prepare R script content + r_script_lines = [ + "library(dada2)", + "dada_objects <- list(" + ", ".join([f"readRDS('{str(p)}')" for p in dada_objects_files]) + ")", + ] + + if samples_names: + r_script_lines.append("sample_names <- c(" + ", ".join([f'"{s}"' for s in samples_names]) + ")") + r_script_lines.append("names(dada_objects) <- sample_names") + else: + # Infer sample names from file names (e.g., remove .rds and common processing suffixes) + inferred_names = [] + for p in dada_objects_files: + name = p.stem + name = name.replace(".filtered", "").replace(".denoised", "").replace(".merged", "") + inferred_names.append(name) + r_script_lines.append("sample_names <- c(" + ", ".join([f'"{s}"' for s in inferred_names]) + ")") + r_script_lines.append("names(dada_objects) <- sample_names") + + r_script_lines.append( + f"seq_table <- makeSequenceTable(dada_objects)" + ) + r_script_lines.append(f"saveRDS(seq_table, file='{str(output_seq_table_file)}')") + + output_files = [str(output_seq_table_file)] + if output_seq_table_csv: + r_script_lines.append(f"write.csv(seq_table, file='{str(output_seq_table_csv)}', row.names=TRUE)") + output_files.append(str(output_seq_table_csv)) + + r_script_content = "\n".join(r_script_lines) + + result = _run_r_script(r_script_content, output_seq_table_file.parent) + result["output_files"] = output_files + return result + +@mcp.tool() +def remove_bimera_denovo( + seq_table_file: Path, + output_nochim_table_file: Path, + output_nochim_table_csv: Optional[Path] = None, + method: str = "consensus", + multithread: Union[bool, int] = False, + verbose: bool = False, +) -> dict: + """ + Removes chimeric sequences from an ASV table using dada2's removeBimeraDenovo. + + Args: + seq_table_file: Path to the ASV table (RDS file) from make_sequence_table. + output_nochim_table_file: Path to save the chimera-removed ASV table (RDS file). + output_nochim_table_csv: Optional path to save the chimera-removed ASV table as a CSV file. + method: The method to use for chimera removal. "consensus" (default) or "pooled". + multithread: If TRUE, multithreading is enabled. Can also be an integer specifying number of threads. + verbose: If TRUE, print verbose output. + + Returns: + A dictionary containing command execution details, stdout, stderr, and paths to output files. + """ + # Input validation + if not seq_table_file.is_file(): + raise FileNotFoundError(f"Sequence table file not found: {seq_table_file}") + if seq_table_file.suffix != ".rds": + raise ValueError("seq_table_file must have a .rds extension.") + if output_nochim_table_file.suffix != ".rds": + raise ValueError("output_nochim_table_file must have a .rds extension.") + output_nochim_table_file.parent.mkdir(parents=True, exist_ok=True) + if output_nochim_table_csv: + if output_nochim_table_csv.suffix != ".csv": + raise ValueError("output_nochim_table_csv must have a .csv extension.") + output_nochim_table_csv.parent.mkdir(parents=True, exist_ok=True) + if method not in ["consensus", "pooled"]: + raise ValueError(f"Invalid method: {method}. Must be 'consensus' or 'pooled'.") + + # Prepare R script content + r_script_lines = [ + "library(dada2)", + "seq_table <- readRDS('" + str(seq_table_file) + "')", + "nochim_file <- '" + str(output_nochim_table_file) + "'", + ] + + bimera_params = [ + f"method='{method}'", + ] + if multithread: + if isinstance(multithread, bool): + bimera_params.append("multithread=TRUE") + else: + bimera_params.append(f"multithread={multithread}") + if verbose: + bimera_params.append("verbose=TRUE") + + r_script_lines.append( + f"seq_table_nochim <- removeBimeraDenovo(seq_table, {', '.join(bimera_params)})" + ) + r_script_lines.append(f"saveRDS(seq_table_nochim, file=nochim_file)") + + output_files = [str(output_nochim_table_file)] + if output_nochim_table_csv: + r_script_lines.append(f"write.csv(seq_table_nochim, file='{str(output_nochim_table_csv)}', row.names=TRUE)") + output_files.append(str(output_nochim_table_csv)) + + r_script_content = "\n".join(r_script_lines) + + result = _run_r_script(r_script_content, output_nochim_table_file.parent) + result["output_files"] = output_files + return result + +@mcp.tool() +def assign_taxonomy( + seq_table_file: Path, + ref_fasta_file: Path, + output_taxonomy_file: Path, + output_taxonomy_csv: Optional[Path] = None, + min_boot: int = 50, + multithread: Union[bool, int] = False, + try_rc: bool = False, + verbose: bool = False, +) -> dict: + """ + Assigns taxonomy to ASVs using the dada2 assignTaxonomy function. + + Args: + seq_table_file: Path to the ASV table (RDS file) from make_sequence_table or remove_bimera_denovo. + ref_fasta_file: Path to the reference FASTA file for taxonomic assignment (e.g., SILVA, RDP). + output_taxonomy_file: Path to save the taxonomy table (RDS file). + output_taxonomy_csv: Optional path to save the taxonomy table as a CSV file. + min_boot: Minimum bootstrap confidence for assigning a taxonomic level. + multithread: If TRUE, multithreading is enabled. Can also be an integer specifying number of threads. + try_rc: If TRUE, the reverse-complement of each ASV is also used for classification. + verbose: If TRUE, print verbose output. + + Returns: + A dictionary containing command execution details, stdout, stderr, and paths to output files. + """ + # Input validation + if not seq_table_file.is_file(): + raise FileNotFoundError(f"Sequence table file not found: {seq_table_file}") + if seq_table_file.suffix != ".rds": + raise ValueError("seq_table_file must have a .rds extension.") + if not ref_fasta_file.is_file(): + raise FileNotFoundError(f"Reference FASTA file not found: {ref_fasta_file}") + if output_taxonomy_file.suffix != ".rds": + raise ValueError("output_taxonomy_file must have a .rds extension.") + output_taxonomy_file.parent.mkdir(parents=True, exist_ok=True) + if output_taxonomy_csv: + if output_taxonomy_csv.suffix != ".csv": + raise ValueError("output_taxonomy_csv must have a .csv extension.") + output_taxonomy_csv.parent.mkdir(parents=True, exist_ok=True) + if not (0 <= min_boot <= 100): + raise ValueError("min_boot must be between 0 and 100.") + + # Prepare R script content + r_script_lines = [ + "library(dada2)", + "seq_table <- readRDS('" + str(seq_table_file) + "')", + "ref_fasta <- '" + str(ref_fasta_file) + "'", + "tax_file <- '" + str(output_taxonomy_file) + "'", + ] + + assign_params = [ + f"minBoot={min_boot}", + f"tryRC={str(try_rc).upper()}", + ] + if multithread: + if isinstance(multithread, bool): + assign_params.append("multithread=TRUE") + else: + assign_params.append(f"multithread={multithread}") + if verbose: + assign_params.append("verbose=TRUE") + + r_script_lines.append( + f"taxa <- assignTaxonomy(seq_table, ref_fasta, {', '.join(assign_params)})" + ) + r_script_lines.append(f"saveRDS(taxa, file=tax_file)") + + output_files = [str(output_taxonomy_file)] + if output_taxonomy_csv: + r_script_lines.append(f"write.csv(taxa, file='{str(output_taxonomy_csv)}', row.names=TRUE)") + output_files.append(str(output_taxonomy_csv)) + + r_script_content = "\n".join(r_script_lines) + + result = _run_r_script(r_script_content, output_taxonomy_file.parent) + result["output_files"] = output_files + return result + +@mcp.tool() +def plot_quality_profile( + fastq_file: Path, + output_plot_file: Path, + n_reads: int = 1000000, +) -> dict: + """ + Generates a quality profile plot for a FASTQ file using dada2's plotQualityProfile. + + Args: + fastq_file: Path to the FASTQ file (raw or filtered). + output_plot_file: Path to save the quality profile plot (e.g., .png, .pdf). + n_reads: The number of reads to sample from the FASTQ file for plotting. + + Returns: + A dictionary containing command execution details, stdout, stderr, and the path to the output plot file. + """ + # Input validation + if not fastq_file.is_file(): + raise FileNotFoundError(f"FASTQ file not found: {fastq_file}") + if output_plot_file.suffix not in [".png", ".pdf", ".jpeg", ".tiff"]: + raise ValueError("output_plot_file must have a .png, .pdf, .jpeg, or .tiff extension.") + if n_reads <= 0: + raise ValueError("n_reads must be a positive integer.") + output_plot_file.parent.mkdir(parents=True, exist_ok=True) + + # Prepare R script content + r_script_lines = [ + "library(dada2)", + "fastq_file <- '" + str(fastq_file) + "'", + "plot_file <- '" + str(output_plot_file) + "'", + ] + + # Determine plotting device based on suffix + if output_plot_file.suffix == ".png": + r_script_lines.append(f"png(plot_file, width=800, height=600)") + elif output_plot_file.suffix == ".pdf": + r_script_lines.append(f"pdf(plot_file, width=10, height=8)") + elif output_plot_file.suffix == ".jpeg": + r_script_lines.append(f"jpeg(plot_file, width=800, height=600)") + elif output_plot_file.suffix == ".tiff": + r_script_lines.append(f"tiff(plot_file, width=800, height=600)") + + r_script_lines.append(f"plotQualityProfile(fastq_file, n={n_reads})") + r_script_lines.append("dev.off()") # Close the plotting device + + r_script_content = "\n".join(r_script_lines) + + result = _run_r_script(r_script_content, output_plot_file.parent) + result["output_files"] = [str(output_plot_file)] + return result + +@mcp.tool() +def plot_errors( + error_model_file: Path, + output_plot_file: Path, +) -> dict: + """ + Generates an error rate plot from a learned error model using dada2's plotErrors. + + Args: + error_model_file: Path to the learned error model (RDS file) from learn_errors. + output_plot_file: Path to save the error plot (e.g., .png, .pdf). + + Returns: + A dictionary containing command execution details, stdout, stderr, and the path to the output plot file. + """ + # Input validation + if not error_model_file.is_file(): + raise FileNotFoundError(f"Error model file not found: {error_model_file}") + if error_model_file.suffix != ".rds": + raise ValueError("error_model_file must have a .rds extension.") + if output_plot_file.suffix not in [".png", ".pdf", ".jpeg", ".tiff"]: + raise ValueError("output_plot_file must have a .png, .pdf, .jpeg, or .tiff extension.") + output_plot_file.parent.mkdir(parents=True, exist_ok=True) + + # Prepare R script content + r_script_lines = [ + "library(dada2)", + "err <- readRDS('" + str(error_model_file) + "')", + "plot_file <- '" + str(output_plot_file) + "'", + ] + + # Determine plotting device based on suffix + if output_plot_file.suffix == ".png": + r_script_lines.append(f"png(plot_file, width=800, height=600)") + elif output_plot_file.suffix == ".pdf": + r_script_lines.append(f"pdf(plot_file, width=10, height=8)") + elif output_plot_file.suffix == ".jpeg": + r_script_lines.append(f"jpeg(plot_file, width=800, height=600)") + elif output_plot_file.suffix == ".tiff": + r_script_lines.append(f"tiff(plot_file, width=800, height=600)") + + r_script_lines.append(f"plotErrors(err, nominalQ=TRUE)") + r_script_lines.append("dev.off()") # Close the plotting device + + r_script_content = "\n".join(r_script_lines) + + result = _run_r_script(r_script_content, output_plot_file.parent) + result["output_files"] = [str(output_plot_file)] + return result \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dada2/app/bioconductor-dada2_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dada2/app/bioconductor-dada2_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..06942b233e54b314273dd7286612ab4fff120a6c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dada2/app/bioconductor-dada2_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-dada2/app/bioconductor-dada2_server.py') +SERVER_NAME = 'biosci_bioconductor_dada2' + + +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-dada2/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dada2/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dada2/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dada2/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dada2/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..04eceaaf308ba5bafb83003b54e5489155d995c0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dada2/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-dada2: + build: . + image: mcp-bioconductor-dada2:latest + container_name: mcp-bioconductor-dada2 + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-dada2 + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dada2/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dada2/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8a4a34928a005c4265f2e6c7ea67ed4817f8c92a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dada2/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-dada2 + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dada2/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dada2/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dada2/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-data-packages/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-data-packages/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..58d8e02b0aef74db7e2e9514bae607a6208870c7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-data-packages/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-data-packages via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-data-packages -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-data-packages_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-data-packages_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-data-packages_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-data-packages/app/bioconductor-data-packages_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-data-packages/app/bioconductor-data-packages_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d7bc038912f0ae264c8aab33ce0f658769149f8f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-data-packages/app/bioconductor-data-packages_server.py @@ -0,0 +1,246 @@ +from pathlib import Path +import subprocess +from typing import Optional, List, Union +import tempfile +import os + +@mcp.tool() +def install_bioconductor_data_package( + package_name: str, + lib_path: Optional[str] = None, + update: bool = False, + ask: bool = False, + force: bool = False, + version: Optional[str] = None +): + """ + Installs a Bioconductor data package using the R BiocManager infrastructure. + + Args: + package_name: The name of the Bioconductor data package to install (e.g., 'AnnotationHub', 'GenomicFeatures'). + lib_path: Specific library path where the package should be installed. + update: Whether to update all dependencies during installation. + ask: Whether to prompt the user before installing/updating. + force: Force installation even if the package is already installed. + version: Specific Bioconductor version to use (e.g., '3.16'). + """ + # Input validation + if not package_name: + return {"error": "package_name is required"} + + # Construct R command + r_cmds = ["if (!require('BiocManager', quietly = TRUE)) install.packages('BiocManager', repos='https://cloud.r-project.org')"] + + install_args = [f"'{package_name}'"] + if lib_path: + lib_p = Path(lib_path).resolve() + install_args.append(f"lib='{lib_p}'") + + install_args.append(f"update={'TRUE' if update else 'FALSE'}") + install_args.append(f"ask={'TRUE' if ask else 'FALSE'}") + install_args.append(f"force={'TRUE' if force else 'FALSE'}") + + if version: + r_cmds.append(f"BiocManager::install(version = '{version}', ask = FALSE)") + + r_cmds.append(f"BiocManager::install({', '.join(install_args)})") + + full_r_script = "; ".join(r_cmds) + + try: + result = subprocess.run( + ["Rscript", "-e", full_r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e \"{full_r_script}\"", + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript -e \"{full_r_script}\"", + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def list_bioconductor_data_packages( + version: Optional[str] = None, + grep_pattern: Optional[str] = None +): + """ + Lists available Bioconductor data packages for a specific version. + + Args: + version: Bioconductor version to query (e.g., '3.16'). If None, uses the current version. + grep_pattern: Optional pattern to filter the package list. + """ + r_cmds = ["if (!require('BiocManager', quietly = TRUE)) install.packages('BiocManager', repos='https://cloud.r-project.org')"] + + if version: + r_cmds.append(f"pkgs <- BiocManager::available(version = '{version}')") + else: + r_cmds.append("pkgs <- BiocManager::available()") + + # Filter for ExperimentData or AnnotationData if possible, or just return all + r_cmds.append("print(pkgs)") + + full_r_script = "; ".join(r_cmds) + + try: + result = subprocess.run( + ["Rscript", "-e", full_r_script], + capture_output=True, + text=True, + check=True + ) + + output = result.stdout + if grep_pattern: + lines = [line for line in output.split('\n') if grep_pattern.lower() in line.lower()] + output = '\n'.join(lines) + + return { + "command_executed": "Rscript BiocManager::available()", + "stdout": output, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stderr": e.stderr + } + +@mcp.tool() +def download_bioconductor_data_file( + url: str, + output_path: str, + use_curl: bool = True +): + """ + Downloads a specific Bioconductor data file or tarball using curl. + + Args: + url: The direct URL to the Bioconductor data resource. + output_path: The local path where the file should be saved. + use_curl: Whether to use curl (default) or standard download methods. + """ + out_p = Path(output_path) + # Ensure directory exists + out_p.parent.mkdir(parents=True, exist_ok=True) + + cmd = ["curl", "-L", url, "-o", str(out_p)] if use_curl else ["wget", url, "-O", str(out_p)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_file": str(out_p.resolve()) + } + except subprocess.CalledProcessError as e: + return { + "error": f"Download failed: {str(e)}", + "stderr": e.stderr + } + +@mcp.tool() +def parse_bioconductor_yaml_metadata( + yaml_file_path: str, + query: str = "." +): + """ + Parses Bioconductor data package metadata stored in YAML format using yq. + + Args: + yaml_file_path: Path to the YAML file containing package metadata. + query: The yq query string to extract specific information (default is "." for everything). + """ + yaml_p = Path(yaml_file_path) + if not yaml_p.exists(): + return {"error": f"File not found: {yaml_file_path}"} + + try: + # Using yq to parse the metadata + result = subprocess.run( + ["yq", query, str(yaml_p)], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"yq {query} {yaml_file_path}", + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": f"yq execution failed: {str(e)}", + "stderr": e.stderr + } + +@mcp.tool() +def search_bioconductor_data_packages( + query: str +): + """ + Searches for Bioconductor data packages matching a specific query string. + + Args: + query: The search term (e.g., 'H. sapiens', 'methylation', 'scRNA-seq'). + """ + if not query: + return {"error": "Query string is required"} + + r_script = f""" + if (!require('BiocManager', quietly = TRUE)) install.packages('BiocManager', repos='https://cloud.r-project.org'); + pkgs <- BiocManager::available(); + matches <- pkgs[grep('{query}', pkgs, ignore.case = TRUE)]; + cat(matches, sep='\\n'); + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "query": query, + "results": result.stdout.splitlines(), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stderr": e.stderr + } + +@mcp.tool() +def get_bioconductor_version_info(): + """ + Retrieves the current Bioconductor and R version information. + """ + r_script = "if (!require('BiocManager', quietly = TRUE)) install.packages('BiocManager', repos='https://cloud.r-project.org'); BiocManager::version()" + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "bioconductor_version": result.stdout.strip(), + "r_version": subprocess.run(["R", "--version"], capture_output=True, text=True).stdout.splitlines()[0] + } + except subprocess.CalledProcessError as e: + return {"error": str(e)} \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-data-packages/app/bioconductor-data-packages_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-data-packages/app/bioconductor-data-packages_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fca4fe7df56bc9e06f198613b96152157e27a49b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-data-packages/app/bioconductor-data-packages_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-data-packages/app/bioconductor-data-packages_server.py') +SERVER_NAME = 'biosci_bioconductor_data_packages' + + +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-data-packages/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-data-packages/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-data-packages/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-data-packages/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-data-packages/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..0d8d5a3e5ea75f6a8a9d10e4afddae0f74a6bd20 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-data-packages/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-data-packages: + build: . + image: mcp-bioconductor-data-packages:latest + container_name: mcp-bioconductor-data-packages + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-data-packages + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-data-packages/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-data-packages/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fae089583404a67cf5f48b9cab9c8e51f9c0eb24 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-data-packages/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-data-packages + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-data-packages/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-data-packages/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-data-packages/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decipher/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decipher/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d5c0a1b5a4acc0ab1e4f03c7158652c8bdb04b3e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decipher/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-decipher via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-decipher -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-decipher_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-decipher_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-decipher_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decipher/app/bioconductor-decipher_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decipher/app/bioconductor-decipher_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4d8adaa48f3ed68bcbb3f49dc0617d150ffdaacd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decipher/app/bioconductor-decipher_server.py @@ -0,0 +1,431 @@ +import subprocess +import tempfile +import textwrap +from pathlib import Path +from typing import Dict, Any, Optional, List + +# MCP decorators are used directly as the execution environment provides them. +# In a local development setup, you would use: +# from mcp import tool as mcp + +def _run_r_script( + r_script_content: str, + args: List[str], + output_files_map: Dict[str, Path] +) -> Dict[str, Any]: + """ + Helper function to execute an R script and return a structured result. + """ + cmd = ["Rscript", "-"] + args + # Create a user-friendly representation of the command + command_executed = f"echo '{r_script_content}' | Rscript - {' '.join(args)}" + + try: + result = subprocess.run( + cmd, + input=r_script_content, + capture_output=True, + text=True, + check=True, + ) + + # Verify that all expected output files were created and are not empty + for key, path in output_files_map.items(): + if not path.is_file() or path.stat().st_size == 0: + raise FileNotFoundError( + f"Expected output file '{path}' was not created or is empty. " + f"R script stderr: {result.stderr}" + ) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {k: str(v) for k, v in output_files_map.items()}, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode, + } + except FileNotFoundError as e: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": str(e), + "error": "An output file was not generated as expected.", + } + + +@mcp.tool() +def align_sequences( + input_fasta: Path, + substitution_matrix: Optional[str] = None, + gap_opening: float = 10.0, + gap_extension: float = 0.1, + processors: int = 1, +) -> Dict[str, Any]: + """ + Performs multiple sequence alignment on sequences using DECIPHER's AlignSeqs. + + This tool aligns a set of DNA, RNA, or amino acid sequences provided in a FASTA file. + It automatically detects the sequence type. + + Args: + input_fasta: Path to the input FASTA file containing unaligned sequences. + substitution_matrix: The substitution matrix to use (e.g., 'BLOSUM62', 'PAM40'). + If None, DECIPHER will choose a default based on sequence type. + gap_opening: The penalty for opening a gap. + gap_extension: The penalty for extending a gap. + processors: The number of processors to use for alignment. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a map of output files. + """ + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + if processors < 1: + raise ValueError("Number of processors must be at least 1.") + + r_script = textwrap.dedent(""" + # Load required libraries + suppressPackageStartupMessages(library(DECIPHER)) + + # Get command line arguments + args <- commandArgs(trailingOnly = TRUE) + inputFile <- args[1] + outputFile <- args[2] + subMatrix <- if (args[3] == "NULL") NULL else args[3] + gapOpen <- as.numeric(args[4]) + gapExt <- as.numeric(args[5]) + procs <- as.integer(args[6]) + + # Read sequences (readBStringSet is generic for DNA, RNA, AA) + seqs <- readBStringSet(inputFile) + + # Perform alignment + cat("Starting sequence alignment...\\n", file = stderr()) + aligned_seqs <- AlignSeqs(seqs, + gapOpening = gapOpen, + gapExtension = gapExt, + substitutionMatrix = subMatrix, + processors = procs, + verbose = TRUE) + cat("Alignment complete.\\n", file = stderr()) + + # Write the aligned sequences to the output file + writeXStringSet(aligned_seqs, filepath = outputFile) + cat("Output written to", outputFile, "\\n", file = stderr()) + """) + + with tempfile.TemporaryDirectory() as temp_dir: + temp_path = Path(temp_dir) + output_aligned_fasta = temp_path / "aligned.fasta" + + args = [ + str(input_fasta.resolve()), + str(output_aligned_fasta.resolve()), + str(substitution_matrix) if substitution_matrix else "NULL", + str(gap_opening), + str(gap_extension), + str(processors), + ] + + return _run_r_script(r_script, args, {"aligned_fasta": output_aligned_fasta}) + + +@mcp.tool() +def find_chimeras( + input_fasta: Path, + processors: int = 1, +) -> Dict[str, Any]: + """ + Identifies chimeric sequences in a FASTA file using DECIPHER's isChimera. + + This tool screens a set of sequences (typically 16S rRNA amplicons) and + identifies which ones are likely to be chimeras formed during PCR. + + Args: + input_fasta: Path to the input FASTA file containing sequences to check. + processors: The number of processors to use for chimera detection. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a map of output files. + """ + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + if processors < 1: + raise ValueError("Number of processors must be at least 1.") + + r_script = textwrap.dedent(""" + suppressPackageStartupMessages(library(DECIPHER)) + + args <- commandArgs(trailingOnly = TRUE) + inputFile <- args[1] + outputFile <- args[2] + procs <- as.integer(args[3]) + + cat("Reading sequences...\\n", file = stderr()) + seqs <- readDNAStringSet(inputFile) + + cat("Finding chimeras...\\n", file = stderr()) + chimera_flags <- isChimera(seqs, processors = procs, verbose = TRUE) + + chimera_names <- names(seqs)[chimera_flags] + + cat(length(chimera_names), "chimeras found.\\n", file = stderr()) + writeLines(chimera_names, con = outputFile) + cat("Chimeric sequence names written to", outputFile, "\\n", file = stderr()) + """) + + with tempfile.TemporaryDirectory() as temp_dir: + temp_path = Path(temp_dir) + output_chimera_list = temp_path / "chimeric_sequences.txt" + + args = [ + str(input_fasta.resolve()), + str(output_chimera_list.resolve()), + str(processors), + ] + + return _run_r_script(r_script, args, {"chimera_list": output_chimera_list}) + + +@mcp.tool() +def classify_sequences( + query_fasta: Path, + training_set: Path, + confidence_threshold: float = 0.7, + processors: int = 1, +) -> Dict[str, Any]: + """ + Classifies sequences using a pre-trained DECIPHER model (IdTaxa). + + This tool assigns taxonomic classification to sequences based on a provided + training set file (e.g., SILVA, RDP, Greengenes). + + Args: + query_fasta: Path to the FASTA file of sequences to classify. + training_set: Path to the .RData file containing the training set object. + confidence_threshold: The minimum confidence required to assign a taxonomy. + processors: The number of processors to use for classification. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a map of output files. + """ + if not query_fasta.is_file(): + raise FileNotFoundError(f"Query FASTA file not found: {query_fasta}") + if not training_set.is_file(): + raise FileNotFoundError(f"Training set file not found: {training_set}") + if not 0.0 <= confidence_threshold <= 1.0: + raise ValueError("Confidence threshold must be between 0.0 and 1.0.") + if processors < 1: + raise ValueError("Number of processors must be at least 1.") + + r_script = textwrap.dedent(""" + suppressPackageStartupMessages(library(DECIPHER)) + + args <- commandArgs(trailingOnly = TRUE) + queryFile <- args[1] + trainingFile <- args[2] + outputFile <- args[3] + conf <- as.numeric(args[4]) + procs <- as.integer(args[5]) + + cat("Reading query sequences...\\n", file = stderr()) + seqs <- readDNAStringSet(queryFile) + + cat("Loading training set...\\n", file = stderr()) + load(trainingFile) # Assumes this loads an object named 'trainingSet' + + cat("Classifying sequences with IdTaxa...\\n", file = stderr()) + ids <- IdTaxa(seqs, trainingSet, threshold = conf, processors = procs, verbose = TRUE) + + # Format the output into a table + get_taxonomy <- function(x) { + if (length(x) > 0 && length(x[[1]]$taxon) > 0) { + paste(x[[1]]$taxon, collapse=";") + } else { + "Unclassified" + } + } + taxonomy_strings <- sapply(ids, get_taxonomy) + output_df <- data.frame(sequence_name = names(seqs), taxonomy = taxonomy_strings) + + cat("Writing classification results...\\n", file = stderr()) + write.table(output_df, file = outputFile, sep = "\\t", row.names = FALSE, quote = FALSE) + cat("Output written to", outputFile, "\\n", file = stderr()) + """) + + with tempfile.TemporaryDirectory() as temp_dir: + temp_path = Path(temp_dir) + output_classification_tsv = temp_path / "classification.tsv" + + args = [ + str(query_fasta.resolve()), + str(training_set.resolve()), + str(output_classification_tsv.resolve()), + str(confidence_threshold), + str(processors), + ] + + return _run_r_script(r_script, args, {"classification_results": output_classification_tsv}) + + +@mcp.tool() +def design_primers( + input_aligned_fasta: Path, + min_length: int = 18, + max_length: int = 25, + min_tm: float = 50.0, + max_tm: float = 65.0, + min_gc: float = 40.0, + max_gc: float = 60.0, + max_degeneracy: int = 4, + processors: int = 1, +) -> Dict[str, Any]: + """ + Designs group-specific PCR primers from an aligned FASTA file using DesignPrimers. + + Args: + input_aligned_fasta: Path to an aligned FASTA file of target sequences. + min_length: Minimum primer length. + max_length: Maximum primer length. + min_tm: Minimum melting temperature (°C). + max_tm: Maximum melting temperature (°C). + min_gc: Minimum GC content (percent). + max_gc: Maximum GC content (percent). + max_degeneracy: Maximum number of degenerate bases allowed in a primer. + processors: The number of processors to use. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a map of output files. + """ + if not input_aligned_fasta.is_file(): + raise FileNotFoundError(f"Input aligned FASTA file not found: {input_aligned_fasta}") + if processors < 1: + raise ValueError("Number of processors must be at least 1.") + + r_script = textwrap.dedent(""" + suppressPackageStartupMessages(library(DECIPHER)) + + args <- commandArgs(trailingOnly = TRUE) + inputFile <- args[1] + outputFile <- args[2] + minL <- as.integer(args[3]) + maxL <- as.integer(args[4]) + minTm <- as.numeric(args[5]) + maxTm <- as.numeric(args[6]) + minGC <- as.numeric(args[7]) + maxGC <- as.numeric(args[8]) + maxD <- as.integer(args[9]) + procs <- as.integer(args[10]) + + cat("Reading aligned sequences...\\n", file = stderr()) + seqs <- readDNAStringSet(inputFile) + + cat("Designing primers...\\n", file = stderr()) + primers <- DesignPrimers( + seqs, minLength = minL, maxLength = maxL, minTm = minTm, maxTm = maxTm, + minGC = minGC, maxGC = maxGC, maxDegeneracy = maxD, + processors = procs, verbose = TRUE + ) + + cat(nrow(primers), "candidate primers found.\\n", file = stderr()) + write.table(primers, file = outputFile, sep = "\\t", row.names = FALSE, quote = FALSE) + cat("Primer table written to", outputFile, "\\n", file = stderr()) + """) + + with tempfile.TemporaryDirectory() as temp_dir: + temp_path = Path(temp_dir) + output_primers_tsv = temp_path / "primers.tsv" + + args = [ + str(input_aligned_fasta.resolve()), + str(output_primers_tsv.resolve()), + str(min_length), str(max_length), str(min_tm), str(max_tm), + str(min_gc), str(max_gc), str(max_degeneracy), str(processors), + ] + + return _run_r_script(r_script, args, {"designed_primers": output_primers_tsv}) + + +@mcp.tool() +def design_probes( + input_aligned_fasta: Path, + min_length: int = 18, + max_length: int = 50, + min_tm: float = 60.0, + max_tm: float = 80.0, + min_gc: float = 40.0, + max_gc: float = 60.0, + max_degeneracy: int = 1, + processors: int = 1, +) -> Dict[str, Any]: + """ + Designs hybridization probes (e.g., for FISH) from an aligned FASTA file using DesignProbes. + + Args: + input_aligned_fasta: Path to an aligned FASTA file of target sequences. + min_length: Minimum probe length. + max_length: Maximum probe length. + min_tm: Minimum melting temperature (°C). + max_tm: Maximum melting temperature (°C). + min_gc: Minimum GC content (percent). + max_gc: Maximum GC content (percent). + max_degeneracy: Maximum number of degenerate bases allowed in a probe. + processors: The number of processors to use. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a map of output files. + """ + if not input_aligned_fasta.is_file(): + raise FileNotFoundError(f"Input aligned FASTA file not found: {input_aligned_fasta}") + if processors < 1: + raise ValueError("Number of processors must be at least 1.") + + r_script = textwrap.dedent(""" + suppressPackageStartupMessages(library(DECIPHER)) + + args <- commandArgs(trailingOnly = TRUE) + inputFile <- args[1] + outputFile <- args[2] + minL <- as.integer(args[3]) + maxL <- as.integer(args[4]) + minTm <- as.numeric(args[5]) + maxTm <- as.numeric(args[6]) + minGC <- as.numeric(args[7]) + maxGC <- as.numeric(args[8]) + maxD <- as.integer(args[9]) + procs <- as.integer(args[10]) + + cat("Reading aligned sequences...\\n", file = stderr()) + seqs <- readDNAStringSet(inputFile) + + cat("Designing probes...\\n", file = stderr()) + probes <- DesignProbes( + seqs, minLength = minL, maxLength = maxL, minTm = minTm, maxTm = maxTm, + minGC = minGC, maxGC = maxGC, maxDegeneracy = maxD, + processors = procs, verbose = TRUE + ) + + cat(nrow(probes), "candidate probes found.\\n", file = stderr()) + write.table(probes, file = outputFile, sep = "\\t", row.names = FALSE, quote = FALSE) + cat("Probe table written to", outputFile, "\\n", file = stderr()) + """) + + with tempfile.TemporaryDirectory() as temp_dir: + temp_path = Path(temp_dir) + output_probes_tsv = temp_path / "probes.tsv" + + args = [ + str(input_aligned_fasta.resolve()), + str(output_probes_tsv.resolve()), + str(min_length), str(max_length), str(min_tm), str(max_tm), + str(min_gc), str(max_gc), str(max_degeneracy), str(processors), + ] + + return _run_r_script(r_script, args, {"designed_probes": output_probes_tsv}) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decipher/app/bioconductor-decipher_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decipher/app/bioconductor-decipher_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..38c7b4af8abf546240648e89a8c0ab3ab949d7c5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decipher/app/bioconductor-decipher_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-decipher/app/bioconductor-decipher_server.py') +SERVER_NAME = 'biosci_bioconductor_decipher' + + +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-decipher/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decipher/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decipher/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decipher/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decipher/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..10686798d56c15c9f8d405ebcaf06e7ae62b78ca --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decipher/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-decipher: + build: . + image: mcp-bioconductor-decipher:latest + container_name: mcp-bioconductor-decipher + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-decipher + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decipher/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decipher/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..551ecb92037dae092073d842ab487868a010c2e4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decipher/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-decipher + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decipher/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decipher/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decipher/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontam/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontam/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b841dc6fd6491701fc9d712aa92aad2174e6eed7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontam/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-decontam via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-decontam -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-decontam_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-decontam_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-decontam_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontam/app/bioconductor-decontam_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontam/app/bioconductor-decontam_server.py new file mode 100644 index 0000000000000000000000000000000000000000..767d4d776904df6f2bf65df10670691ad533095d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontam/app/bioconductor-decontam_server.py @@ -0,0 +1,228 @@ +import subprocess +import tempfile +import shutil +from pathlib import Path +from typing import Optional, List, Literal + +# The R script that will be executed. It includes package installation, +# argument parsing, data loading, running decontam, and saving results. +R_SCRIPT_CONTENT = """ +# --- Package Installation --- +# Function to install a package if it's not already installed +install_if_missing <- function(pkg, repo = "cran") { + if (!requireNamespace(pkg, quietly = TRUE)) { + if (repo == "bioc") { + if (!requireNamespace("BiocManager", quietly = TRUE)) { + install.packages("BiocManager", repos = "http://cran.us.r-project.org") + } + BiocManager::install(pkg, update = FALSE, ask = FALSE) + } else { + install.packages(pkg, repos = "http://cran.us.r-project.org") + } + } +} + +# Install required packages from CRAN and Bioconductor +install_if_missing("argparse", repo = "cran") +install_if_missing("decontam", repo = "bioc") +install_if_missing("phyloseq", repo = "bioc") + +# --- Library Loading --- +suppressPackageStartupMessages(library(argparse)) +suppressPackageStartupMessages(library(decontam)) +suppressPackageStartupMessages(library(phyloseq)) + +# --- Argument Parsing --- +parser <- ArgumentParser(description="Run decontam's isContaminant function from a command line interface.") + +parser$add_argument("--feature_table", type="character", required=TRUE, help="Path to the feature table (CSV, features as columns, samples as rows).") +parser$add_argument("--metadata", type="character", required=TRUE, help="Path to the sample metadata file (CSV).") +parser$add_argument("--output_path", type="character", required=TRUE, help="Path to save the output results CSV file.") +parser$add_argument("--method", type="character", choices=c("prevalence", "frequency", "combined"), default="prevalence", help="Decontamination method to use.") +parser$add_argument("--neg_column", type="character", required=TRUE, help="Column name in metadata indicating negative controls (must contain TRUE/FALSE values).") +parser$add_argument("--conc_column", type="character", default=NULL, help="Column name in metadata for DNA concentration. Required for 'frequency' and 'combined' methods.") +parser$add_argument("--threshold", type="double", default=0.1, help="P-value threshold for contaminant classification.") +parser$add_argument("--normalize", action="store_true", default=FALSE, help="Normalize by library size (for frequency method). Pass this flag to enable.") +parser$add_argument("--detailed", action="store_true", default=FALSE, help="Return detailed output including p-values. Pass this flag to enable.") + +args <- parser$parse_args() + +# --- Data Loading and Validation --- +tryCatch({ + # The first column of the input CSVs is expected to be the sample/feature names + feature_table <- read.csv(args$feature_table, row.names=1, check.names=FALSE) +}, error = function(e) { + stop(paste("Error reading feature table:", e$message)) +}) + +tryCatch({ + metadata <- read.csv(args$metadata, row.names=1, check.names=FALSE) +}, error = function(e) { + stop(paste("Error reading metadata:", e$message)) +}) + +# Align samples between feature table and metadata to ensure they match +common_samples <- intersect(rownames(feature_table), rownames(metadata)) +if (length(common_samples) == 0) { + stop("No common samples found between feature table and metadata. Please check that sample names in the first column of both files match.") +} +feature_table <- feature_table[common_samples, , drop=FALSE] +metadata <- metadata[common_samples, , drop=FALSE] + +# Validate that required columns exist in the metadata +if (!args$neg_column %in% colnames(metadata)) { + stop(paste0("Negative control column '", args$neg_column, "' not found in metadata file.")) +} +if (args$method %in% c("frequency", "combined")) { + if (is.null(args$conc_column)) { + stop("A concentration column ('--conc_column') is required for the 'frequency' or 'combined' method.") + } + if (!args$conc_column %in% colnames(metadata)) { + stop(paste0("Concentration column '", args$conc_column, "' not found in metadata file.")) + } +} + +# --- Run Decontam --- +# Decontam requires a phyloseq object, which we construct from the input tables +otu <- otu_table(as.matrix(feature_table), taxa_are_rows=FALSE) +samdf <- sample_data(metadata) +physeq <- phyloseq(otu, samdf) + +# Prepare arguments for the isContaminant function call +is_contam_args <- list( + seqtab = physeq, + method = args$method, + neg = args$neg_column, + threshold = args$threshold, + detailed = args$detailed +) + +if (args$method %in% c("frequency", "combined")) { + is_contam_args$conc <- args$conc_column + is_contam_args$normalize <- args$normalize +} + +# Execute isContaminant and handle potential errors during its run +contam_df <- tryCatch({ + do.call(isContaminant, is_contam_args) +}, error = function(e) { + stop(paste("Error during decontam execution:", e$message)) +}) + +# --- Save Output --- +tryCatch({ + write.csv(contam_df, file=args$output_path, row.names=TRUE) +}, error = function(e) { + stop(paste("Error writing output file:", e$message)) +}) + +cat(paste("Decontam analysis complete. Results saved to", args$output_path, "\\n")) +""" + +@mcp.tool() +def is_contaminant( + feature_table: Path, + metadata: Path, + output_path: Path, + neg_column: str, + method: Literal["prevalence", "frequency", "combined"] = "prevalence", + conc_column: Optional[str] = None, + threshold: float = 0.1, + normalize: bool = True, + detailed: bool = False, +): + """ + Identifies contaminant sequences in sequencing data using the decontam R package. + + This tool wraps the isContaminant function from decontam, which identifies contaminants + based on two statistical methods: 'frequency' (correlation with DNA concentration) and + 'prevalence' (presence in negative controls). + + Args: + feature_table: Path to the feature table file (e.g., ASV/OTU table). + Format: CSV with samples as rows and features as columns. + The first column must contain unique sample IDs. + metadata: Path to the sample metadata file. + Format: CSV with samples as rows and metadata as columns. + The first column must contain sample IDs matching the feature table. + output_path: Path to save the output CSV file containing contaminant classifications. + neg_column: The name of the column in the metadata file that identifies negative + control samples. This column must contain boolean (TRUE/FALSE) values. + method: The statistical method for identifying contaminants. + 'prevalence': Identifies contaminants based on their higher prevalence in negative controls. + 'frequency': Identifies contaminants based on their inverse correlation with sample DNA concentration. + 'combined': A combination of both frequency and prevalence methods. + conc_column: The name of the column in the metadata file containing DNA concentrations. + Required if method is 'frequency' or 'combined'. + threshold: The p-value threshold for classifying a feature as a contaminant. + Features with a p-value below this threshold are classified as contaminants. + normalize: If True, normalize by library size in the 'frequency' method. + detailed: If True, the output will include detailed statistics (e.g., p-values) + for each feature instead of just the boolean contaminant classification. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not feature_table.is_file(): + raise FileNotFoundError(f"Feature table file not found: {feature_table}") + if not metadata.is_file(): + raise FileNotFoundError(f"Metadata file not found: {metadata}") + if not (0.0 <= threshold <= 1.0): + raise ValueError("Threshold must be a float between 0.0 and 1.0.") + if method in ["frequency", "combined"] and not conc_column: + raise ValueError("The 'conc_column' parameter is required for 'frequency' and 'combined' methods.") + + # Check for Rscript dependency + if not shutil.which("Rscript"): + raise RuntimeError("Rscript executable not found in PATH. Please ensure R is installed and accessible.") + + with tempfile.TemporaryDirectory() as temp_dir: + r_script_path = Path(temp_dir) / "run_decontam.R" + r_script_path.write_text(R_SCRIPT_CONTENT) + + # --- Command Construction --- + cmd = [ + "Rscript", + str(r_script_path), + "--feature_table", str(feature_table.resolve()), + "--metadata", str(metadata.resolve()), + "--output_path", str(output_path.resolve()), + "--method", method, + "--neg_column", neg_column, + "--threshold", str(threshold), + ] + + if conc_column: + cmd.extend(["--conc_column", conc_column]) + if normalize: + cmd.append("--normalize") + if detailed: + cmd.append("--detailed") + + # --- Subprocess Execution --- + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + # R can print errors to either stdout or stderr, so we combine them for a comprehensive error message. + error_message = ( + f"R script execution failed with exit code {e.returncode}.\n" + f"STDOUT:\n{e.stdout}\n" + f"STDERR:\n{e.stderr}\n" + ) + raise RuntimeError(error_message) from e + + return { + "command_executed": " ".join(cmd), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_path.resolve())] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontam/app/bioconductor-decontam_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontam/app/bioconductor-decontam_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2f5a280389044c874fb652806c1f90fefe800d13 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontam/app/bioconductor-decontam_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-decontam/app/bioconductor-decontam_server.py') +SERVER_NAME = 'biosci_bioconductor_decontam' + + +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-decontam/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontam/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontam/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontam/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontam/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c6ce8822731866aa0f4eb6b74685000567296134 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontam/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-decontam: + build: . + image: mcp-bioconductor-decontam:latest + container_name: mcp-bioconductor-decontam + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-decontam + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontam/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontam/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fb54043185521d18619255a22a22a8db8de09be4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontam/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-decontam + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontam/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontam/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontam/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontx/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontx/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..820ab9780370a368b6c65cf4a3dfb8651f02dc92 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontx/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-decontx via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-decontx -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-decontx_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-decontx_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-decontx_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontx/app/bioconductor-decontx_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontx/app/bioconductor-decontx_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1f7910b0003b3bc6928b53699877744209ebf73d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontx/app/bioconductor-decontx_server.py @@ -0,0 +1,326 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional + +# @mcp.tool() +def decontx( + x: Path, + output_prefix: str, + z: Optional[Path] = None, + batch: Optional[Path] = None, + max_iter: int = 500, + delta_a: float = 1.0, + delta_b: float = 10.0, + phi: Optional[Path] = None, + theta: Optional[Path] = None, + effective_length: Optional[Path] = None, + length_normalization: str = "tpm", + num_chains: int = 3, + num_cores: int = 1, + seed: int = 12345, + logfile: Optional[Path] = None, + verbose: bool = True, +): + """ + Estimate and remove RNA contamination in single-cell data using DecontX. + + This tool wraps the decontX R function to identify and remove contamination + from ambient RNA in single-cell RNA-seq count data. + + Args: + x: Path to the input count matrix file (e.g., CSV). Rows should be + genes and columns should be cells. The first column should contain + gene names. + output_prefix: Prefix for the output files. The directory will be + created if it doesn't exist. + z: Optional path to a file containing cell labels. One label per line. + batch: Optional path to a file containing batch labels. One label per line. + max_iter: Maximum number of iterations for the Gibbs sampler. + delta_a: The first concentration parameter for the Dirichlet prior on + contamination levels. + delta_b: The second concentration parameter for the Dirichlet prior on + contamination levels. + phi: Optional path to a file containing the background contamination + distribution. If not provided, it will be estimated. + theta: Optional path to a file containing the native expression + distribution for each cell. If not provided, it will be estimated. + effective_length: Optional path to a file containing effective transcript + lengths for length normalization. + length_normalization: The length normalization method to be used. + One of 'tpm', 'fpm', 'fpkm', 'none'. + num_chains: The number of MCMC chains to run. + num_cores: The number of cores to use for parallel processing. + seed: The seed for the random number generator. + logfile: Optional path to a file where logs will be written. + verbose: If True, print progress messages to stderr. + """ + # --- Input Validation --- + if not x.is_file(): + raise FileNotFoundError(f"Input count matrix file not found: {x}") + if z and not z.is_file(): + raise FileNotFoundError(f"Cell labels file not found: {z}") + if batch and not batch.is_file(): + raise FileNotFoundError(f"Batch labels file not found: {batch}") + if phi and not phi.is_file(): + raise FileNotFoundError(f"Phi distribution file not found: {phi}") + if theta and not theta.is_file(): + raise FileNotFoundError(f"Theta distribution file not found: {theta}") + if effective_length and not effective_length.is_file(): + raise FileNotFoundError(f"Effective length file not found: {effective_length}") + + if max_iter <= 0: + raise ValueError("max_iter must be a positive integer.") + if num_chains <= 0: + raise ValueError("num_chains must be a positive integer.") + if num_cores <= 0: + raise ValueError("num_cores must be a positive integer.") + if delta_a <= 0 or delta_b <= 0: + raise ValueError("Delta parameters (delta_a, delta_b) must be positive.") + + allowed_norm = ["tpm", "fpm", "fpkm", "none"] + if length_normalization not in allowed_norm: + raise ValueError(f"length_normalization must be one of {allowed_norm}") + + # --- File and Path Handling --- + output_dir = Path(output_prefix).parent + output_dir.mkdir(parents=True, exist_ok=True) + + output_counts_path = Path(f"{output_prefix}_decontXcounts.csv") + output_contamination_path = Path(f"{output_prefix}_contamination.csv") + + with tempfile.TemporaryDirectory() as temp_dir: + script_path = Path(temp_dir) / "run_decontx.R" + + # --- R Script Generation --- + z_r = f'"{z.resolve()}"' if z else "NULL" + batch_r = f'"{batch.resolve()}"' if batch else "NULL" + phi_r = f'read.csv("{phi.resolve()}", header=FALSE)$V1' if phi else "NULL" + theta_r = f'read.csv("{theta.resolve()}", header=FALSE)$V1' if theta else "NULL" + effective_length_r = f'read.csv("{effective_length.resolve()}", header=FALSE)$V1' if effective_length else "NULL" + logfile_r = f'"{logfile.resolve()}"' if logfile else "NULL" + verbose_r = "TRUE" if verbose else "FALSE" + + r_script = f""" + library(decontX) + library(SingleCellExperiment) + library(Matrix) + + counts <- as.matrix(read.csv("{x.resolve()}", row.names=1, check.names=FALSE)) + + z_data <- if (!is.null({z_r})) read.csv({z_r}, header=FALSE, stringsAsFactors=TRUE)$V1 else NULL + batch_data <- if (!is.null({batch_r})) read.csv({batch_r}, header=FALSE, stringsAsFactors=TRUE)$V1 else NULL + phi_data <- if (!is.null({phi_r})) {phi_r} else NULL + theta_data <- if (!is.null({theta_r})) {theta_r} else NULL + effectiveLength_data <- if (!is.null({effective_length_r})) {effective_length_r} else NULL + + sce <- SingleCellExperiment(assays = list(counts = counts)) + + set.seed({seed}) + sce <- decontX( + x = sce, + z = z_data, + batch = batch_data, + maxIter = {max_iter}, + delta = c({delta_a}, {delta_b}), + phi = phi_data, + theta = theta_data, + effectiveLength = effectiveLength_data, + lengthNormalization = "{length_normalization}", + numChains = {num_chains}, + numCores = {num_cores}, + logfile = {logfile_r}, + verbose = {verbose_r} + ) + + decontaminated_counts <- decontXcounts(sce) + contamination_scores <- colData(sce)$decontX_contamination + results_df <- data.frame(contamination = contamination_scores, row.names = colnames(sce)) + + write.csv(as.matrix(decontaminated_counts), file="{output_counts_path.resolve()}", row.names=TRUE) + write.csv(results_df, file="{output_contamination_path.resolve()}", row.names=TRUE) + """ + + with open(script_path, "w") as f: + f.write(r_script) + + # --- Subprocess Execution --- + command = ["Rscript", str(script_path)] + command_str = " ".join(map(str, command)) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + + output_files = [ + str(output_counts_path), + str(output_contamination_path) + ] + + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "DecontX execution failed.", + "return_code": e.returncode + } + +# @mcp.tool() +def decontpro( + x: Path, + output_prefix: str, + z: Optional[Path] = None, + batch: Optional[Path] = None, + max_iter: int = 200, + delta_a: float = 1.0, + delta_b: float = 1.0, + gamma: float = 1.0, + beta: float = 1.0, + num_chains: int = 3, + num_cores: int = 1, + seed: int = 12345, + logfile: Optional[Path] = None, + verbose: bool = True, +): + """ + Estimate and remove protein contamination in CITE-seq data using DecontPro. + + This tool wraps the decontPro R function to identify and remove contamination + from ambient and background sources in single-cell protein expression data. + + Args: + x: Path to the input ADT count matrix file (e.g., CSV). Rows should be + proteins and columns should be cells. The first column should contain + protein names. + output_prefix: Prefix for the output files. The directory will be + created if it doesn't exist. + z: Optional path to a file containing cell labels. One label per line. + batch: Optional path to a file containing batch labels. One label per line. + max_iter: Maximum number of iterations for the Gibbs sampler. + delta_a: The first concentration parameter for the Dirichlet prior on + contamination levels. + delta_b: The second concentration parameter for the Dirichlet prior on + contamination levels. + gamma: The background contamination distribution parameter. + beta: The native expression distribution parameter for each cell. + num_chains: The number of MCMC chains to run. + num_cores: The number of cores to use for parallel processing. + seed: The seed for the random number generator. + logfile: Optional path to a file where logs will be written. + verbose: If True, print progress messages to stderr. + """ + # --- Input Validation --- + if not x.is_file(): + raise FileNotFoundError(f"Input ADT count matrix file not found: {x}") + if z and not z.is_file(): + raise FileNotFoundError(f"Cell labels file not found: {z}") + if batch and not batch.is_file(): + raise FileNotFoundError(f"Batch labels file not found: {batch}") + + if max_iter <= 0: + raise ValueError("max_iter must be a positive integer.") + if num_chains <= 0: + raise ValueError("num_chains must be a positive integer.") + if num_cores <= 0: + raise ValueError("num_cores must be a positive integer.") + if delta_a <= 0 or delta_b <= 0: + raise ValueError("Delta parameters (delta_a, delta_b) must be positive.") + if gamma <= 0 or beta <= 0: + raise ValueError("Gamma and Beta parameters must be positive.") + + # --- File and Path Handling --- + output_dir = Path(output_prefix).parent + output_dir.mkdir(parents=True, exist_ok=True) + + output_counts_path = Path(f"{output_prefix}_decontPro_counts.csv") + output_contamination_path = Path(f"{output_prefix}_decontPro_contamination.csv") + + with tempfile.TemporaryDirectory() as temp_dir: + script_path = Path(temp_dir) / "run_decontpro.R" + + # --- R Script Generation --- + z_r = f'"{z.resolve()}"' if z else "NULL" + batch_r = f'"{batch.resolve()}"' if batch else "NULL" + logfile_r = f'"{logfile.resolve()}"' if logfile else "NULL" + verbose_r = "TRUE" if verbose else "FALSE" + + r_script = f""" + library(decontX) + library(SingleCellExperiment) + library(Matrix) + + counts <- as.matrix(read.csv("{x.resolve()}", row.names=1, check.names=FALSE)) + + z_data <- if (!is.null({z_r})) read.csv({z_r}, header=FALSE, stringsAsFactors=TRUE)$V1 else NULL + batch_data <- if (!is.null({batch_r})) read.csv({batch_r}, header=FALSE, stringsAsFactors=TRUE)$V1 else NULL + + sce <- SingleCellExperiment(assays = list(counts = counts)) + + set.seed({seed}) + sce <- decontPro( + x = sce, + z = z_data, + batch = batch_data, + maxIter = {max_iter}, + delta = c({delta_a}, {delta_b}), + gamma = {gamma}, + beta = {beta}, + numChains = {num_chains}, + numCores = {num_cores}, + logfile = {logfile_r}, + verbose = {verbose_r} + ) + + decontaminated_counts <- metadata(sce)$decontPro$decontPro_counts + contamination_scores <- colData(sce)$decontPro_contamination + results_df <- data.frame(contamination = contamination_scores, row.names = colnames(sce)) + + write.csv(as.matrix(decontaminated_counts), file="{output_counts_path.resolve()}", row.names=TRUE) + write.csv(results_df, file="{output_contamination_path.resolve()}", row.names=TRUE) + """ + + with open(script_path, "w") as f: + f.write(r_script) + + # --- Subprocess Execution --- + command = ["Rscript", str(script_path)] + command_str = " ".join(map(str, command)) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + + output_files = [ + str(output_counts_path), + str(output_contamination_path) + ] + + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "DecontPro execution failed.", + "return_code": e.returncode + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontx/app/bioconductor-decontx_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontx/app/bioconductor-decontx_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8ac7d72c760f9ca4c2e538853c842051ee91acce --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontx/app/bioconductor-decontx_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-decontx/app/bioconductor-decontx_server.py') +SERVER_NAME = 'biosci_bioconductor_decontx' + + +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-decontx/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontx/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..54278d77b94074aee3436b6a210fcfbe16409ac2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontx/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-decontx: + build: . + image: mcp-bioconductor-decontx:latest + container_name: mcp-bioconductor-decontx + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-decontx + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontx/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontx/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..494d5271b04b4f4c9ab6c0e7d89038eb55a793e2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontx/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-decontx + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontx/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontx/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-decontx/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deconvobuddies/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deconvobuddies/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..af527c8333371e1f05ee96a65ee3d6f9e4fb7a13 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deconvobuddies/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-deconvobuddies via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-deconvobuddies -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-deconvobuddies_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-deconvobuddies_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-deconvobuddies_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deconvobuddies/app/bioconductor-deconvobuddies_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deconvobuddies/app/bioconductor-deconvobuddies_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ccb42b0cab7f07f03901adf82ff06d02bc0c4116 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deconvobuddies/app/bioconductor-deconvobuddies_server.py @@ -0,0 +1,278 @@ +import subprocess +import os +from pathlib import Path +from typing import Optional, List, Dict, Any + +@mcp.tool() +def get_mean_ratio( + sce_path: str, + cell_type_col: str, + assay_name: str = "logcounts", + output_path: str = "mean_ratio_stats.rds", +) -> Dict[str, Any]: + """ + Calculate the Mean Ratio for each gene and cell type in a SingleCellExperiment object. + This is a key metric for identifying specific marker genes for deconvolution. + """ + sce_p = Path(sce_path) + if not sce_p.exists(): + raise FileNotFoundError(f"Input SCE file not found: {sce_path}") + + # Construct R command + r_code = f""" + library(DeconvoBuddies) + library(SingleCellExperiment) + sce <- readRDS('{sce_path}') + stats <- get_mean_ratio(sce, cellType_col = '{cell_type_col}', assay_name = '{assay_name}') + saveRDS(stats, '{output_path}') + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"DeconvoBuddies::get_mean_ratio on {sce_path}", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_path] + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def find_markers_1v_all( + sce_path: str, + cell_type_col: str, + assay_name: str = "logcounts", + output_path: str = "findMarkers_stats.rds", +) -> Dict[str, Any]: + """ + Wrapper for scran::findMarkers to perform 1-vs-all comparisons for cell type marker identification. + """ + sce_p = Path(sce_path) + if not sce_p.exists(): + raise FileNotFoundError(f"Input SCE file not found: {sce_path}") + + r_code = f""" + library(DeconvoBuddies) + library(SingleCellExperiment) + sce <- readRDS('{sce_path}') + stats <- findMarkers_1vAll(sce, cellType_col = '{cell_type_col}', assay_name = '{assay_name}') + saveRDS(stats, '{output_path}') + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"DeconvoBuddies::findMarkers_1vAll on {sce_path}", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_path] + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def plot_marker_expression( + sce_path: str, + stats_path: str, + cell_type_col: str, + n_markers: int = 5, + assay_name: str = "logcounts", + output_plot: str = "marker_expression.pdf", +) -> Dict[str, Any]: + """ + Visualize the expression of top marker genes across cell types using violin plots. + """ + if n_markers <= 0: + raise ValueError("n_markers must be a positive integer") + + sce_p = Path(sce_path) + stats_p = Path(stats_path) + if not sce_p.exists() or not stats_p.exists(): + raise FileNotFoundError("Input SCE or Stats file not found.") + + r_code = f""" + library(DeconvoBuddies) + library(SingleCellExperiment) + library(ggplot2) + sce <- readRDS('{sce_path}') + stats <- readRDS('{stats_path}') + + # Get top markers + top_markers <- stats[stats$Rank <= {n_markers}, "gene"] + + plot <- plot_marker_express(sce, + stats, + cell_type_col = '{cell_type_col}', + n_genes = {n_markers}, + assay_name = '{assay_name}') + + ggsave('{output_plot}', plot, width = 10, height = 8) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "DeconvoBuddies::plot_marker_express", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_plot] + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def make_cell_colors( + cell_types: List[str], + palette: str = "hue_pal", + seed: int = 123, +) -> Dict[str, Any]: + """ + Generate a consistent color palette for cell types. + """ + cell_types_str = 'c("' + '","'.join(cell_types) + '")' + + r_code = f""" + library(DeconvoBuddies) + set.seed({seed}) + colors <- make_cell_colors(cell_types = {cell_types_str}, palette = '{palette}') + cat(jsonlite::toJSON(as.list(colors))) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "DeconvoBuddies::make_cell_colors", + "stdout": result.stdout, + "stderr": result.stderr, + "colors": result.stdout + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stderr": e.stderr + } + +@mcp.tool() +def plot_set_basis( + sce_path: str, + basis_matrix_path: str, + cell_type_col: str, + output_plot: str = "basis_plot.pdf", +) -> Dict[str, Any]: + """ + Plot the basis matrix (reference profile) to visualize the expression of markers in the reference. + """ + sce_p = Path(sce_path) + basis_p = Path(basis_matrix_path) + + if not sce_p.exists() or not basis_p.exists(): + raise FileNotFoundError("Input SCE or Basis Matrix file not found.") + + r_code = f""" + library(DeconvoBuddies) + library(SingleCellExperiment) + library(ggplot2) + sce <- readRDS('{sce_path}') + basis <- readRDS('{basis_matrix_path}') + + plot <- plot_set_basis(sce, basis, cellType_col = '{cell_type_col}') + ggsave('{output_plot}', plot, width = 8, height = 6) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "DeconvoBuddies::plot_set_basis", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_plot] + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def create_merged_sce( + sce_paths: List[str], + output_path: str = "merged_sce.rds", +) -> Dict[str, Any]: + """ + Merge multiple SingleCellExperiment objects into one, ensuring consistent metadata. + """ + if not sce_paths: + raise ValueError("List of SCE paths cannot be empty") + + for p in sce_paths: + if not Path(p).exists(): + raise FileNotFoundError(f"File not found: {p}") + + paths_r = 'c("' + '","'.join(sce_paths) + '")' + + r_code = f""" + library(SingleCellExperiment) + sce_list <- lapply({paths_r}, readRDS) + # Simple merge logic for SCE + merged_sce <- do.call(cbind, sce_list) + saveRDS(merged_sce, '{output_path}') + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "Manual SCE Merge via Rscript", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_path] + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deconvobuddies/app/bioconductor-deconvobuddies_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deconvobuddies/app/bioconductor-deconvobuddies_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9b6fd678c405d189d2a170bb68117fd2a418e682 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deconvobuddies/app/bioconductor-deconvobuddies_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-deconvobuddies/app/bioconductor-deconvobuddies_server.py') +SERVER_NAME = 'biosci_bioconductor_deconvobuddies' + + +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-deconvobuddies/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deconvobuddies/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deconvobuddies/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deconvobuddies/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deconvobuddies/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..3879582e1c4b2d6bfbc7c26d642832328bfc0e31 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deconvobuddies/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-deconvobuddies: + build: . + image: mcp-bioconductor-deconvobuddies:latest + container_name: mcp-bioconductor-deconvobuddies + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-deconvobuddies + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deconvobuddies/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deconvobuddies/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0939aef8616e2a4d908ea17157ad8e306e3bb61a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deconvobuddies/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-deconvobuddies + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deconvobuddies/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deconvobuddies/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deconvobuddies/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-delayedarray/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-delayedarray/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-delayedarray/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-delayedmatrixstats/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-delayedmatrixstats/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..727a460343f6fb737b5caace83184a909970a929 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-delayedmatrixstats/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-delayedmatrixstats via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-delayedmatrixstats -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-delayedmatrixstats_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-delayedmatrixstats_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-delayedmatrixstats_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-delayedmatrixstats/app/bioconductor-delayedmatrixstats_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-delayedmatrixstats/app/bioconductor-delayedmatrixstats_server.py new file mode 100644 index 0000000000000000000000000000000000000000..01b5e705c7ab447b86ebd6bd619f17de5ef099f1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-delayedmatrixstats/app/bioconductor-delayedmatrixstats_server.py @@ -0,0 +1,181 @@ +import subprocess +from pathlib import Path +from typing import List, Optional + +# In a real MCP environment, the 'mcp' module would be available. +# The following is a placeholder to make the code runnable for testing. +class _MCP: + def tool(self): + def decorator(f): + return f + return decorator +mcp = _MCP() + + +@mcp.tool() +def fastqc( + sequence_files: List[Path], + outdir: Optional[Path] = None, + extract: bool = True, + format: Optional[str] = None, + threads: int = 1, + contaminants: Optional[Path] = None, + adapters: Optional[Path] = None, + limits: Optional[Path] = None, + quiet: bool = False, + java_path: Optional[Path] = None, + min_length: Optional[int] = None, + max_length: Optional[int] = None, + max_memory: Optional[str] = None, + casava: bool = False, + nano: bool = False, + nofilter: bool = False, + nogroup: bool = False, + min_base_quality: Optional[int] = None, + read_group_size: Optional[int] = None, + kmers: Optional[int] = None, +): + """ + Run FastQC, a quality control tool for high throughput sequence data. + + This tool takes a set of sequence files and produces a quality control + report for each one, which can be used to assess the quality of raw data. + """ + # 1. Input Validation + if not sequence_files: + raise ValueError("At least one sequence file must be provided.") + + for seq_file in sequence_files: + if not seq_file.exists(): + raise FileNotFoundError(f"Input sequence file not found: {seq_file}") + + if format and format.lower() not in ["fastq", "bam", "sam"]: + raise ValueError("Invalid format specified. Must be one of 'fastq', 'bam', 'sam'.") + + if threads <= 0: + raise ValueError("Number of threads must be a positive integer.") + + for optional_file in [contaminants, adapters, limits, java_path]: + if optional_file and not optional_file.exists(): + raise FileNotFoundError(f"Optional file not found: {optional_file}") + + # 2. Command Construction + cmd = ["fastqc"] + + if outdir: + # Ensure output directory exists + outdir.mkdir(parents=True, exist_ok=True) + cmd.extend(["--outdir", str(outdir)]) + + if not extract: + cmd.append("--noextract") + + if format: + cmd.extend(["--format", format.lower()]) + + if threads > 1: + cmd.extend(["--threads", str(threads)]) + + if contaminants: + cmd.extend(["--contaminants", str(contaminants)]) + + if adapters: + cmd.extend(["--adapters", str(adapters)]) + + if limits: + cmd.extend(["--limits", str(limits)]) + + if quiet: + cmd.append("--quiet") + + if java_path: + cmd.extend(["--java", str(java_path)]) + + if min_length is not None: + cmd.extend(["--min_length", str(min_length)]) + + if max_length is not None: + cmd.extend(["--max_length", str(max_length)]) + + if max_memory: + cmd.extend(["--max_memory", str(max_memory)]) + + if casava: + cmd.append("--casava") + + if nano: + cmd.append("--nano") + + if nofilter: + cmd.append("--nofilter") + + if nogroup: + cmd.append("--nogroup") + + if min_base_quality is not None: + cmd.extend(["--min_base_quality", str(min_base_quality)]) + + if read_group_size is not None: + cmd.extend(["--read_group_size", str(read_group_size)]) + + if kmers is not None: + cmd.extend(["--kmers", str(kmers)]) + + cmd.extend([str(f) for f in sequence_files]) + command_executed = " ".join(cmd) + + # 3. Subprocess Execution and Error Handling + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except FileNotFoundError: + # This error occurs if the 'fastqc' executable is not in the system's PATH + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'fastqc' command not found. Please ensure FastQC is installed and in your PATH.", + "output_files": [], + "return_code": 127 + } + except subprocess.CalledProcessError as e: + # This error occurs if FastQC returns a non-zero exit code + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "return_code": e.returncode + } + + # 4. Discover and list output files + output_dir_path = outdir if outdir else sequence_files[0].parent + output_files = [] + for seq_file in sequence_files: + # FastQC output naming convention: strip common extensions and add _fastqc.zip/html + base_name = seq_file.name + for ext in ['.gz', '.bz2', '.txt', '.sam', '.bam', '.fastq', '.fq']: + if base_name.lower().endswith(ext): + base_name = base_name[:-len(ext)] + + zip_file = output_dir_path / f"{base_name}_fastqc.zip" + html_file = output_dir_path / f"{base_name}_fastqc.html" + + if zip_file.exists(): + output_files.append(str(zip_file)) + # The HTML file is inside the ZIP unless --noextract is used with an older FastQC + # or if --extract is used. We will primarily report the zip and the unzipped HTML if it exists. + if html_file.exists(): + output_files.append(str(html_file)) + + # 5. Structured Result Return + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": sorted(list(set(output_files))), # Ensure unique paths + "return_code": result.returncode + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-delayedmatrixstats/app/bioconductor-delayedmatrixstats_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-delayedmatrixstats/app/bioconductor-delayedmatrixstats_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..dd5138ada6ce46544b356eed4755a92080e8d7cf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-delayedmatrixstats/app/bioconductor-delayedmatrixstats_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-delayedmatrixstats/app/bioconductor-delayedmatrixstats_server.py') +SERVER_NAME = 'biosci_bioconductor_delayedmatrixstats' + + +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-delayedmatrixstats/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-delayedmatrixstats/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-delayedmatrixstats/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-delayedmatrixstats/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-delayedmatrixstats/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..639ad771950cf50d4867c1f9f233bfc20e285322 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-delayedmatrixstats/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-delayedmatrixstats: + build: . + image: mcp-bioconductor-delayedmatrixstats:latest + container_name: mcp-bioconductor-delayedmatrixstats + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-delayedmatrixstats + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-delayedmatrixstats/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-delayedmatrixstats/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0bc8b4b932138dfc95c27d2c84e87b006ad0ea06 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-delayedmatrixstats/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-delayedmatrixstats + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-delayedmatrixstats/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-delayedmatrixstats/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-delayedmatrixstats/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deseq2/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deseq2/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6ce2c11f459604c91a335ffbaba16221d791a713 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deseq2/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-deseq2 via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-deseq2 -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-deseq2_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-deseq2_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-deseq2_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deseq2/app/bioconductor-deseq2_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deseq2/app/bioconductor-deseq2_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e415a1165d8d953e2f5af3c66effaf76f3ef8c07 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deseq2/app/bioconductor-deseq2_server.py @@ -0,0 +1,291 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Dict, Any + +@mcp.tool() +def deseq2_differential_expression( + counts_path: str, + metadata_path: str, + design_formula: str, + output_results_path: str, + contrast_column: Optional[str] = None, + reference_level: Optional[str] = None, + treated_level: Optional[str] = None, + alpha: float = 0.05, + lfc_threshold: float = 0.0, + test_type: str = "Wald", + fit_type: str = "parametric", + reduced_formula: Optional[str] = None, + shrink_lfc: bool = True, + shrink_type: str = "apeglm" +): + """ + Performs differential expression analysis using DESeq2. + + Args: + counts_path: Path to the raw counts matrix (CSV/TSV, genes as rows, samples as columns). + metadata_path: Path to the sample metadata (CSV/TSV, samples as rows). + design_formula: The design formula (e.g., '~ condition' or '~ genotype + condition'). + output_results_path: Path where the results CSV will be saved. + contrast_column: The column in metadata to use for comparison. + reference_level: The baseline/control level in the contrast column. + treated_level: The treatment level in the contrast column. + alpha: Significance threshold (FDR). + lfc_threshold: Log2 fold change threshold for null hypothesis. + test_type: 'Wald' or 'LRT' (Likelihood Ratio Test). + fit_type: 'parametric', 'local', or 'mean'. + reduced_formula: Required if test_type is 'LRT' (e.g., '~ 1'). + shrink_lfc: Whether to apply Log2 Fold Change shrinkage. + shrink_type: Type of shrinkage estimator ('apeglm', 'ashr', or 'normal'). + """ + counts_p = Path(counts_path) + meta_p = Path(metadata_path) + out_p = Path(output_results_path) + + if not counts_p.exists(): + raise FileNotFoundError(f"Counts file not found: {counts_path}") + if not meta_p.exists(): + raise FileNotFoundError(f"Metadata file not found: {metadata_path}") + if test_type == "LRT" and not reduced_formula: + raise ValueError("reduced_formula is required when test_type is 'LRT'") + + # Construct R script + r_script = f""" + library(DESeq2) + + # Load data + counts <- read.csv("{counts_p}", row.names=1, check.names=FALSE) + coldata <- read.csv("{meta_p}", row.names=1, check.names=FALSE) + + # Ensure factors + for(col in colnames(coldata)) {{ + if(is.character(coldata[[col]])) coldata[[col]] <- as.factor(coldata[[col]]) + }} + + # Create DESeqDataSet + dds <- DESeqDataSetFromMatrix(countData=counts, colData=coldata, design=as.formula("{design_formula}")) + + # Run DESeq + if ("{test_type}" == "LRT") {{ + dds <- DESeq(dds, test="LRT", reduced=as.formula("{reduced_formula}"), fitType="{fit_type}") + }} else {{ + dds <- DESeq(dds, test="Wald", fitType="{fit_type}") + }} + + # Results extraction + if (!is.null("{contrast_column}") && !is.null("{reference_level}") && !is.null("{treated_level}")) {{ + res <- results(dds, contrast=c("{contrast_column}", "{treated_level}", "{reference_level}"), + alpha={alpha}, lfcThreshold={lfc_threshold}) + + if ({str(shrink_lfc).upper()}) {{ + # Shrinkage requires the coefficient name or contrast + # apeglm is preferred but requires 'coef' + res <- lfcShrink(dds, contrast=c("{contrast_column}", "{treated_level}", "{reference_level}"), + res=res, type="{shrink_type}") + }} + }} else {{ + res <- results(dds, alpha={alpha}, lfcThreshold={lfc_threshold}) + }} + + write.csv(as.data.frame(res), file="{out_p}") + """ + + with tempfile.NamedTemporaryFile(suffix=".R", mode="w", delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + try: + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_p)] + } + except subprocess.CalledProcessError as e: + return { + "error": "DESeq2 execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": " ".join(e.cmd) + } + finally: + Path(tmp_path).unlink(missing_ok=True) + +@mcp.tool() +def deseq2_transform_counts( + counts_path: str, + metadata_path: str, + design_formula: str, + output_path: str, + method: str = "vst", + blind: bool = True +): + """ + Transforms count data using Variance Stabilizing Transformation (VST) or Regularized Log (rlog). + Useful for PCA, clustering, and visualization. + + Args: + counts_path: Path to raw counts matrix. + metadata_path: Path to sample metadata. + design_formula: Design formula (e.g., '~ condition'). + output_path: Path to save the transformed matrix CSV. + method: Transformation method ('vst' or 'rlog'). + blind: Whether to perform transformation in a blind manner (independent of design). + """ + counts_p = Path(counts_path) + meta_p = Path(metadata_path) + out_p = Path(output_path) + + if method not in ["vst", "rlog"]: + raise ValueError("Method must be 'vst' or 'rlog'") + + r_script = f""" + library(DESeq2) + counts <- read.csv("{counts_p}", row.names=1, check.names=FALSE) + coldata <- read.csv("{meta_p}", row.names=1, check.names=FALSE) + dds <- DESeqDataSetFromMatrix(countData=counts, colData=coldata, design=as.formula("{design_formula}")) + + if ("{method}" == "vst") {{ + transformed <- vst(dds, blind={str(blind).upper()}) + }} else {{ + transformed <- rlog(dds, blind={str(blind).upper()}) + }} + + write.csv(assay(transformed), file="{out_p}") + """ + + with tempfile.NamedTemporaryFile(suffix=".R", mode="w", delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + try: + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_p)] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + finally: + Path(tmp_path).unlink(missing_ok=True) + +@mcp.tool() +def deseq2_get_normalized_counts( + counts_path: str, + metadata_path: str, + design_formula: str, + output_path: str, + normalization_type: str = "ratio" +): + """ + Calculates size factors and returns normalized counts. + + Args: + counts_path: Path to raw counts matrix. + metadata_path: Path to sample metadata. + design_formula: Design formula. + output_path: Path to save normalized counts CSV. + normalization_type: Method for size factor estimation ('ratio', 'poscounts', 'iterate'). + """ + counts_p = Path(counts_path) + meta_p = Path(metadata_path) + out_p = Path(output_path) + + r_script = f""" + library(DESeq2) + counts <- read.csv("{counts_p}", row.names=1, check.names=FALSE) + coldata <- read.csv("{meta_p}", row.names=1, check.names=FALSE) + dds <- DESeqDataSetFromMatrix(countData=counts, colData=coldata, design=as.formula("{design_formula}")) + dds <- estimateSizeFactors(dds, type="{normalization_type}") + norm_counts <- counts(dds, normalized=TRUE) + write.csv(norm_counts, file="{out_p}") + """ + + with tempfile.NamedTemporaryFile(suffix=".R", mode="w", delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + try: + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_p)] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + finally: + Path(tmp_path).unlink(missing_ok=True) + +@mcp.tool() +def deseq2_plot_pca( + counts_path: str, + metadata_path: str, + design_formula: str, + intgroup_columns: List[str], + output_plot_path: str, + ntop: int = 500 +): + """ + Generates a PCA plot from DESeq2 transformed data. + + Args: + counts_path: Path to raw counts matrix. + metadata_path: Path to sample metadata. + design_formula: Design formula. + intgroup_columns: List of columns in metadata to use for grouping/coloring. + output_plot_path: Path to save the PCA plot (PDF or PNG). + ntop: Number of top variable genes to use for PCA. + """ + counts_p = Path(counts_path) + meta_p = Path(metadata_path) + out_p = Path(output_plot_path) + + intgroup_r = 'c("' + '","'.join(intgroup_columns) + '")' + + r_script = f""" + library(DESeq2) + library(ggplot2) + counts <- read.csv("{counts_p}", row.names=1, check.names=FALSE) + coldata <- read.csv("{meta_p}", row.names=1, check.names=FALSE) + dds <- DESeqDataSetFromMatrix(countData=counts, colData=coldata, design=as.formula("{design_formula}")) + vsd <- vst(dds, blind=TRUE) + + pca_data <- plotPCA(vsd, intgroup={intgroup_r}, ntop={ntop}, returnData=TRUE) + percentVar <- round(100 * attr(pca_data, "percentVar")) + + p <- ggplot(pca_data, aes(PC1, PC2, color={intgroup_columns[0]})) + + geom_point(size=3) + + xlab(paste0("PC1: ", percentVar[1], "% variance")) + + ylab(paste0("PC2: ", percentVar[2], "% variance")) + + coord_fixed() + + theme_bw() + + ggsave("{out_p}", plot=p, device="{out_p.suffix[1:]}") + """ + + with tempfile.NamedTemporaryFile(suffix=".R", mode="w", delete=False) as tmp: + tmp.write(r_script) + tmp_path = tmp.name + + try: + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_p)] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + finally: + Path(tmp_path).unlink(missing_ok=True) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deseq2/app/bioconductor-deseq2_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deseq2/app/bioconductor-deseq2_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..99d92238817537bd2f32a6a1d11231a7817d3dd8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deseq2/app/bioconductor-deseq2_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-deseq2/app/bioconductor-deseq2_server.py') +SERVER_NAME = 'biosci_bioconductor_deseq2' + + +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-deseq2/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deseq2/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deseq2/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deseq2/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deseq2/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..44fca83c313aca169d4a672bc807c812c843473f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deseq2/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-deseq2: + build: . + image: mcp-bioconductor-deseq2:latest + container_name: mcp-bioconductor-deseq2 + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-deseq2 + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deseq2/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deseq2/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6e0fbe21343a08899e814e52812d2bb7e94709bd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deseq2/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-deseq2 + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deseq2/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deseq2/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-deseq2/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-despace/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-despace/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4da99cfeeacc2224edafb176136f0e1db9162e6c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-despace/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-despace via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-despace -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-despace_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-despace_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-despace_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-despace/app/bioconductor-despace_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-despace/app/bioconductor-despace_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8bc6f46ca09e1ca06ac407afca565ec6930f7136 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-despace/app/bioconductor-despace_server.py @@ -0,0 +1,295 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, List + +# MCP is a placeholder for the Model Context Protocol library. +# In a real environment, this would be: from mcp import tool +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') + +@mcp.tool() +def cluster_scrnaseq( + sc_object_path: Path, + output_rds_path: Path, + s_topics: int = 10, + n_top_genes: int = 2000, +) -> dict: + """ + Performs clustering on single-cell RNA-seq data as a preprocessing step for DeSpace. + + This tool wraps the `cluster_scRNAseq` function from the DeSpace R package. It takes a + Seurat object, identifies highly variable genes, performs dimensionality reduction, + and identifies clusters based on topic modeling. + + Args: + sc_object_path: Path to the input single-cell Seurat object (.rds file). + output_rds_path: Path to save the clustered single-cell Seurat object (.rds file). + s_topics: The number of topics (S) for topic modeling, representing putative cell types. + n_top_genes: Number of highly variable genes to use for clustering. + + Returns: + A dictionary containing the executed command, stdout, stderr, and the path to the output file. + """ + # --- Input Validation --- + if not sc_object_path.is_file(): + raise FileNotFoundError(f"Input single-cell object not found: {sc_object_path}") + if not output_rds_path.parent.exists(): + output_rds_path.parent.mkdir(parents=True, exist_ok=True) + logging.info(f"Created output directory: {output_rds_path.parent}") + + if s_topics <= 0: + raise ValueError("s_topics must be a positive integer.") + if n_top_genes <= 0: + raise ValueError("n_top_genes must be a positive integer.") + + # --- Command Construction --- + # This assumes a wrapper R script 'cluster_scrnaseq.R' is in the system's PATH. + cmd = [ + "Rscript", "cluster_scrnaseq.R", + "--sc_object_path", str(sc_object_path), + "--output_rds_path", str(output_rds_path), + "--s_topics", str(s_topics), + "--n_top_genes", str(n_top_genes), + ] + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + # --- Subprocess Execution --- + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + stdout = process.stdout + stderr = process.stderr + logging.info("Single-cell clustering completed successfully.") + except FileNotFoundError: + err_msg = "Error: 'Rscript' command not found. Please ensure R and the required wrapper scripts are in the system's PATH." + logging.error(err_msg) + return {"command_executed": command_executed, "stdout": "", "stderr": err_msg, "output_files": []} + except subprocess.CalledProcessError as e: + logging.error(f"Single-cell clustering failed with exit code {e.returncode}.") + return {"command_executed": command_executed, "stdout": e.stdout, "stderr": e.stderr, "output_files": []} + + # --- Structured Result Return --- + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_rds_path)] + } + +@mcp.tool() +def cluster_sp_data( + sp_object_path: Path, + output_rds_path: Path, + resolution: float = 0.8, +) -> dict: + """ + Performs clustering on spatial transcriptomics data as a preprocessing step for DeSpace. + + This tool wraps the `cluster_sp_data` function from the DeSpace R package. It takes a + spatial Seurat object, normalizes the data, finds variable features, and performs + graph-based clustering. + + Args: + sp_object_path: Path to the input spatial Seurat object (.rds file). + output_rds_path: Path to save the clustered spatial Seurat object (.rds file). + resolution: Clustering resolution for the Louvain algorithm. + + Returns: + A dictionary containing the executed command, stdout, stderr, and the path to the output file. + """ + # --- Input Validation --- + if not sp_object_path.is_file(): + raise FileNotFoundError(f"Input spatial object not found: {sp_object_path}") + if not output_rds_path.parent.exists(): + output_rds_path.parent.mkdir(parents=True, exist_ok=True) + logging.info(f"Created output directory: {output_rds_path.parent}") + + if resolution <= 0.0: + raise ValueError("resolution must be a positive float.") + + # --- Command Construction --- + # This assumes a wrapper R script 'cluster_sp_data.R' is in the system's PATH. + cmd = [ + "Rscript", "cluster_sp_data.R", + "--sp_object_path", str(sp_object_path), + "--output_rds_path", str(output_rds_path), + "--resolution", str(resolution), + ] + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + # --- Subprocess Execution --- + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + stdout = process.stdout + stderr = process.stderr + logging.info("Spatial data clustering completed successfully.") + except FileNotFoundError: + err_msg = "Error: 'Rscript' command not found. Please ensure R and the required wrapper scripts are in the system's PATH." + logging.error(err_msg) + return {"command_executed": command_executed, "stdout": "", "stderr": err_msg, "output_files": []} + except subprocess.CalledProcessError as e: + logging.error(f"Spatial data clustering failed with exit code {e.returncode}.") + return {"command_executed": command_executed, "stdout": e.stdout, "stderr": e.stderr, "output_files": []} + + # --- Structured Result Return --- + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_rds_path)] + } + +@mcp.tool() +def run_despace( + sc_object_path: Path, + sp_object_path: Path, + output_rds_path: Path, + sc_assay: str = "RNA", + sc_slot: str = "counts", + sp_assay: str = "Spatial", + sp_slot: str = "counts", + num_markers_sc: int = 10, + num_markers_sp: int = 10, + s_topics: int = 10, + n_top_genes: int = 2000, + resolution: float = 0.8, + sample_id: Optional[str] = None, + num_threads: int = 1, + save_model: bool = False, + model_path: Optional[Path] = None, +) -> dict: + """ + Runs the main DeSpace algorithm to integrate single-cell and spatial transcriptomics data. + + This tool wraps the `DeSpace` R function. It can perform clustering internally if not + already present in the input objects, or it can use pre-computed clusters. The main + output is a Seurat object with cell-type deconvolution results. + + Args: + sc_object_path: Path to the single-cell Seurat object (.rds file). + sp_object_path: Path to the spatial transcriptomics Seurat object (.rds file). + output_rds_path: Path to save the resulting Seurat object with DeSpace results. + sc_assay: Assay to use from the single-cell Seurat object. + sc_slot: Slot to use from the single-cell assay (e.g., 'counts', 'data'). + sp_assay: Assay to use from the spatial Seurat object. + sp_slot: Slot to use from the spatial assay (e.g., 'counts', 'data'). + num_markers_sc: Number of markers to use for each single-cell cluster. + num_markers_sp: Number of markers to use for each spatial cluster. + s_topics: The number of topics (S) for topic modeling, used if sc-data is not pre-clustered. + n_top_genes: Number of highly variable genes, used if sc-data is not pre-clustered. + resolution: Clustering resolution, used if sp-data is not pre-clustered. + sample_id: Optional identifier for the sample, used for saving the model. + num_threads: Number of parallel threads to use. + save_model: If True, save the trained DeSpace model. + model_path: Path to save the DeSpace model file. Required if save_model is True. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not sc_object_path.is_file(): + raise FileNotFoundError(f"Single-cell input file not found: {sc_object_path}") + if not sp_object_path.is_file(): + raise FileNotFoundError(f"Spatial input file not found: {sp_object_path}") + + if not output_rds_path.parent.exists(): + output_rds_path.parent.mkdir(parents=True, exist_ok=True) + logging.info(f"Created output directory: {output_rds_path.parent}") + + if num_markers_sc <= 0: + raise ValueError("num_markers_sc must be a positive integer.") + if num_markers_sp <= 0: + raise ValueError("num_markers_sp must be a positive integer.") + if s_topics <= 0: + raise ValueError("s_topics must be a positive integer.") + if n_top_genes <= 0: + raise ValueError("n_top_genes must be a positive integer.") + if resolution <= 0.0: + raise ValueError("resolution must be a positive float.") + if num_threads <= 0: + raise ValueError("num_threads must be a positive integer.") + + if save_model: + if model_path is None: + raise ValueError("model_path must be provided when save_model is True.") + if not model_path.parent.exists(): + model_path.parent.mkdir(parents=True, exist_ok=True) + logging.info(f"Created model output directory: {model_path.parent}") + + # --- Command Construction --- + # This assumes a wrapper R script 'run_despace.R' is in the system's PATH. + cmd = [ + "Rscript", "run_despace.R", + "--sc_object_path", str(sc_object_path), + "--sp_object_path", str(sp_object_path), + "--output_rds_path", str(output_rds_path), + "--sc_assay", sc_assay, + "--sc_slot", sc_slot, + "--sp_assay", sp_assay, + "--sp_slot", sp_slot, + "--num_markers_sc", str(num_markers_sc), + "--num_markers_sp", str(num_markers_sp), + "--s_topics", str(s_topics), + "--n_top_genes", str(n_top_genes), + "--resolution", str(resolution), + "--num_threads", str(num_threads), + ] + + if sample_id: + cmd.extend(["--sample_id", sample_id]) + + if save_model and model_path: + cmd.append("--save_model") + cmd.extend(["--model_path", str(model_path)]) + + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + # --- Subprocess Execution --- + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + stdout = process.stdout + stderr = process.stderr + logging.info("DeSpace execution completed successfully.") + except FileNotFoundError: + err_msg = "Error: 'Rscript' command not found. Please ensure R and the required wrapper scripts are in the system's PATH." + logging.error(err_msg) + return {"command_executed": command_executed, "stdout": "", "stderr": err_msg, "output_files": []} + except subprocess.CalledProcessError as e: + logging.error(f"DeSpace execution failed with exit code {e.returncode}.") + return {"command_executed": command_executed, "stdout": e.stdout, "stderr": e.stderr, "output_files": []} + + # --- Structured Result Return --- + output_files: List[str] = [str(output_rds_path)] + if save_model and model_path: + output_files.append(str(model_path)) + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-despace/app/bioconductor-despace_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-despace/app/bioconductor-despace_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b1496375634f56e629826d7f271e44e3937191b5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-despace/app/bioconductor-despace_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-despace/app/bioconductor-despace_server.py') +SERVER_NAME = 'biosci_bioconductor_despace' + + +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-despace/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-despace/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-despace/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-despace/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-despace/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7a02735107b0381e3e0a06f2c081e776f2bd05b3 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-despace/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-despace: + build: . + image: mcp-bioconductor-despace:latest + container_name: mcp-bioconductor-despace + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-despace + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-despace/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-despace/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..aa7dcfc187fbd6567c43123ac5cc15ac3a6a30d3 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-despace/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-despace + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-despace/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-despace/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-despace/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-diffbind/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-diffbind/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..688e4b88373ed30f5a74d5f62ced57b363eb1fc3 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-diffbind/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-diffbind via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-diffbind -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-diffbind_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-diffbind_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-diffbind_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-diffbind/app/bioconductor-diffbind_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-diffbind/app/bioconductor-diffbind_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9f16a20a5b3ff7d0a3aba7319b1b43abf16db445 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-diffbind/app/bioconductor-diffbind_server.py @@ -0,0 +1,261 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# @mcp.tool() +def run_diffbind( + sample_sheet: Path, + output_prefix: str, + method: str = "DBA_DESEQ2", + fdr_threshold: float = 0.05, + summits: Optional[int] = None, + min_overlap: int = 2, + use_summarize_overlaps: bool = False, + cores: int = 1, + plot_pca: bool = True, + plot_heatmap: bool = True, + plot_ma: bool = True, + plot_volcano: bool = True, +) -> dict: + """ + Performs differential binding analysis of ChIP-Seq peak data using DiffBind. + + This tool wraps the main DiffBind analysis workflow, including data loading, + read counting, normalization, contrast definition, differential analysis, + and reporting. + + Args: + sample_sheet: Path to the sample sheet CSV file. This file must contain + metadata for each sample. Essential columns include: SampleID, + Condition, Replicate, bamReads, and Peaks. Optional columns include + ControlID and bamControl for control reads. + output_prefix: Prefix for all output files (e.g., 'my_analysis'). + method: The differential analysis method to use. + Must be one of 'DBA_EDGER', 'DBA_DESEQ2', or 'DBA_LIMMA'. + fdr_threshold: FDR threshold for reporting significantly differentially + bound sites. + summits: Optional integer value. If set, peaks will be re-centered + around the point of greatest enrichment, with the size of the peak + extended to this value. If not provided, no re-centering is done. + min_overlap: The minimum number of peaksets a peak must be in to be + included in the global binding matrix. + use_summarize_overlaps: If True, use the more accurate but slower + `summarizeOverlaps` method for counting reads in peaks. + cores: Number of CPU cores to use for parallel processing. + plot_pca: If True, generate a PCA plot of the samples. + plot_heatmap: If True, generate a correlation heatmap. + plot_ma: If True, generate an MA plot for the contrast. + plot_volcano: If True, generate a volcano plot for the contrast. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list + of generated output files. + """ + # Input validation + if not sample_sheet.is_file(): + raise FileNotFoundError(f"Sample sheet not found at: {sample_sheet}") + + allowed_methods = ["DBA_EDGER", "DBA_DESEQ2", "DBA_LIMMA"] + if method not in allowed_methods: + raise ValueError(f"Method must be one of {allowed_methods}, not '{method}'.") + + if not (0 < fdr_threshold <= 1): + raise ValueError("fdr_threshold must be between 0 and 1.") + + if cores < 1: + raise ValueError("cores must be a positive integer.") + + if summits is not None and summits <= 0: + raise ValueError("summits must be a positive integer if specified.") + + r_script_content = """ + suppressPackageStartupMessages(library(optparse)) + suppressPackageStartupMessages(library(DiffBind)) + suppressPackageStartupMessages(library(BiocParallel)) + + option_list <- list( + make_option(c("-s", "--sampleSheet"), type="character", default=NULL, + help="Path to the sample sheet CSV file", metavar="character"), + make_option(c("-o", "--outputPrefix"), type="character", default="diffbind_results", + help="Prefix for output files", metavar="character"), + make_option(c("-m", "--method"), type="character", default="DBA_DESEQ2", + help="Differential analysis method (DBA_EDGER, DBA_DESEQ2, DBA_LIMMA)", metavar="character"), + make_option(c("-t", "--threshold"), type="double", default=0.05, + help="FDR threshold for reporting", metavar="double"), + make_option(c("--summits"), type="integer", default=NULL, + help="Re-center peaks to this size. If not provided, no re-centering is done.", metavar="integer"), + make_option(c("--minOverlap"), type="integer", default=2, + help="Minimum overlap for consensus peaks", metavar="integer"), + make_option(c("--useSummarizeOverlaps"), action="store_true", default=FALSE, + help="Use SummarizeOverlaps for counting"), + make_option(c("--cores"), type="integer", default=1, + help="Number of cores for parallel processing", metavar="integer"), + make_option(c("--plotPCA"), action="store_true", default=FALSE, help="Generate PCA plot"), + make_option(c("--plotHeatmap"), action="store_true", default=FALSE, help="Generate correlation heatmap"), + make_option(c("--plotMA"), action="store_true", default=FALSE, help="Generate MA plot"), + make_option(c("--plotVolcano"), action="store_true", default=FALSE, help="Generate Volcano plot") + ) + + opt_parser <- OptionParser(option_list=option_list) + opt <- parse_args(opt_parser) + + if (is.null(opt$sampleSheet)){ + print_help(opt_parser) + stop("Sample sheet file must be supplied.", call.=FALSE) + } + + # Set up parallel processing + if (opt$cores > 1) { + register(MulticoreParam(workers = opt$cores)) + cat(paste("Using", opt$cores, "cores for parallel processing.\\n")) + } + + # 1. Load data + cat("Loading sample sheet...\\n") + samples <- read.csv(opt$sampleSheet) + dbObj <- dba(sampleSheet=samples) + + # 2. Count reads + cat("Counting reads...\\n") + count_summits_val <- if (is.null(opt$summits)) FALSE else opt$summits + dbObj <- dba.count(dbObj, summits=count_summits_val, bUseSummarizeOverlaps=opt$useSummarizeOverlaps) + + # 3. Normalize + cat("Normalizing data...\\n") + dbObj <- dba.normalize(dbObj) + + # 4. Establish contrast + cat("Establishing contrast...\\n") + dbObj <- dba.contrast(dbObj, minMembers=opt$minOverlap) + + # 5. Perform analysis + cat(paste("Performing differential analysis with", opt$method, "...\\n")) + analysis_method <- switch(opt$method, + "DBA_EDGER"=DBA_EDGER, + "DBA_DESEQ2"=DBA_DESEQ2, + "DBA_LIMMA"=DBA_LIMMA, + stop("Invalid method specified")) + dbObj <- dba.analyze(dbObj, method=analysis_method) + + # 6. Report results + cat("Generating report...\\n") + report <- dba.report(dbObj, th=opt$threshold) + if (!is.null(report)) { + report_df <- as.data.frame(report) + report_file <- paste0(opt$outputPrefix, "_differential_report.csv") + write.csv(report_df, file=report_file, row.names=FALSE) + cat(paste("Report saved to", report_file, "\\n")) + } else { + cat("No significant results to report.\\n") + } + + + # 7. Plotting + if (opt$plotPCA) { + cat("Generating PCA plot...\\n") + pdf(paste0(opt$outputPrefix, "_pca.pdf")) + dba.plotPCA(dbObj, label=DBA_ID) + dev.off() + } + + if (opt$plotHeatmap) { + cat("Generating correlation heatmap...\\n") + pdf(paste0(opt$outputPrefix, "_correlation_heatmap.pdf")) + dba.plotHeatmap(dbObj) + dev.off() + } + + if (opt$plotMA) { + cat("Generating MA plot...\\n") + pdf(paste0(opt$outputPrefix, "_ma_plot.pdf")) + dba.plotMA(dbObj) + dev.off() + } + + if (opt$plotVolcano) { + cat("Generating Volcano plot...\\n") + pdf(paste0(opt$outputPrefix, "_volcano_plot.pdf")) + dba.plotVolcano(dbObj) + dev.off() + } + + cat("DiffBind analysis complete.\\n") + """ + + output_files = [] + with tempfile.NamedTemporaryFile(mode="w", suffix=".R", delete=False) as r_script: + r_script_path = r_script.name + r_script.write(r_script_content) + + try: + cmd = [ + "Rscript", + r_script_path, + "--sampleSheet", + str(sample_sheet), + "--outputPrefix", + output_prefix, + "--method", + method, + "--threshold", + str(fdr_threshold), + "--minOverlap", + str(min_overlap), + "--cores", + str(cores), + ] + + if summits is not None: + cmd.extend(["--summits", str(summits)]) + if use_summarize_overlaps: + cmd.append("--useSummarizeOverlaps") + if plot_pca: + cmd.append("--plotPCA") + if plot_heatmap: + cmd.append("--plotHeatmap") + if plot_ma: + cmd.append("--plotMA") + if plot_volcano: + cmd.append("--plotVolcano") + + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + # Collect output files + report_file = Path(f"{output_prefix}_differential_report.csv") + if report_file.exists(): + output_files.append(str(report_file)) + if plot_pca: + output_files.append(f"{output_prefix}_pca.pdf") + if plot_heatmap: + output_files.append(f"{output_prefix}_correlation_heatmap.pdf") + if plot_ma: + output_files.append(f"{output_prefix}_ma_plot.pdf") + if plot_volcano: + output_files.append(f"{output_prefix}_volcano_plot.pdf") + + # Verify that plot files were created + verified_files = [f for f in output_files if Path(f).exists()] + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": verified_files, + } + + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "DiffBind R script failed.", + "return_code": e.returncode, + } + finally: + Path(r_script_path).unlink() diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-diffbind/app/bioconductor-diffbind_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-diffbind/app/bioconductor-diffbind_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..86b8f70ef45877d5ec544d13b6193aca58b4b104 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-diffbind/app/bioconductor-diffbind_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-diffbind/app/bioconductor-diffbind_server.py') +SERVER_NAME = 'biosci_bioconductor_diffbind' + + +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-diffbind/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-diffbind/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-diffbind/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-diffbind/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-diffbind/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..18b3fc5e962c25d0514a55227a62185efbc6e09a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-diffbind/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-diffbind: + build: . + image: mcp-bioconductor-diffbind:latest + container_name: mcp-bioconductor-diffbind + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-diffbind + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-diffbind/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-diffbind/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..839a0d08388f697b8b465c52c817fde4915186d0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-diffbind/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-diffbind + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-diffbind/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-diffbind/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-diffbind/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dino/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dino/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6e82559b1698fd13bbb4072e5206c349eeaab3da --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dino/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-dino via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-dino -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-dino_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-dino_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-dino_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dino/app/bioconductor-dino_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dino/app/bioconductor-dino_server.py new file mode 100644 index 0000000000000000000000000000000000000000..92e26bd620e1c07add3566e7fe36d3944d190bac --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dino/app/bioconductor-dino_server.py @@ -0,0 +1,195 @@ +import subprocess +import tempfile +import os +from pathlib import Path +from typing import Optional, List, Dict, Any + +@mcp.tool() +def normalize_single_cell_data( + input_sce_path: Path, + output_sce_path: Path, + output_normalized_matrix_path: Optional[Path] = None, + seed: Optional[int] = None, + num_cores: Optional[int] = None, +) -> Dict[str, Any]: + """ + Normalizes single-cell mRNA sequencing data using the Bioconductor Dino package. + + This tool corrects for technical variation, particularly sequencing depth, + producing a matrix of corrected expression where the dependency between + sequencing depth and the full distribution of normalized expression is removed. + It is particularly useful for highly sparse datasets from UMI-based protocols. + + Args: + input_sce_path: Path to the input SingleCellExperiment R object file (.rds). + This file should contain raw count data. + output_sce_path: Path to save the output normalized SingleCellExperiment + R object file (.rds). + output_normalized_matrix_path: Optional path to save the normalized + expression matrix as a CSV file. If provided, + the normalized logcounts will be extracted + and written to this file. + seed: Optional integer seed for reproducibility of random processes + within the normalization. Must be a positive integer. + num_cores: Optional integer specifying the number of cores to use for + parallel processing. Must be a positive integer. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list + of generated output files. + """ + # 1. Input Validation + if not input_sce_path.is_file(): + raise ValueError(f"Input SingleCellExperiment file not found: {input_sce_path}") + if not input_sce_path.suffix == ".rds": + raise ValueError(f"Input file must be an .rds file, but got: {input_sce_path.suffix}") + + if output_sce_path.suffix != ".rds": + raise ValueError(f"Output SingleCellExperiment file must have a .rds extension, but got: {output_sce_path.suffix}") + output_sce_path.parent.mkdir(parents=True, exist_ok=True) + + if output_normalized_matrix_path: + if not output_normalized_matrix_path.suffix.lower() in [".csv", ".tsv"]: + raise ValueError(f"Output normalized matrix file must be .csv or .tsv, but got: {output_normalized_matrix_path.suffix}") + output_normalized_matrix_path.parent.mkdir(parents=True, exist_ok=True) + + if seed is not None: + if not isinstance(seed, int) or seed <= 0: + raise ValueError(f"Seed must be a positive integer, but got: {seed}") + + if num_cores is not None: + if not isinstance(num_cores, int) or num_cores <= 0: + raise ValueError(f"Number of cores must be a positive integer, but got: {num_cores}") + + # 2. File Path Handling and R Script Generation + r_script_content = f""" + library(Dino) + library(SingleCellExperiment) + library(BiocParallel) + library(Matrix) # For sparse matrix handling if needed + library(utils) # For write.csv/write.table + + # Set seed for reproducibility if provided + if (!is.null({seed})) {{ + set.seed({seed}) + }} + + # Set up parallel processing if num_cores is provided + if (!is.null({num_cores})) {{ + BPPARAM <- MulticoreParam(workers = {num_cores}) + }} else {{ + BPPARAM <- SerialParam() # Default to serial processing + }} + + # Load input SingleCellExperiment object + sce <- readRDS("{input_sce_path}") + + # Ensure 'counts' assay exists, as Dino typically operates on raw counts + if (!("counts" %in% assayNames(sce))) {{ + stop("Input SingleCellExperiment object must contain a 'counts' assay.") + }} + + # Perform Dino normalization + # The main normalization function in Dino is typically called 'DinoNormalize' + # or similar, operating on a SingleCellExperiment object. + # Assuming a function `DinoNormalize` exists and takes an SCE and BPPARAM. + # If the actual function name is different, this needs to be updated. + message("Starting Dino normalization...") + normalized_sce <- DinoNormalize(sce, BPPARAM = BPPARAM) + message("Dino normalization complete.") + + # Save the normalized SingleCellExperiment object + saveRDS(normalized_sce, "{output_sce_path}") + message("Normalized SingleCellExperiment object saved to {output_sce_path}") + + # Optionally save the normalized expression matrix + if (!is.null("{output_normalized_matrix_path}")) {{ + # Dino typically stores normalized data in 'logcounts' or a similar assay + if ("logcounts" %in% assayNames(normalized_sce)) {{ + normalized_matrix <- assay(normalized_sce, "logcounts") + }} else if ("normcounts" %in% assayNames(normalized_sce)) {{ + normalized_matrix <- assay(normalized_sce, "normcounts") + }} else {{ + stop("Normalized assay (e.g., 'logcounts' or 'normcounts') not found in the output SingleCellExperiment object.") + }} + + # Determine separator based on file extension + if (grepl("\\.csv$", "{output_normalized_matrix_path}", ignore.case = TRUE)) {{ + write.csv(as.matrix(normalized_matrix), "{output_normalized_matrix_path}", row.names = TRUE) + message("Normalized expression matrix saved to {output_normalized_matrix_path} as CSV.") + }} else if (grepl("\\.tsv$", "{output_normalized_matrix_path}", ignore.case = TRUE)) {{ + write.table(as.matrix(normalized_matrix), "{output_normalized_matrix_path}", sep = "\\t", quote = FALSE, row.names = TRUE) + message("Normalized expression matrix saved to {output_normalized_matrix_path} as TSV.") + }} else {{ + warning("Unsupported output format for normalized matrix. Skipping saving matrix.") + }} + }} + """ + + # Use a temporary file for the R script + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".R") as r_script_file: + r_script_file.write(r_script_content) + r_script_path = Path(r_script_file.name) + + command = ["Rscript", str(r_script_path)] + command_executed = " ".join(command) + + stdout: str = "" + stderr: str = "" + output_files: List[str] = [] + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + env=os.environ.copy() # Pass current environment to Rscript + ) + stdout = process.stdout + stderr = process.stderr + + if output_sce_path.is_file(): + output_files.append(str(output_sce_path)) + else: + raise FileNotFoundError(f"Expected output SCE file not found: {output_sce_path}") + + if output_normalized_matrix_path and output_normalized_matrix_path.is_file(): + output_files.append(str(output_normalized_matrix_path)) + + except subprocess.CalledProcessError as e: + stdout = e.stdout + stderr = e.stderr + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "error": f"R script failed with exit code {e.returncode}. See stderr for details.", + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": "Rscript command not found. Is R installed and in your PATH?", + "error": "Rscript executable not found.", + "output_files": [], + } + finally: + # Clean up the temporary R script file + if r_script_path.exists(): + os.remove(r_script_path) + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + +# Note: The actual function name for normalization within the Dino package +# (e.g., `DinoNormalize`) is an assumption based on common Bioconductor practices +# and the package's description. If the specific function name or its parameters +# differ, the R script content within this Python function would need adjustment +# based on the official Dino package documentation (e.g., by running `help(package="Dino")` +# or `?DinoNormalize` in an R session after installing the package). \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dino/app/bioconductor-dino_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dino/app/bioconductor-dino_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..cf783f001ea29d37a9299a00fd7c4656831db6ff --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dino/app/bioconductor-dino_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-dino/app/bioconductor-dino_server.py') +SERVER_NAME = 'biosci_bioconductor_dino' + + +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-dino/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dino/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..4fd86a2fb530e480a3be61540646fc99417a27c2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dino/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-dino: + build: . + image: mcp-bioconductor-dino:latest + container_name: mcp-bioconductor-dino + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-dino + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dino/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dino/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d43d9329de36095538b4692008941e84a395ce3d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dino/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-dino + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dino/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dino/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dino/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dirichletmultinomial/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dirichletmultinomial/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6b140ffebcc28a004b81e016332d3c19575de84d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dirichletmultinomial/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-dirichletmultinomial via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-dirichletmultinomial -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-dirichletmultinomial_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-dirichletmultinomial_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-dirichletmultinomial_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dirichletmultinomial/app/bioconductor-dirichletmultinomial_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dirichletmultinomial/app/bioconductor-dirichletmultinomial_server.py new file mode 100644 index 0000000000000000000000000000000000000000..986e9bd57e6968574a1c98d47ada889bfb5e19e3 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dirichletmultinomial/app/bioconductor-dirichletmultinomial_server.py @@ -0,0 +1,354 @@ +import subprocess +import tempfile +import shutil +from pathlib import Path +from typing import Optional, Dict, List + +# Assume mcp is imported and the @mcp.tool decorator is available. +# We define it here for the code to be syntactically valid. +class mcp: + def tool(func): + return func + +# R script template for fitting the Dirichlet-Multinomial model +DMN_FIT_R_SCRIPT = """ +# Ensure required packages are installed and loaded +if (!requireNamespace("DirichletMultinomial", quietly = TRUE)) {{ + stop("FATAL: R package 'DirichletMultinomial' is not installed. Please install it from Bioconductor.", call. = FALSE) +}} +if (!requireNamespace("argparse", quietly = TRUE)) {{ + stop("FATAL: R package 'argparse' is not installed. Please install it from CRAN.", call. = FALSE) +}} +library(DirichletMultinomial) +library(argparse) + +# --- Argument Parsing --- +parser <- ArgumentParser(description="Fit a Dirichlet-Multinomial Model using the DirichletMultinomial package.") +parser$add_argument("--counts", type="character", required=TRUE, help="Path to the input count matrix (tab-separated, no header, samples as rows, features as columns).") +parser$add_argument("--k", type="integer", required=TRUE, help="The number of mixture components (clusters) to fit.") +parser$add_argument("--output_model", type="character", required=TRUE, help="Path to save the fitted model object (.rds).") +parser$add_argument("--verbose", action="store_true", default=FALSE, help="Enable verbose output during model fitting.") + +args <- parser$parse_args() + +# --- Data Loading and Validation --- +message("INFO: Reading count data from: ", args$counts) +if (!file.exists(args$counts)) {{ + stop("FATAL: Input counts file not found: ", args$counts, call. = FALSE) +}} +counts <- tryCatch({{ + as.matrix(read.table(args$counts, sep="\\t", header=FALSE, check.names=FALSE)) +}}, error = function(e) {{ + stop(paste("FATAL: Failed to read counts file. Ensure it is a proper tab-separated matrix:", e$message), call. = FALSE) +}}) +message("INFO: Count matrix dimensions: ", nrow(counts), " samples, ", ncol(counts), " features.") + +if (any(counts < 0) || !all(counts == floor(counts))) {{ + stop("FATAL: Count matrix must contain non-negative integers only.", call. = FALSE) +}} + +# --- Model Fitting --- +message("INFO: Fitting Dirichlet-Multinomial model with k=", args$k) +fit <- tryCatch({{ + dmn(count = counts, k = args$k, verbose = args$verbose) +}}, error = function(e) {{ + stop(paste("FATAL: Error during model fitting:", e$message), call. = FALSE) +}}) +message("INFO: Model fitting complete.") + +# --- Save Output --- +message("INFO: Saving fitted model to: ", args$output_model) +tryCatch({{ + saveRDS(fit, file = args$output_model) +}}, error = function(e) {{ + stop(paste("FATAL: Failed to save output model file:", e$message), call. = FALSE) +}}) + +message("SUCCESS: Script finished successfully.") +""" + +# R script template for calculating goodness-of-fit +DMN_GOF_R_SCRIPT = """ +# Ensure required packages are installed and loaded +if (!requireNamespace("DirichletMultinomial", quietly = TRUE)) {{ + stop("FATAL: R package 'DirichletMultinomial' is not installed.", call. = FALSE) +}} +if (!requireNamespace("argparse", quietly = TRUE)) {{ + stop("FATAL: R package 'argparse' is not installed.", call. = FALSE) +}} +library(DirichletMultinomial) +library(argparse) + +# --- Argument Parsing --- +parser <- ArgumentParser(description="Calculate and plot goodness-of-fit for a DMM model.") +parser$add_argument("--model", type="character", required=TRUE, help="Path to the fitted DMM model object (.rds).") +parser$add_argument("--output_plot", type="character", required=TRUE, help="Path to save the goodness-of-fit plot (.png).") + +args <- parser$parse_args() + +# --- Model Loading --- +message("INFO: Loading fitted model from: ", args$model) +if (!file.exists(args$model)) {{ + stop("FATAL: Input model file not found: ", args$model, call. = FALSE) +}} +model <- tryCatch({{ + readRDS(args$model) +}}, error = function(e) {{ + stop(paste("FATAL: Failed to read model file:", e$message), call. = FALSE) +}}) + +# --- Goodness-of-Fit Calculation and Plotting --- +message("INFO: Calculating goodness-of-fit.") +gof <- tryCatch({{ + goodnessOfFit(model) +}}, error = function(e) {{ + stop(paste("FATAL: Error during goodnessOfFit calculation:", e$message), call. = FALSE) +}}) + +message("INFO: Saving plot to: ", args$output_plot) +tryCatch({{ + png(args$output_plot, width=800, height=600) + plot(gof) + dev.off() +}}, error = function(e) {{ + stop(paste("FATAL: Failed to save output plot:", e$message), call. = FALSE) +}}) + +message("SUCCESS: Script finished successfully.") +""" + +# R script template for prediction +DMN_PREDICT_R_SCRIPT = """ +# Ensure required packages are installed and loaded +if (!requireNamespace("DirichletMultinomial", quietly = TRUE)) {{ + stop("FATAL: R package 'DirichletMultinomial' is not installed.", call. = FALSE) +}} +if (!requireNamespace("argparse", quietly = TRUE)) {{ + stop("FATAL: R package 'argparse' is not installed.", call. = FALSE) +}} +library(DirichletMultinomial) +library(argparse) + +# --- Argument Parsing --- +parser <- ArgumentParser(description="Predict cluster assignments for new data using a fitted DMM model.") +parser$add_argument("--model", type="character", required=TRUE, help="Path to the fitted DMM model object (.rds).") +parser$add_argument("--new_data", type="character", required=TRUE, help="Path to new count data (tab-separated, no header).") +parser$add_argument("--output_predictions", type="character", required=TRUE, help="Path to save the prediction results (tab-separated).") +parser$add_argument("--type", type="character", default="prob", choices=c("prob", "class"), help="Type of prediction: 'prob' for posterior probabilities or 'class' for the most likely cluster.") + +args <- parser$parse_args() + +# --- Model and Data Loading --- +message("INFO: Loading fitted model from: ", args$model) +if (!file.exists(args$model)) {{ + stop("FATAL: Input model file not found: ", args$model, call. = FALSE) +}} +model <- readRDS(args$model) + +message("INFO: Reading new data from: ", args$new_data) +if (!file.exists(args$new_data)) {{ + stop("FATAL: New data file not found: ", args$new_data, call. = FALSE) +}} +new_data <- as.matrix(read.table(args$new_data, sep="\\t", header=FALSE, check.names=FALSE)) + +# --- Prediction --- +message("INFO: Predicting cluster assignments for new data.") +predictions <- tryCatch({{ + predict(model, newdata=new_data) +}}, error = function(e) {{ + stop(paste("FATAL: Error during prediction:", e$message), call. = FALSE) +}}) + +# --- Process and Save Output --- +if (args$type == "class") {{ + # Get the index of the maximum probability for each row + result <- apply(predictions, 1, which.max) +}} else {{ + # Use the full probability matrix + result <- predictions +}} + +message("INFO: Saving prediction results to: ", args$output_predictions) +write.table(result, file=args$output_predictions, sep="\\t", row.names=FALSE, col.names=FALSE, quote=FALSE) + +message("SUCCESS: Script finished successfully.") +""" + +def _run_r_script(script_content: str, args: List[str]) -> Dict[str, str]: + """Helper function to run an R script in a temporary file.""" + if not shutil.which("Rscript"): + raise RuntimeError("Rscript executable not found in PATH. R is required.") + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_script: + tmp_script.write(script_content) + script_path = tmp_script.name + + command = ["Rscript", script_path] + args + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + } + except subprocess.CalledProcessError as e: + # Provide a more informative error message + error_message = ( + f"R script execution failed with exit code {e.returncode}.\n" + f"Command: {' '.join(e.cmd)}\n" + f"Stdout:\n{e.stdout}\n" + f"Stderr:\n{e.stderr}\n" + ) + raise RuntimeError(error_message) from e + finally: + Path(script_path).unlink() + + +@mcp.tool +def fit_dirichlet_multinomial( + counts_file: Path, + k: int, + output_model_file: Path, + verbose: bool = False, +) -> Dict: + """ + Fits a Dirichlet-Multinomial Mixture (DMM) model to count data. + + This tool uses the dmn() function from the R package 'DirichletMultinomial' + to identify clusters in count data, such as microbial abundance profiles. + + Args: + counts_file: Path to the input count matrix. Must be a tab-separated file + with no header, where rows are samples and columns are features. + k: The number of mixture components (clusters) to fit. Must be a positive integer. + output_model_file: Path to save the fitted model as an R object (.rds file). + verbose: If True, enables verbose output during the model fitting process. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a + mapping to the output model file. + """ + # --- Input Validation --- + if not counts_file.is_file(): + raise FileNotFoundError(f"Input counts file not found: {counts_file}") + if k <= 0: + raise ValueError("The number of components 'k' must be a positive integer.") + if not output_model_file.parent.exists(): + output_model_file.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + args = [ + "--counts", str(counts_file), + "--k", str(k), + "--output_model", str(output_model_file), + ] + if verbose: + args.append("--verbose") + + # --- Subprocess Execution --- + result = _run_r_script(DMN_FIT_R_SCRIPT, args) + + # --- Structured Result Return --- + result["output_files"] = {"fitted_model": str(output_model_file)} + return result + + +@mcp.tool +def goodness_of_fit( + model_file: Path, + output_plot_file: Path, +) -> Dict: + """ + Calculates and plots the goodness-of-fit for a fitted DMM model. + + This tool uses the goodnessOfFit() function from 'DirichletMultinomial' to + assess how well the model fits the data by comparing the log-likelihood of + the fitted model to that of a saturated multinomial model. + + Args: + model_file: Path to a fitted DMM model object (.rds file) generated by + the fit_dirichlet_multinomial tool. + output_plot_file: Path to save the output goodness-of-fit plot (.png). + + Returns: + A dictionary containing the command executed, stdout, stderr, and a + mapping to the output plot file. + """ + # --- Input Validation --- + if not model_file.is_file(): + raise FileNotFoundError(f"Input model file not found: {model_file}") + if not output_plot_file.parent.exists(): + output_plot_file.parent.mkdir(parents=True, exist_ok=True) + if output_plot_file.suffix.lower() != ".png": + raise ValueError("Output plot file must have a .png extension.") + + # --- Command Construction --- + args = [ + "--model", str(model_file), + "--output_plot", str(output_plot_file), + ] + + # --- Subprocess Execution --- + result = _run_r_script(DMN_GOF_R_SCRIPT, args) + + # --- Structured Result Return --- + result["output_files"] = {"gof_plot": str(output_plot_file)} + return result + + +@mcp.tool +def predict_clusters( + model_file: Path, + new_data_file: Path, + output_predictions_file: Path, + prediction_type: str = "prob", +) -> Dict: + """ + Predicts cluster assignments for new data using a fitted DMM model. + + This tool uses the predict() function from 'DirichletMultinomial' to calculate + the posterior probabilities of cluster membership for new samples. + + Args: + model_file: Path to a fitted DMM model object (.rds file). + new_data_file: Path to a new count matrix for which to predict clusters. + Format must match the original training data. + output_predictions_file: Path to save the prediction results (tab-separated). + prediction_type: Type of prediction to output. Can be 'prob' (default) for + the full matrix of posterior probabilities, or 'class' for + the single most likely cluster assignment for each sample. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a + mapping to the output predictions file. + """ + # --- Input Validation --- + if not model_file.is_file(): + raise FileNotFoundError(f"Input model file not found: {model_file}") + if not new_data_file.is_file(): + raise FileNotFoundError(f"New data file not found: {new_data_file}") + if prediction_type not in ["prob", "class"]: + raise ValueError("prediction_type must be either 'prob' or 'class'.") + if not output_predictions_file.parent.exists(): + output_predictions_file.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + args = [ + "--model", str(model_file), + "--new_data", str(new_data_file), + "--output_predictions", str(output_predictions_file), + "--type", prediction_type, + ] + + # --- Subprocess Execution --- + result = _run_r_script(DMN_PREDICT_R_SCRIPT, args) + + # --- Structured Result Return --- + result["output_files"] = {"predictions": str(output_predictions_file)} + return result \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dirichletmultinomial/app/bioconductor-dirichletmultinomial_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dirichletmultinomial/app/bioconductor-dirichletmultinomial_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d2afe6845b9294611c860c508365f8df250fe818 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dirichletmultinomial/app/bioconductor-dirichletmultinomial_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-dirichletmultinomial/app/bioconductor-dirichletmultinomial_server.py') +SERVER_NAME = 'biosci_bioconductor_dirichletmultinomial' + + +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-dirichletmultinomial/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dirichletmultinomial/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dirichletmultinomial/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dirichletmultinomial/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dirichletmultinomial/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..cb60f4389afe631128c813da64d85d6a4bc4d26e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dirichletmultinomial/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-dirichletmultinomial: + build: . + image: mcp-bioconductor-dirichletmultinomial:latest + container_name: mcp-bioconductor-dirichletmultinomial + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-dirichletmultinomial + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dirichletmultinomial/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dirichletmultinomial/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c361af9475e4996a82d48c65765813a91eb93eb4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dirichletmultinomial/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-dirichletmultinomial + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dirichletmultinomial/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dirichletmultinomial/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dirichletmultinomial/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dnacopy/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dnacopy/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..acfa6545a2f171d74ff198f82cd7aaba66db4989 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dnacopy/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-dnacopy via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-dnacopy -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-dnacopy_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-dnacopy_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-dnacopy_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dnacopy/app/bioconductor-dnacopy_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dnacopy/app/bioconductor-dnacopy_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8a1aa7e2b77094a03372e2ea22b29a69aec3434b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dnacopy/app/bioconductor-dnacopy_server.py @@ -0,0 +1,371 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Union + +@mcp.tool() +def dnacopy_segment( + input_file: str, + output_file: str, + chrom_col: str, + maploc_col: str, + sample_col: str, + data_type: str = "logratio", + alpha: float = 0.01, + nperm: int = 10000, + p_method: str = "hybrid", + min_width: int = 2, + kmax: int = 25, + nmin: int = 200, + eta: float = 0.05, + trim: float = 0.025, + undo_splits: str = "none", + undo_pr: float = 0.05, + undo_sd: float = 3.0, + verbose: int = 1, + sep: str = "\t" +): + """ + Perform Circular Binary Segmentation (CBS) on DNA copy number data using the DNAcopy Bioconductor package. + + Args: + input_file: Path to the input data file (TSV/CSV). + output_file: Path where the segmented output will be saved. + chrom_col: Name of the column containing chromosome information. + maploc_col: Name of the column containing genomic coordinates/map locations. + sample_col: Name of the column containing the copy number log-ratio data. + data_type: Type of data, either 'logratio' or 'binary'. + alpha: Significance level for the test to accept change-points. + nperm: Number of permutations used for p-value computation. + p_method: Method used for p-value computation ('hybrid' or 'perm'). + min_width: Minimum number of markers for a segment. + kmax: Maximum width of smaller segment for the hybrid method. + nmin: Minimum length of data for which the hybrid method is used. + eta: Probability threshold for the hybrid method. + trim: Proportion of data to be trimmed for calculating the smoothed variance. + undo_splits: Method to undo unnecessary splits ('none', 'prune', or 'sdundo'). + undo_pr: Significance level for pruning (if undo_splits='prune'). + undo_sd: Number of standard deviations for undoing (if undo_splits='sdundo'). + verbose: Level of verbosity (0, 1, 2). + sep: Field separator in the input file (default is tab). + """ + # Input validation + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + + if data_type not in ["logratio", "binary"]: + return {"error": "data_type must be 'logratio' or 'binary'"} + + if p_method not in ["hybrid", "perm"]: + return {"error": "p_method must be 'hybrid' or 'perm'"} + + if undo_splits not in ["none", "prune", "sdundo"]: + return {"error": "undo_splits must be 'none', 'prune', or 'sdundo'"} + + # Create R script + r_script_content = f""" + library(DNAcopy) + + # Load data + data_df <- read.table("{input_file}", header=TRUE, sep="{sep}", check.names=FALSE) + + # Create CNA object + cna_obj <- CNA( + genomdat = data_df[["{sample_col}"]], + chrom = data_df[["{chrom_col}"]], + maploc = data_df[["{maploc_col}"]], + data.type = "{data_type}", + sampleid = "{sample_col}" + ) + + # Run segmentation + segmented <- segment( + cna_obj, + alpha = {alpha}, + nperm = {nperm}, + p.method = "{p_method}", + min.width = {min_width}, + kmax = {kmax}, + nmin = {nmin}, + eta = {eta}, + trim = {trim}, + undo.splits = "{undo_splits}", + undo.PR = {undo_pr}, + undo.SD = {undo_sd}, + verbose = {verbose} + ) + + # Write output + write.table(segmented$output, file="{output_file}", sep="\\t", quote=FALSE, row.names=FALSE) + """ + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script_content) + tmp_path = tmp.name + + result = subprocess.run( + ["Rscript", tmp_path], + capture_output=True, + text=True, + check=True + ) + + Path(tmp_path).unlink() # Clean up + + return { + "command_executed": f"Rscript {tmp_path} (DNAcopy::segment)", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def dnacopy_smooth( + input_file: str, + output_file: str, + chrom_col: str, + maploc_col: str, + sample_col: str, + smooth_region: int = 10, + outlier_sd_scale: float = 4.0, + smooth_sd_scale: float = 2.0, + trim: float = 0.025, + sep: str = "\t" +): + """ + Smooth DNA copy number data to detect and mitigate outliers before segmentation. + + Args: + input_file: Path to the input data file (TSV/CSV). + output_file: Path where the smoothed data will be saved. + chrom_col: Name of the column containing chromosome information. + maploc_col: Name of the column containing genomic coordinates. + sample_col: Name of the column containing the copy number log-ratio data. + smooth_region: Number of points to the left and right of a point to use for smoothing. + outlier_sd_scale: The number of SDs from the local mean to consider a point an outlier. + smooth_sd_scale: The number of SDs from the local mean to which an outlier is smoothed. + trim: Proportion of data to be trimmed for calculating the smoothed variance. + sep: Field separator in the input file. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + + r_script_content = f""" + library(DNAcopy) + + data_df <- read.table("{input_file}", header=TRUE, sep="{sep}", check.names=FALSE) + + cna_obj <- CNA( + genomdat = data_df[["{sample_col}"]], + chrom = data_df[["{chrom_col}"]], + maploc = data_df[["{maploc_col}"]], + sampleid = "{sample_col}" + ) + + smoothed_obj <- smooth.CNA( + cna_obj, + smooth.region = {smooth_region}, + outlier.SD.scale = {outlier_sd_scale}, + smooth.SD.scale = {smooth_sd_scale}, + trim = {trim} + ) + + # Reconstruct dataframe for output + out_df <- data.frame( + chrom = smoothed_obj$chrom, + maploc = smoothed_obj$maploc, + smoothed_val = smoothed_obj[[3]] + ) + colnames(out_df) <- c("{chrom_col}", "{maploc_col}", "{sample_col}") + + write.table(out_df, file="{output_file}", sep="\\t", quote=FALSE, row.names=FALSE) + """ + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script_content) + tmp_path = tmp.name + + result = subprocess.run( + ["Rscript", tmp_path], + capture_output=True, + text=True, + check=True + ) + + Path(tmp_path).unlink() + + return { + "command_executed": f"Rscript {tmp_path} (DNAcopy::smooth.CNA)", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file] + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stdout": e.stdout, "stderr": e.stderr} + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def dnacopy_plot( + input_file: str, + plot_file: str, + chrom_col: str, + maploc_col: str, + sample_col: str, + plot_type: str = "whole", + xmaploc: bool = False, + sep: str = "\t" +): + """ + Generate plots for DNA copy number segmentation results. + + Args: + input_file: Path to the input data file (TSV/CSV). + plot_file: Path where the plot (PNG) will be saved. + chrom_col: Name of the column containing chromosome information. + maploc_col: Name of the column containing genomic coordinates. + sample_col: Name of the column containing the copy number log-ratio data. + plot_type: Type of plot ('whole', 'chromosomal', or 'sample'). + xmaploc: Logical flag to indicate if the x-axis should be map location (True) or index (False). + sep: Field separator in the input file. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + + if not plot_file.lower().endswith('.png'): + plot_file += ".png" + + r_script_content = f""" + library(DNAcopy) + + data_df <- read.table("{input_file}", header=TRUE, sep="{sep}", check.names=FALSE) + + cna_obj <- CNA( + genomdat = data_df[["{sample_col}"]], + chrom = data_df[["{chrom_col}"]], + maploc = data_df[["{maploc_col}"]], + sampleid = "{sample_col}" + ) + + segmented <- segment(cna_obj, verbose=0) + + png("{plot_file}", width=1200, height=800) + plot(segmented, plot.type="{plot_type}", xmaploc={"TRUE" if xmaploc else "FALSE"}) + dev.off() + """ + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script_content) + tmp_path = tmp.name + + result = subprocess.run( + ["Rscript", tmp_path], + capture_output=True, + text=True, + check=True + ) + + Path(tmp_path).unlink() + + return { + "command_executed": f"Rscript {tmp_path} (DNAcopy::plot)", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [plot_file] + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stdout": e.stdout, "stderr": e.stderr} + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def dnacopy_subset( + input_file: str, + output_file: str, + chrom_col: str, + maploc_col: str, + sample_col: str, + chromosomes: List[str], + sep: str = "\t" +): + """ + Subset a CNA object by chromosomes using DNAcopy internal logic. + + Args: + input_file: Path to the input data file. + output_file: Path where the subsetted data will be saved. + chrom_col: Name of the chromosome column. + maploc_col: Name of the map location column. + sample_col: Name of the sample data column. + chromosomes: List of chromosome names to keep (e.g., ["1", "2", "X"]). + sep: Field separator. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + + chrom_list_r = 'c("' + '", "'.join(chromosomes) + '")' + + r_script_content = f""" + library(DNAcopy) + + data_df <- read.table("{input_file}", header=TRUE, sep="{sep}", check.names=FALSE) + + cna_obj <- CNA( + genomdat = data_df[["{sample_col}"]], + chrom = data_df[["{chrom_col}"]], + maploc = data_df[["{maploc_col}"]], + sampleid = "{sample_col}" + ) + + subset_obj <- subset(cna_obj, chromlist = {chrom_list_r}) + + # Reconstruct dataframe + out_df <- data.frame( + chrom = subset_obj$chrom, + maploc = subset_obj$maploc, + val = subset_obj[[3]] + ) + colnames(out_df) <- c("{chrom_col}", "{maploc_col}", "{sample_col}") + + write.table(out_df, file="{output_file}", sep="\\t", quote=FALSE, row.names=FALSE) + """ + + try: + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_script_content) + tmp_path = tmp.name + + result = subprocess.run( + ["Rscript", tmp_path], + capture_output=True, + text=True, + check=True + ) + + Path(tmp_path).unlink() + + return { + "command_executed": f"Rscript {tmp_path} (DNAcopy::subset)", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file] + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stdout": e.stdout, "stderr": e.stderr} + except Exception as e: + return {"error": str(e)} \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dnacopy/app/bioconductor-dnacopy_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dnacopy/app/bioconductor-dnacopy_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..85644ebdb44a39809845a2eb4ec615d751fb9cec --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dnacopy/app/bioconductor-dnacopy_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-dnacopy/app/bioconductor-dnacopy_server.py') +SERVER_NAME = 'biosci_bioconductor_dnacopy' + + +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-dnacopy/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dnacopy/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dnacopy/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dnacopy/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dnacopy/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..2a3bc04cf7735b56b19adb7824aab027ad1edc38 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dnacopy/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-dnacopy: + build: . + image: mcp-bioconductor-dnacopy:latest + container_name: mcp-bioconductor-dnacopy + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-dnacopy + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dnacopy/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dnacopy/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a899be3d3c4b68ef4f21429190feaaf5b44d4dbf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dnacopy/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-dnacopy + - python=3.10 + \ No newline at end of file