diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_abyss/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_abyss/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0cf551459d3b438e84031a5bff03697c1e228449 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_abyss/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install abyss via conda (e.g., from bioconda) +RUN conda install -c bioconda abyss -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY abyss_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/abyss_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/abyss_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_abyss/app/__pycache__/abyss_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_abyss/app/__pycache__/abyss_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f44656cc98cc197916bf327042f38a40f37251d1 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_abyss/app/__pycache__/abyss_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_abyss/app/abyss_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_abyss/app/abyss_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7e897940964d168659f69e680ee975743aa936b9 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_abyss/app/abyss_server.py @@ -0,0 +1,211 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict, Any + +# from mcp import tool as mcp_tool +# Note: The 'mcp' import is commented out as per the instructions. +# In a real MCP environment, you would uncomment the line above. + +def mcp_tool(func): + """A placeholder decorator to mimic @mcp.tool().""" + return func + +@mcp_tool +def run_perl( + programfile: Optional[Path] = None, + program_string: Optional[str] = None, + arguments: Optional[List[str]] = None, + include_dirs: Optional[List[Path]] = None, + use_modules: Optional[List[str]] = None, + no_modules: Optional[List[str]] = None, + warnings: str = "normal", + check_syntax_only: bool = False, + enable_all_features: bool = False, +) -> Dict[str, Any]: + """ + Executes a Perl script or a one-liner command with specified options. + + This tool serves as a wrapper around the Perl interpreter, allowing for the execution + of scripts from files or direct command-line strings. It provides options for + managing modules, include paths, and warning levels. + + Args: + programfile: Path to the Perl program file to execute. + program_string: A string containing a one-liner Perl program to execute. + arguments: A list of arguments to pass to the program file or one-liner. + include_dirs: A list of directories to add to Perl's @INC path for finding modules. + use_modules: A list of modules to 'use' before executing the program. + no_modules: A list of modules to 'no' (disable) before executing the program. + warnings: Set the warning level. Can be 'normal' (-w), 'all' (-W), or 'none' (-X). + check_syntax_only: If True, checks the syntax of the program without executing it (-c). + enable_all_features: If True and using program_string, enables all optional features (-E). + """ + # 1. Input Validation + if not (programfile or program_string): + raise ValueError("Either 'programfile' or 'program_string' must be provided.") + if programfile and program_string: + raise ValueError("Cannot provide both 'programfile' and 'program_string'.") + + if programfile and not programfile.is_file(): + raise FileNotFoundError(f"Program file not found: {programfile}") + + if include_dirs: + for d in include_dirs: + if not d.is_dir(): + raise NotADirectoryError(f"Include directory not found: {d}") + + allowed_warnings = ["normal", "all", "none"] + if warnings not in allowed_warnings: + raise ValueError(f"Invalid 'warnings' value '{warnings}'. Must be one of {allowed_warnings}.") + + # 2. Command Construction + cmd = ["perl"] + + # Handle warnings + if warnings == "normal": + cmd.append("-w") + elif warnings == "all": + cmd.append("-W") + elif warnings == "none": + cmd.append("-X") + + # Handle syntax check + if check_syntax_only: + cmd.append("-c") + + # Handle include directories + if include_dirs: + for d in include_dirs: + cmd.extend(["-I", str(d)]) + + # Handle modules + if use_modules: + for module in use_modules: + cmd.extend(["-M", module]) + if no_modules: + for module in no_modules: + cmd.extend(["-m", module]) + + # Handle program source (file or string) + if program_string: + if enable_all_features: + cmd.append("-E") + else: + cmd.append("-e") + cmd.append(program_string) + elif programfile: + cmd.append(str(programfile)) + + # Handle arguments to the script + if arguments: + cmd.extend(arguments) + + command_executed = " ".join(map(str, cmd)) + + # 3. Subprocess Execution + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=False, # Check manually to provide better error context + ) + if result.returncode != 0: + raise subprocess.CalledProcessError( + result.returncode, cmd, output=result.stdout, stderr=result.stderr + ) + except FileNotFoundError: + raise RuntimeError("Perl executable not found. Please ensure it is in your system's PATH.") + except subprocess.CalledProcessError as e: + return { + "error": "Perl execution failed.", + "return_code": e.returncode, + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": command_executed, + } + + # 4. Structured Result Return + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] # The wrapper itself doesn't create files + } + +@mcp_tool +def perl_version() -> Dict[str, Any]: + """ + Retrieves the version, patchlevel, and license of the Perl interpreter. + + This corresponds to the `perl -v` command. + """ + cmd = ["perl", "-v"] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except FileNotFoundError: + raise RuntimeError("Perl executable not found. Please ensure it is in your system's PATH.") + except subprocess.CalledProcessError as e: + return { + "error": "Failed to get Perl version.", + "return_code": e.returncode, + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": command_executed, + } + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + } + +@mcp_tool +def perl_config(variable: Optional[str] = None) -> Dict[str, Any]: + """ + Prints the configuration summary for the Perl installation. + + This corresponds to the `perl -V` command. If a variable name is provided, + it prints the value of that specific configuration variable. + + Args: + variable: A specific Config.pm variable to query. + """ + cmd = ["perl"] + if variable: + cmd.append(f"-V:{variable}") + else: + cmd.append("-V") + + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except FileNotFoundError: + raise RuntimeError("Perl executable not found. Please ensure it is in your system's PATH.") + except subprocess.CalledProcessError as e: + return { + "error": "Failed to get Perl configuration.", + "return_code": e.returncode, + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": command_executed, + } + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + } \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_abyss/app/abyss_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_abyss/app/abyss_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8d03a013ef0001f939fe06f51be52c4facb4da59 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_abyss/app/abyss_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_abyss/app/abyss_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_abyss' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_abyss/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_abyss/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..0b776c095129c6c459841083e9ee41eaad24d392 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_abyss/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-abyss: + build: . + image: mcp-abyss:latest + container_name: mcp-abyss + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=abyss + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_abyss/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_abyss/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fe6f92d9673028828b344143f444099fe8da3d64 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_abyss/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - abyss + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_abyss/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_abyss/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_abyss/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_aragorn/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_aragorn/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2cdc6ab27d8af15e6706a59d711433b15df37b21 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_aragorn/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install aragorn via conda (e.g., from bioconda) +RUN conda install -c bioconda aragorn -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/aragorn_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/aragorn_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/aragorn_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_aragorn/app/__pycache__/aragorn_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_aragorn/app/__pycache__/aragorn_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..38761591a7673c57d4564e94b1ed8eb8f7838d93 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_aragorn/app/__pycache__/aragorn_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_aragorn/app/aragorn_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_aragorn/app/aragorn_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4dee6f4745984f6864210cde96f0f799554da1be --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_aragorn/app/aragorn_server.py @@ -0,0 +1,225 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, List + +# This is a placeholder for the MCP environment's decorator. +# In a real MCP environment, this would be provided. +class mcp: + @staticmethod + def tool(): + def decorator(f): + return f + return decorator + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_aragorn' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def aragorn( + sequence_file: Path, + output_file: Optional[Path] = None, + search_mode: str = "both", + batch_output: bool = False, + fasta_output_all: bool = False, + fasta_output_all_seq_only: bool = False, + fasta_output_mature: bool = False, + fasta_output_mature_seq_only: bool = False, + fasta_output_all_no_spaces: bool = False, + fasta_output_mature_no_spaces: bool = False, + output_format: str = "normal", + verbose: bool = False, + verbose_trna_structure: bool = False, + verbose_tmrna_structure: bool = False, + genetic_code: str = "standard", + genetic_code_table_id: Optional[int] = None, + allow_introns: bool = False, + topology: str = "circular", + post_process_cutoff: Optional[float] = None, + no_post_process: bool = False, + ecoli_tloop: bool = False, + permuted_exons: bool = False, + input_format: Optional[int] = None, + strand: str = "both" +): + """ + Finds tRNA and tmRNA genes in nucleotide sequences using ARAGORN. + + ARAGORN is a tool for finding transfer RNA (tRNA) and transfer-messenger RNA (tmRNA) + genes in nucleotide sequences. It uses homology search algorithms to identify + these genes with high accuracy. + + Args: + sequence_file: Input FASTA file containing nucleotide sequences. + output_file: Specify the output file path. If not provided, output is sent to stdout. + search_mode: Type of genes to search for. One of 'both', 'trna', 'tmrna'. + batch_output: Use batch output in a readable format (-w). + fasta_output_all: Fasta output of all genes (-fo). + fasta_output_all_seq_only: Fasta output of all genes, sequence only (-fos). + fasta_output_mature: Fasta output of mature tRNAs (-fr). + fasta_output_mature_seq_only: Fasta output of mature tRNAs, sequence only (-frs). + fasta_output_all_no_spaces: Fasta output of all genes, no spaces in header (-fons). + fasta_output_mature_no_spaces: Fasta output of mature tRNAs, no spaces in header (-frns). + output_format: Specify the main output format. One of 'normal', 'fasta', 'raw', 'brackets'. + verbose: Enable verbose output (-v). + verbose_trna_structure: Print tRNA secondary structure with verbose output (-tv). + verbose_tmrna_structure: Print tmRNA secondary structure with verbose output (-mv). + genetic_code: Genetic code to use for tRNA search. One of 'standard', 'chloroplast', 'mitochondrial', + 'vertebrate_mitochondrial', 'invertebrate_mitochondrial', 'yeast_mitochondrial', + 'protozoan', 'mycoplasma'. + genetic_code_table_id: Specify genetic code by its table number (-gcode ). + allow_introns: Allow introns in tRNAs (-i). + topology: Assume sequence topology. One of 'circular' (default) or 'linear' (-l). + post_process_cutoff: Post-process with profile search, using a cutoff in bits (-ps ). + no_post_process: Do not post-process with profile search (-d). + ecoli_tloop: Use E. coli tRNA T-loop consensus T-Psi-C-R-A (-a). + permuted_exons: Search for tRNA genes with permuted exons (-rp). + input_format: Specify input format code (1=fasta, 2=plain, 3=embl, 4=genbank). + strand: Strand to search. One of 'both' (default), 'sense', 'complementary'. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not sequence_file.is_file(): + raise FileNotFoundError(f"Input sequence file not found: {sequence_file}") + + valid_search_modes = ["both", "trna", "tmrna"] + if search_mode not in valid_search_modes: + raise ValueError(f"Invalid search_mode '{search_mode}'. Must be one of {valid_search_modes}") + + valid_output_formats = ["normal", "fasta", "raw", "brackets"] + if output_format not in valid_output_formats: + raise ValueError(f"Invalid output_format '{output_format}'. Must be one of {valid_output_formats}") + + valid_genetic_codes = [ + "standard", "chloroplast", "mitochondrial", "vertebrate_mitochondrial", + "invertebrate_mitochondrial", "yeast_mitochondrial", "protozoan", "mycoplasma" + ] + if genetic_code not in valid_genetic_codes: + raise ValueError(f"Invalid genetic_code '{genetic_code}'. Must be one of {valid_genetic_codes}") + + if genetic_code != "standard" and genetic_code_table_id is not None: + raise ValueError("Cannot specify both a named genetic_code and a genetic_code_table_id.") + + valid_topologies = ["circular", "linear"] + if topology not in valid_topologies: + raise ValueError(f"Invalid topology '{topology}'. Must be one of {valid_topologies}") + + if post_process_cutoff is not None and no_post_process: + raise ValueError("Cannot specify both post_process_cutoff and no_post_process.") + + if input_format is not None and input_format not in [1, 2, 3, 4]: + raise ValueError(f"Invalid input_format '{input_format}'. Must be one of 1, 2, 3, or 4.") + + valid_strands = ["both", "sense", "complementary"] + if strand not in valid_strands: + raise ValueError(f"Invalid strand '{strand}'. Must be one of {valid_strands}") + + # --- Command Construction --- + cmd = ["aragorn"] + + if search_mode == "trna": + cmd.append("-t") + elif search_mode == "tmrna": + cmd.append("-m") + + if output_file: + cmd.extend(["-o", str(output_file)]) + if batch_output: + cmd.append("-w") + if fasta_output_all: + cmd.append("-fo") + if fasta_output_all_seq_only: + cmd.append("-fos") + if fasta_output_mature: + cmd.append("-fr") + if fasta_output_mature_seq_only: + cmd.append("-frs") + if fasta_output_all_no_spaces: + cmd.append("-fons") + if fasta_output_mature_no_spaces: + cmd.append("-frns") + + if output_format == "fasta": + cmd.append("-fasta") + elif output_format == "raw": + cmd.append("-raw") + elif output_format == "brackets": + cmd.append("-br") + + if verbose: + cmd.append("-v") + if verbose_trna_structure: + cmd.append("-tv") + if verbose_tmrna_structure: + cmd.append("-mv") + + if genetic_code_table_id is not None: + cmd.extend(["-gcode", str(genetic_code_table_id)]) + else: + code_map = { + "standard": "-gcstd", "chloroplast": "-c", "mitochondrial": "-mt", + "vertebrate_mitochondrial": "-gcvert", "invertebrate_mitochondrial": "-gcinvert", + "yeast_mitochondrial": "-gcyeast", "protozoan": "-gcprot", "mycoplasma": "-gcmyco" + } + if genetic_code != "standard": + cmd.append(code_map[genetic_code]) + + if allow_introns: + cmd.append("-i") + if topology == "linear": + cmd.append("-l") + if post_process_cutoff is not None: + cmd.extend(["-ps", str(post_process_cutoff)]) + if no_post_process: + cmd.append("-d") + if ecoli_tloop: + cmd.append("-a") + if permuted_exons: + cmd.append("-rp") + + if input_format is not None: + cmd.extend(["-if", str(input_format)]) + + if strand == "sense": + cmd.append("-sense") + elif strand == "complementary": + cmd.append("-sc") + + cmd.append(str(sequence_file)) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + encoding='utf-8' + ) + except FileNotFoundError: + raise RuntimeError("aragorn executable not found. Please ensure it is in your system's PATH.") + except subprocess.CalledProcessError as e: + logging.error(f"ARAGORN execution failed with return code {e.returncode}") + logging.error(f"Stderr: {e.stderr}") + # Re-raise as a more informative exception for the MCP environment + raise RuntimeError(f"ARAGORN execution failed. Stderr: {e.stderr}") + + # --- Structured Result Return --- + output_files_list = [str(output_file)] if output_file else [] + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files_list + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_aragorn/app/aragorn_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_aragorn/app/aragorn_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9883b979b38c67b0178e0418c3ae5f3ff6e8fbcd --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_aragorn/app/aragorn_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_aragorn/app/aragorn_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_aragorn' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_aragorn/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_aragorn/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_aragorn/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_aragorn/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_aragorn/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..90e1e956e6c62b275450b10dc67a2ed34c58bb0c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_aragorn/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-aragorn: + build: . + image: mcp-aragorn:latest + container_name: mcp-aragorn + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=aragorn + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_aragorn/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_aragorn/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..613d2e28d7109c3855893da6fba0c4cf25384747 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_aragorn/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - aragorn + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_aragorn/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_aragorn/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_aragorn/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_auspice/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_auspice/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d25db4d616a48de43407b52e112dc59dc8f0ce5f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_auspice/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install auspice via conda (e.g., from bioconda) +RUN conda install -c bioconda auspice -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/auspice_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/auspice_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/auspice_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_auspice/app/__pycache__/auspice_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_auspice/app/__pycache__/auspice_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21d1bda44d86bfb135031f0f18c95fef10f4323e Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_auspice/app/__pycache__/auspice_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_auspice/app/auspice_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_auspice/app/auspice_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d05a3c6b0b4d3803a096d4cbc127ebcebec93641 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_auspice/app/auspice_server.py @@ -0,0 +1,406 @@ +import subprocess +from pathlib import Path +from typing import Dict, List, Optional, Any + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided by the MCP framework. +def tool(): + def decorator(f): + return f + return decorator + +mcp = type("mcp", (), {"tool": tool})() + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_auspice' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def view( + dataset_dir: Optional[List[Path]] = None, + host: str = "localhost", + port: int = 4000, + verbose: bool = False, + allow_remote_access: bool = False, + handlers: Optional[Path] = None, + config: Optional[Path] = None, + extend: Optional[Path] = None, +) -> Dict[str, str]: + """ + Starts the Auspice server to view and explore phylogenomic data. + Note: This command starts a long-running server process and may not be suitable + for automated workflows that expect a command to terminate. + + Args: + dataset_dir: Directory of datasets to serve. Can be specified multiple times. + host: Host IP address to listen on. + port: Port to listen on. + verbose: Print more information to the console. + allow_remote_access: Allow remote connections to the server. + handlers: Path to a Javascript file with custom API handlers. + config: Path to a custom config JSON file. + extend: Path to a directory containing custom client code. + + Returns: + A dictionary containing the command executed, stdout, and stderr. + """ + cmd = ["auspice", "view"] + + if dataset_dir: + for d in dataset_dir: + if not d.is_dir(): + raise ValueError(f"Dataset directory not found: {d}") + cmd.extend(["--datasetDir", str(d)]) + + cmd.extend(["--host", host]) + cmd.extend(["--port", str(port)]) + + if verbose: + cmd.append("--verbose") + if allow_remote_access: + cmd.append("--allow-remote-access") + + if handlers: + if not handlers.is_file(): + raise FileNotFoundError(f"Handlers file not found: {handlers}") + cmd.extend(["--handlers", str(handlers)]) + + if config: + if not config.is_file(): + raise FileNotFoundError(f"Config file not found: {config}") + cmd.extend(["--config", str(config)]) + + if extend: + if not extend.is_dir(): + raise ValueError(f"Extend directory not found: {extend}") + cmd.extend(["--extend", str(extend)]) + + try: + # This will block until the server is manually stopped. + result = subprocess.run( + cmd, capture_output=True, text=True, check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": "Error: 'auspice' command not found. Please ensure it is installed and in your PATH.", + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + } + + +@mcp.tool() +def build( + verbose: bool = False, + extend: Optional[Path] = None, + deploy_path: Optional[str] = None, +) -> Dict[str, Any]: + """ + Creates a production bundle of the Auspice client-side app. + The output is typically created in a './dist' directory. + + Args: + verbose: Print more information to the console. + extend: Path to a directory containing custom client code. + deploy_path: Path to deploy the app to (e.g., for GitHub pages). + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + cmd = ["auspice", "build"] + + if verbose: + cmd.append("--verbose") + + if extend: + if not extend.is_dir(): + raise ValueError(f"Extend directory not found: {extend}") + cmd.extend(["--extend", str(extend)]) + + if deploy_path: + cmd.extend(["--deploy-path", deploy_path]) + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True + ) + output_dir = Path("./dist") + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": { + "build_directory": str(output_dir) if output_dir.exists() else "Not created" + } + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": "Error: 'auspice' command not found. Please ensure it is installed and in your PATH.", + "output_files": {} + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": {} + } + + +@mcp.tool() +def export_v1( + dataset_dir: Path, + output_dir: Path, + verbose: bool = False, +) -> Dict[str, Any]: + """ + Exports auspice v1 JSONs to create a static site. + This is a deprecated command and will be removed in a future version. + + Args: + dataset_dir: Directory of datasets to export. + output_dir: Directory to export the auspice client and datasets to. + verbose: Print more information to the console. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output directory. + """ + cmd = ["auspice", "export", "v1"] + + if not dataset_dir.is_dir(): + raise ValueError(f"Dataset directory not found: {dataset_dir}") + cmd.extend(["--dataset-dir", str(dataset_dir)]) + + output_dir.mkdir(parents=True, exist_ok=True) + cmd.extend(["--output-dir", str(output_dir)]) + + if verbose: + cmd.append("--verbose") + + 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": { + "export_directory": str(output_dir) + } + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": "Error: 'auspice' command not found. Please ensure it is installed and in your PATH.", + "output_files": {} + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": {} + } + + +@mcp.tool() +def export_v2( + dataset_dir: Path, + output_dir: Path, + verbose: bool = False, + config: Optional[Path] = None, + extend: Optional[Path] = None, + deploy_path: Optional[str] = None, +) -> Dict[str, Any]: + """ + Exports auspice v2 JSONs to create a static site. + + Args: + dataset_dir: Directory of datasets to export. + output_dir: Directory to export the auspice client and datasets to. + verbose: Print more information to the console. + config: Path to a custom config JSON file. + extend: Path to a directory containing custom client code. + deploy_path: Path to deploy the app to (e.g., for GitHub pages). + + Returns: + A dictionary containing the command executed, stdout, stderr, and output directory. + """ + cmd = ["auspice", "export", "v2"] + + if not dataset_dir.is_dir(): + raise ValueError(f"Dataset directory not found: {dataset_dir}") + cmd.extend(["--dataset-dir", str(dataset_dir)]) + + output_dir.mkdir(parents=True, exist_ok=True) + cmd.extend(["--output-dir", str(output_dir)]) + + if verbose: + cmd.append("--verbose") + + if config: + if not config.is_file(): + raise FileNotFoundError(f"Config file not found: {config}") + cmd.extend(["--config", str(config)]) + + if extend: + if not extend.is_dir(): + raise ValueError(f"Extend directory not found: {extend}") + cmd.extend(["--extend", str(extend)]) + + if deploy_path: + cmd.extend(["--deploy-path", deploy_path]) + + 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": { + "export_directory": str(output_dir) + } + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": "Error: 'auspice' command not found. Please ensure it is installed and in your PATH.", + "output_files": {} + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": {} + } + + +@mcp.tool() +def develop( + verbose: bool = False, + extend: Optional[Path] = None, + config: Optional[Path] = None, + dataset_dir: Optional[List[Path]] = None, + port: int = 4000, + host: str = "localhost", +) -> Dict[str, str]: + """ + Starts the Auspice development server with hot-reloading. + Note: This command starts a long-running server process and may not be suitable + for automated workflows that expect a command to terminate. + + Args: + verbose: Print more information to the console. + extend: Path to a directory containing custom client code. + config: Path to a custom config JSON file. + dataset_dir: Directory of datasets to serve. Can be specified multiple times. + port: Port to listen on. + host: Host IP address to listen on. + + Returns: + A dictionary containing the command executed, stdout, and stderr. + """ + cmd = ["auspice", "develop"] + + if verbose: + cmd.append("--verbose") + + if extend: + if not extend.is_dir(): + raise ValueError(f"Extend directory not found: {extend}") + cmd.extend(["--extend", str(extend)]) + + if config: + if not config.is_file(): + raise FileNotFoundError(f"Config file not found: {config}") + cmd.extend(["--config", str(config)]) + + if dataset_dir: + for d in dataset_dir: + if not d.is_dir(): + raise ValueError(f"Dataset directory not found: {d}") + cmd.extend(["--datasetDir", str(d)]) + + cmd.extend(["--port", str(port)]) + cmd.extend(["--host", host]) + + try: + # This will block until the server is manually stopped. + result = subprocess.run( + cmd, capture_output=True, text=True, check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": "Error: 'auspice' command not found. Please ensure it is installed and in your PATH.", + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + } + + +@mcp.tool() +def version() -> Dict[str, str]: + """ + Prints the version number of auspice and exits. + + Returns: + A dictionary containing the command executed, stdout, stderr, and parsed version. + """ + cmd = ["auspice", "version"] + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "version": result.stdout.strip(), + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": "Error: 'auspice' command not found. Please ensure it is installed and in your PATH.", + "version": "", + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "version": "", + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_auspice/app/auspice_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_auspice/app/auspice_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..10672de8177e875f0e1ea33ba91e532444fb5b77 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_auspice/app/auspice_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_auspice/app/auspice_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_auspice' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_auspice/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_auspice/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_auspice/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_auspice/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_auspice/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..9a3df520dc961f08ec57d610d823931b1d415765 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_auspice/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-auspice: + build: . + image: mcp-auspice:latest + container_name: mcp-auspice + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=auspice + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_auspice/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_auspice/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..492ce6777fe7c7088cc1c347fa0b1d14cf597302 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_auspice/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - auspice + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_auspice/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_auspice/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_auspice/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_barrnap/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_barrnap/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ea6fbd530245c85ba9bce7c9fb9fbfde679a175d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/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/Biomanus/biomni_web/backend/data/mcp_generated/mcp_barrnap/app/__pycache__/barrnap_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_barrnap/app/__pycache__/barrnap_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b9604af963abe5e95265dd08534526586ca47ff5 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_barrnap/app/__pycache__/barrnap_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_barrnap/app/barrnap_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_barrnap/app/barrnap_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f60f2cacae1abf7b4488df2f2c902c002749e09d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_barrnap/app/barrnap_server.py @@ -0,0 +1,246 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Union + +# Assume mcp is imported and available in the actual runtime environment +# from mcp import tool + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_barrnap' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def perl( + program_file: Optional[Path] = None, + program_arguments: Optional[List[str]] = None, + zero_record_separator: Optional[str] = None, + autosplit_mode: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + debugger: Optional[str] = None, + debug_flags: Optional[str] = None, + execute_program_line: Optional[List[str]] = None, + execute_program_line_extended: Optional[List[str]] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + in_place_edit_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_ending_processing: Optional[str] = None, + use_modules: Optional[List[str]] = None, + no_modules: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + rudimentary_switches: bool = False, + search_path_for_program: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core_after_parsing: bool = False, + allow_unsafe_operations: bool = False, + print_version: bool = False, + print_config_summary: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_text_before_shebang: Optional[Path] = None, + disable_all_warnings: bool = False, +) -> dict: + """ + Executes Perl programs with various command-line switches. + + This tool provides an interface to the Perl interpreter, allowing users to + run Perl scripts, execute one-liners, and control various aspects of Perl's + behavior, including debugging, warnings, Unicode features, and module loading. + + Args: + program_file: Path to the Perl program file to execute. + If -e or -E is used, this should typically be omitted. + program_arguments: List of arguments to pass to the Perl program. + zero_record_separator: Specify record separator. If an empty string, uses '\0'. + Otherwise, specifies an octal value. (e.g., "0" for -0, "0777" for -0777) + autosplit_mode: Enable autosplit mode with -n or -p (splits $_ into @F). + unicode_features: Enables the listed Unicode features (e.g., "all", "io"). + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks). + debugger: Run program under debugger. If an empty string, uses default debugger (-d). + Otherwise, specifies a debugger (e.g., ":MyDebugger"). + debug_flags: Set debugging flags (argument is a bit mask or alphabets). + execute_program_line: One line of program to execute. Can be specified multiple times. + If used, program_file should typically be omitted. + execute_program_line_extended: Like -e, but enables all optional features. + Can be specified multiple times. + If used, program_file should typically be omitted. + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup. + split_pattern: split() pattern for -a switch (e.g., "/\t/"). + in_place_edit_extension: Edit <> files in place. If an empty string, no backup is made (-i). + If an extension is supplied (e.g., ".bak"), a backup is made. + include_directories: Specify @INC/#include directory. Can be specified multiple times. + line_ending_processing: Enable line ending processing. If an empty string, enables default (-l). + Otherwise, specifies line terminator (e.g., "012"). + use_modules: Execute "use module..." before executing program. Can be specified multiple times. + Corresponds to -m or -M. + no_modules: Execute "no module..." before executing program. Can be specified multiple times. + Corresponds to -m- or -M-. + loop_around_program: Assume "while (<>) { ... }" loop around program (-n). + loop_and_print: Assume loop like -n but print line also, like sed (-p). + rudimentary_switches: Enable rudimentary parsing for switches after programfile (-s). + search_path_for_program: Look for programfile using PATH environment variable (-S). + tainting_warnings: Enable tainting warnings (-t). + tainting_checks: Enable tainting checks (-T). + dump_core_after_parsing: Dump core after parsing program (-u). + allow_unsafe_operations: Allow unsafe operations (-U). + print_version: Print version, patchlevel and license (-v). + print_config_summary: Print configuration summary. If an empty string, prints full summary (-V). + Otherwise, prints a single Config.pm variable (e.g., ":archname"). + enable_warnings: Enable many useful warnings (-w). + enable_all_warnings: Enable all warnings (-W). + ignore_text_before_shebang: Ignore text before #!perl line. If None, just ignores (-x). + Optionally change to directory (e.g., Path("/tmp")). + disable_all_warnings: Disable all warnings (-X). + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + cmd = ["perl"] + output_files = [] + + # Input validation + if program_file and not program_file.is_file(): + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": f"Error: Program file '{program_file}' not found.", + "output_files": [], + } + + if (execute_program_line or execute_program_line_extended) and program_file: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": "Error: Cannot use -e/-E with a program file. Please omit program_file.", + "output_files": [], + } + + # Add switches + if zero_record_separator is not None: + cmd.append(f"-0{zero_record_separator}") + if autosplit_mode: + cmd.append("-a") + if unicode_features: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if debugger is not None: + cmd.append(f"-d{':' if debugger else ''}{debugger}") + if debug_flags: + cmd.append(f"-D{debug_flags}") + if execute_program_line: + for line in execute_program_line: + cmd.append("-e") + cmd.append(line) + if execute_program_line_extended: + for line in execute_program_line_extended: + cmd.append("-E") + cmd.append(line) + if no_sitecustomize: + cmd.append("-f") + if split_pattern: + cmd.append(f"-F{split_pattern}") + if in_place_edit_extension is not None: + cmd.append(f"-i{in_place_edit_extension}") + if include_directories: + for directory in include_directories: + if not directory.is_dir(): + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": f"Error: Include directory '{directory}' not found.", + "output_files": [], + } + cmd.append("-I") + cmd.append(str(directory)) + if line_ending_processing is not None: + cmd.append(f"-l{line_ending_processing}") + if use_modules: + for module in use_modules: + # The help document shows -[mM][-]module. + # Assuming -M for 'use' and -m- for 'no'. + # For simplicity, we'll use -M for 'use' as it's more common for explicit module loading. + cmd.append(f"-M{module}") + if no_modules: + for module in no_modules: + cmd.append(f"-M-{module}") # Using -M- for 'no module' + if loop_around_program: + cmd.append("-n") + if loop_and_print: + cmd.append("-p") + if rudimentary_switches: + cmd.append("-s") + if search_path_for_program: + cmd.append("-S") + if tainting_warnings: + cmd.append("-t") + if tainting_checks: + cmd.append("-T") + if dump_core_after_parsing: + cmd.append("-u") + if allow_unsafe_operations: + cmd.append("-U") + if print_version: + cmd.append("-v") + if print_config_summary is not None: + cmd.append(f"-V{':' if print_config_summary else ''}{print_config_summary}") + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if ignore_text_before_shebang is not None: + if ignore_text_before_shebang and not ignore_text_before_shebang.is_dir(): + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": f"Error: Directory for -x '{ignore_text_before_shebang}' not found.", + "output_files": [], + } + cmd.append(f"-x{str(ignore_text_before_shebang) if ignore_text_before_shebang else ''}") + if disable_all_warnings: + cmd.append("-X") + + # Add program file and its arguments + if program_file: + cmd.append(str(program_file)) + if program_arguments: + cmd.extend(program_arguments) + + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": "Error: 'perl' command not found. Ensure Perl is installed and in your PATH.", + "output_files": [], + } + + return { + "command_executed": " ".join(cmd), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_barrnap/app/barrnap_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_barrnap/app/barrnap_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..660c1aed23f0004a91d8dd7eb86dc08cc867556a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_barrnap/app/barrnap_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_barrnap/app/barrnap_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_barrnap' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_barrnap/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_barrnap/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_barrnap/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_barrnap/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_barrnap/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..02c3e28e1c54228dcf0d8b743b2f15fcde7a0c1c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/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/Biomanus/biomni_web/backend/data/mcp_generated/mcp_barrnap/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_barrnap/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eda56f8ba60811468f2c9d2f53a2ff421f7837b6 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/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/Biomanus/biomni_web/backend/data/mcp_generated/mcp_barrnap/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_barrnap/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_barrnap/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedtools/app/__pycache__/bedtools_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedtools/app/__pycache__/bedtools_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5bbc2f9c7cef86cc18ca7451c4727117ffc1c3a4 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedtools/app/__pycache__/bedtools_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedtools/app/__pycache__/bedtools_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedtools/app/__pycache__/bedtools_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8ff21d0315aa340965797b174a7608a3d02b998 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedtools/app/__pycache__/bedtools_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedtools/app/bedtools_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedtools/app/bedtools_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..15ec4000aed6789dce3c9ff2d561f14622060067 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bedtools/app/bedtools_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedtools/app/bedtools_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bedtools' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bin2cell/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bin2cell/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a472346995a69a9ad4e37300bc0e533fc606e73a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/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/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bin2cell/app/__pycache__/bin2cell_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bin2cell/app/__pycache__/bin2cell_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d06b3af3d3f9947ca1d904a2c8398e3e359a04cd Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bin2cell/app/__pycache__/bin2cell_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bin2cell/app/bin2cell_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bin2cell/app/bin2cell_server.py new file mode 100644 index 0000000000000000000000000000000000000000..639764038d24aad6fad508440e59677953d234df --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bin2cell/app/bin2cell_server.py @@ -0,0 +1,286 @@ +import subprocess +from pathlib import Path +from typing import Optional, List + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bin2cell' +mcp = FastMCP(SERVER_NAME) + +@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 + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bin2cell/app/bin2cell_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bin2cell/app/bin2cell_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..bfd90ecb74cef8fd7f0972f4fac324727ce7f5cc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bin2cell/app/bin2cell_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bin2cell/app/bin2cell_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bin2cell' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bin2cell/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bin2cell/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bin2cell/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bin2cell/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bin2cell/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..098ceb799750eea4200969287a28a53212a12fc4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/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/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bin2cell/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bin2cell/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eb8ff7f84e83b73a3a12f8d25a0f5767d0133558 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/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/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bin2cell/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bin2cell/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bin2cell/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-alabaster/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-alabaster/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..adf3034b80c6daf061e68aa17f25bd39e1e1eb37 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-alabaster/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-alabaster via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-alabaster -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-alabaster_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-alabaster_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-alabaster_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-alabaster/app/__pycache__/bioconductor-alabaster_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-alabaster/app/__pycache__/bioconductor-alabaster_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..907f9b0b28b0fbad25403a5fbf8f073247774270 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-alabaster/app/__pycache__/bioconductor-alabaster_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-alabaster/app/bioconductor-alabaster_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-alabaster/app/bioconductor-alabaster_server.py new file mode 100644 index 0000000000000000000000000000000000000000..adb75c86deee5de88a84fd7b75fd2c59e6bb05cd --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-alabaster/app/bioconductor-alabaster_server.py @@ -0,0 +1,66 @@ +import subprocess +import sys +from pathlib import Path +from typing import Optional, List +import tempfile +import logging + +# Configure logging +logging.basicConfig(level=logging.INFO) + +# Mock mcp.tool decorator for standalone execution +class mcp: + def tool(func): + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + return wrapper + +@mcp.tool +def alabaster_check(): + """ + Verifies the installation of the bioconductor-alabaster umbrella package. + + This tool does not perform any data analysis. Instead, it attempts to load + the 'alabaster' library within an R session to confirm that the Alabaster + framework and all its components are correctly installed and accessible. + A successful execution indicates the environment is ready for tools that + depend on the Alabaster suite. + """ + command = ["Rscript", "-e", "library(alabaster)"] + command_str = " ".join(command) + logging.info(f"Executing command: {command_str}") + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + stdout = process.stdout + stderr = process.stderr + logging.info("bioconductor-alabaster package loaded successfully.") + + except FileNotFoundError: + logging.error("Rscript not found. Please ensure R is installed and in your PATH.") + # Re-raise with a more informative message for the MCP context + raise RuntimeError("Rscript executable not found. R installation is required.") from None + + except subprocess.CalledProcessError as e: + logging.error(f"Error loading bioconductor-alabaster package.") + logging.error(f"Stderr: {e.stderr}") + logging.error(f"Stdout: {e.stdout}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to load the 'alabaster' R library. It may not be installed correctly.", + "return_code": e.returncode, + } + + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": stderr, + "status": "success" + } diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-alabaster/app/bioconductor-alabaster_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-alabaster/app/bioconductor-alabaster_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fefef75e961a8cb656aab3b33c3640c8b91c410d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-alabaster/app/bioconductor-alabaster_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-alabaster/app/bioconductor-alabaster_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_alabaster' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-alabaster/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-alabaster/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-alabaster/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-alabaster/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-alabaster/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..1e7f78ab1fdc06a0f6527a02824e5ac4283ab2f5 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-alabaster/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-alabaster: + build: . + image: mcp-bioconductor-alabaster:latest + container_name: mcp-bioconductor-alabaster + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-alabaster + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-alabaster/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-alabaster/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..005b89505905813f059b39eff70b16c86b5b6306 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-alabaster/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-alabaster + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-alabaster/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-alabaster/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-alabaster/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apeglm/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apeglm/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..57cd40f2416b347da5e546796f7f35bde99211bf --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apeglm/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-apeglm via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-apeglm -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY bioconductor-apeglm_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-apeglm_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-apeglm_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apeglm/app/__pycache__/bioconductor-apeglm_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apeglm/app/__pycache__/bioconductor-apeglm_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf85d8d2607b47aa7b5892419f6a47050d5dff4f Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apeglm/app/__pycache__/bioconductor-apeglm_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apeglm/app/bioconductor-apeglm_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apeglm/app/bioconductor-apeglm_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d9e532794f69d56fd258bf850b3e370bbfcb7f07 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apeglm/app/bioconductor-apeglm_server.py @@ -0,0 +1,133 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_apeglm' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_r_script( + r_script_file: Optional[Path] = None, + r_expressions: Optional[List[str]] = None, + script_args: Optional[List[str]] = None, + verbose: bool = False, + default_packages: Optional[str] = None, + save_workspace: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: bool = False, + restore_workspace: bool = False, + vanilla: bool = False, +) -> Dict[str, Any]: + """ + Executes an R script file or R expressions using the Rscript command. + + This tool provides a wrapper for the Rscript command, allowing users to run + R code with various configuration options. It supports executing a specified + R script file or a list of R expressions directly. It also allows passing + arguments to the R script itself and configuring R's startup behavior. + + Args: + r_script_file: Path to an R script file to execute. Mutually exclusive with `r_expressions`. + r_expressions: A list of R expressions (strings) to execute. Mutually exclusive with `r_script_file`. + script_args: A list of arguments to be passed to the R script or expressions. + verbose: If True, print information on progress (corresponds to Rscript's --verbose). + default_packages: A comma-separated list of package names, or 'NULL', + to set the default packages loaded (corresponds to --default-packages). + save_workspace: If True, save the workspace at the end of the session (corresponds to R's --save). + Ignored if `vanilla` is True. + no_environ: If True, don't read the site and user environment files (corresponds to R's --no-environ). + Ignored if `vanilla` is True. + no_site_file: If True, don't read the site-wide Rprofile (corresponds to R's --no-site-file). + Ignored if `vanilla` is True. + no_init_file: If True, don't read the user R profile (corresponds to R's --no-init-file). + Ignored if `vanilla` is True. + restore_workspace: If True, restore previously saved objects at startup (corresponds to R's --restore). + Ignored if `vanilla` is True. + vanilla: If True, combine --no-save, --no-restore, --no-site-file, --no-init-file, and --no-environ. + This option overrides individual settings for these flags. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + In case of an error, it includes error details and the return code. + + Raises: + ValueError: If neither `r_script_file` nor `r_expressions` is provided, or if both are provided. + FileNotFoundError: If `r_script_file` is provided but does not exist. + """ + command: List[str] = ["Rscript"] + output_files: List[Path] = [] + + # Input validation for script source + if r_script_file is None and r_expressions is None: + raise ValueError("Either 'r_script_file' or 'r_expressions' must be provided.") + if r_script_file is not None and r_expressions is not None: + raise ValueError("Cannot provide both 'r_script_file' and 'r_expressions'. Choose one.") + + if r_script_file: + if not r_script_file.is_file(): + raise FileNotFoundError(f"R script file not found: {r_script_file}") + + # Add Rscript specific options + if verbose: + command.append("--verbose") + if default_packages is not None: + command.append(f"--default-packages={default_packages}") + + # Add R options (passed to R, in addition to --no-echo --no-restore by Rscript) + if vanilla: + command.append("--vanilla") + else: + # Only add these if --vanilla is not set, as --vanilla implies them + if save_workspace: + command.append("--save") + if no_environ: + command.append("--no-environ") + if no_site_file: + command.append("--no-site-file") + if no_init_file: + command.append("--no-init-file") + if restore_workspace: + command.append("--restore") + + # Add the script source (file or expressions) + if r_script_file: + command.append(str(r_script_file)) + elif r_expressions: + for expr in r_expressions: + command.extend(["-e", expr]) + + # Add arguments to the R script + if script_args: + command.extend(script_args) + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "returncode": e.returncode, + "output_files": output_files, + } + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apeglm/app/bioconductor-apeglm_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apeglm/app/bioconductor-apeglm_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c0e18d69352f300b80fbc101a43abe584b7931e0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apeglm/app/bioconductor-apeglm_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-apeglm/app/bioconductor-apeglm_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_apeglm' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apeglm/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apeglm/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e15e303cb39aa7756cd707cc87115c9bf685830c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apeglm/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-apeglm: + build: . + image: mcp-bioconductor-apeglm:latest + container_name: mcp-bioconductor-apeglm + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-apeglm + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apeglm/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apeglm/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ebc2281a594f219239a61a4c8336c9dea78166b1 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apeglm/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-apeglm + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apeglm/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apeglm/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apeglm/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apl/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apl/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..12d5dbd56f0614e144adc7e9f202e95644c3a163 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apl/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-apl via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-apl -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-apl_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-apl_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-apl_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apl/app/__pycache__/bioconductor-apl_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apl/app/__pycache__/bioconductor-apl_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..729733685eb013f2867003aa17d3e5c0168f92ef Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apl/app/__pycache__/bioconductor-apl_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apl/app/bioconductor-apl_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apl/app/bioconductor-apl_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ed368d916170fbb25aee6623ff2fe0fad799467d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apl/app/bioconductor-apl_server.py @@ -0,0 +1,296 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any + +# Note: mcp is not imported as per instructions. + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_apl' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_apl_analysis( + input_seurat_object: Path, + output_directory: Path, + cluster_column: str, + selected_cluster: Optional[str] = None, + organism: Optional[str] = None, + min_genes_per_cluster: int = 5, + top_n_genes_for_report: int = 50, + generate_interactive_plots: bool = False, +) -> Dict[str, Any]: + """ + Performs a hypothetical APL (Association Plots) analysis on single-cell transcriptomics data. + + This function serves as a placeholder for integrating the bioconductor-apl R package. + **Crucially, the specific R functions and their parameters from the APL package + are NOT available in the provided documentation.** Therefore, the R script + executed by this tool contains illustrative placeholders for APL package + function calls. + + In a real implementation, the R script would be populated with specific + calls to functions from the APL R package (e.g., `APL::runAPL`, `APL::plotAP`, + `APL::calculateSpecificityScores`) based on its official documentation + (e.g., the APL Reference Manual PDF or vignettes). + + Args: + input_seurat_object: Path to an RDS file containing a Seurat object or + SingleCellExperiment object. This is the primary input + single-cell data. + output_directory: Path to the directory where output files (plots, + specificity scores, summary) will be saved. + The directory will be created if it does not exist. + cluster_column: The name of the column in the Seurat object's metadata + (or SingleCellExperiment's colData) that contains + cell cluster assignments. + selected_cluster: Optional. If provided, the analysis might focus on + this specific cluster for detailed plots or reports. + Defaults to None, meaning analysis might cover all clusters. + organism: Optional. Specifies the organism for gene annotation, + e.g., 'human' or 'mouse'. This influences which `org.db` + package (`org.Hs.eg.db` or `org.Mm.eg.db`) might be loaded + by the R script. Defaults to None. + min_genes_per_cluster: Hypothetical. Minimum number of genes required + for a cluster to be considered in certain analyses. + Defaults to 5. + top_n_genes_for_report: Hypothetical. Number of top cluster-specific genes + to include in summary reports or plots. Defaults to 50. + generate_interactive_plots: Hypothetical. If True, attempts to generate + interactive plots using `plotly` (if APL supports it). + Defaults to False. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list + of generated output files. + """ + # Input validation + if not input_seurat_object.is_file(): + raise FileNotFoundError(f"Input Seurat/SingleCellExperiment object not found: {input_seurat_object}") + + output_directory.mkdir(parents=True, exist_ok=True) + + # Determine organism-specific package to load in R + org_db_package_load = "" + if organism: + if organism.lower() == "human": + org_db_package_load = "BiocManager::install('org.Hs.eg.db', update = FALSE, ask = FALSE); library(org.Hs.eg.db)" + elif organism.lower() == "mouse": + org_db_package_load = "BiocManager::install('org.Mm.eg.db', update = FALSE, ask = FALSE); library(org.Mm.eg.db)" + else: + # This is a hypothetical validation, as APL might support more or less organisms + raise ValueError(f"Unsupported organism: {organism}. Only 'human' and 'mouse' are hypothetically supported for gene annotation.") + + # R script template + # This template includes installation of common dependencies and placeholders + # for the actual APL package function calls. + R_SCRIPT_TEMPLATE = f""" + # Ensure BiocManager is installed for package management + if (!require("BiocManager", quietly = TRUE)) install.packages("BiocManager") + + # Install APL and its core dependencies (as inferred from conda/bioconductor info) + # update=FALSE and ask=FALSE are used to prevent interactive prompts and unnecessary updates + BiocManager::install("APL", update = FALSE, ask = FALSE) + BiocManager::install("Seurat", update = FALSE, ask = FALSE) + BiocManager::install("SingleCellExperiment", update = FALSE, ask = FALSE) + BiocManager::install("ggplot2", update = FALSE, ask = FALSE) + BiocManager::install("plotly", update = FALSE, ask = FALSE) + BiocManager::install("magrittr", update = FALSE, ask = FALSE) + BiocManager::install("SummarizedExperiment", update = FALSE, ask = FALSE) + BiocManager::install("topGO", update = FALSE, ask = FALSE) + BiocManager::install("methods", update = FALSE, ask = FALSE) + BiocManager::install("stats", update = FALSE, ask = FALSE) + BiocManager::install("utils", update = FALSE, ask = FALSE) + BiocManager::install("rlang", update = FALSE, ask = FALSE) + BiocManager::install("ggrepel", update = FALSE, ask = FALSE) + BiocManager::install("viridisLite", update = FALSE, ask = FALSE) + BiocManager::install("reticulate", update = FALSE, ask = FALSE) # For python dependencies if APL uses them + BiocManager::install("Matrix", update = FALSE, ask = FALSE) # From conda search (r-matrix) + BiocManager::install("RSpectra", update = FALSE, ask = FALSE) # From conda search (r-rspectra) + BiocManager::install("SeuratObject", update = FALSE, ask = FALSE) # From conda search (r-seuratobject) + + # Load organism-specific gene annotation database if specified + {org_db_package_load} + + # Load necessary libraries + library(APL) + library(Seurat) + library(SingleCellExperiment) + library(ggplot2) + library(plotly) + library(magrittr) # For %>% + library(SummarizedExperiment) + library(topGO) + library(methods) + library(stats) + library(utils) + library(rlang) + library(ggrepel) + library(viridisLite) + library(reticulate) # If APL uses python/pytorch/numpy via reticulate + + # Set output directory + output_dir <- "{output_directory}" + dir.create(output_dir, showWarnings = FALSE) + + # Load input data + # Assuming input_seurat_object is a path to an RDS file containing a Seurat object + seurat_obj <- readRDS("{input_seurat_object}") + + # Ensure the object is in a format APL expects, e.g., SingleCellExperiment + # APL's dependencies include both Seurat and SingleCellExperiment, + # so it might accept either or have conversion utilities. + # For robustness, we convert to SingleCellExperiment if it's a Seurat object. + if (inherits(seurat_obj, "Seurat")) {{ + message("Converting Seurat object to SingleCellExperiment for APL analysis.") + sce_obj <- as.SingleCellExperiment(seurat_obj) + }} else if (inherits(seurat_obj, "SingleCellExperiment")) {{ + sce_obj <- seurat_obj + }} else {{ + stop("Input object must be a Seurat or SingleCellExperiment object.") + }} + + # Validate cluster_column presence in colData + if (!("{cluster_column}" %in% names(colData(sce_obj)))) {{ + stop(paste0("Cluster column '", "{cluster_column}", "' not found in colData of the input object.")) + }} + + # --- Placeholder for actual APL function calls --- + # The following R code is illustrative and based on the package description. + # It needs to be replaced with actual function calls from the APL R package + # documentation (e.g., APL::runAPL, APL::plotAP, APL::calculateSpecificityScores). + + tryCatch({{ + message("Starting hypothetical APL analysis...") + + # In a real scenario, you would call APL functions here, for example: + # 1. Run Correspondence Analysis and prepare APL-specific data structure: + # apl_results_obj <- APL::runAPL(sce_obj, group_by = "{cluster_column}", + # min_genes = {min_genes_per_cluster}) + # + # 2. Calculate gene specificity scores: + # specificity_scores_df <- APL::calculateSpecificityScores(apl_results_obj) + # write.csv(specificity_scores_df, file.path(output_dir, "gene_specificity_scores.csv"), row.names = FALSE) + # + # 3. Generate Association Plots: + # if (!is.null("{selected_cluster_r_val}")) {{ + # ap_plot_selected <- APL::plotAssociationPlot(apl_results_obj, cluster = "{selected_cluster}", + # top_n = {top_n_genes_for_report}) + # ggplot2::ggsave(file.path(output_dir, "association_plot_{selected_cluster}.png"), ap_plot_selected, width = 10, height = 8) + # }} else {{ + # ap_plot_all <- APL::plotAssociationPlot(apl_results_obj, top_n = {top_n_genes_for_report}) + # ggplot2::ggsave(file.path(output_dir, "association_plot_all_clusters.png"), ap_plot_all, width = 10, height = 8) + # }} + # + # 4. Generate interactive plots if requested (assuming APL has such a function): + # if ({'TRUE' if generate_interactive_plots else 'FALSE'}) {{ + # interactive_ap_plot <- APL::plotInteractiveAP(apl_results_obj) + # htmlwidgets::saveWidget(interactive_ap_plot, file.path(output_dir, "interactive_association_plot.html")) + # }} + + # --- Dummy output generation for demonstration --- + # Create a dummy output file to simulate a summary report + dummy_output_path <- file.path(output_dir, "apl_analysis_summary.txt") + file_conn <- file(dummy_output_path) + writeLines(c( + "APL Analysis Summary (Hypothetical Output)", + paste("Input object:", "{input_seurat_object}"), + paste("Cluster column:", "{cluster_column}"), + paste("Selected cluster (if any):", "{selected_cluster_r_val}"), + paste("Organism (if specified):", "{organism_r_val}"), + paste("Min genes per cluster (hypothetical):", "{min_genes_per_cluster}"), + paste("Top N genes for report (hypothetical):", "{top_n_genes_for_report}"), + paste("Generate interactive plots (hypothetical):", "{'TRUE' if generate_interactive_plots else 'FALSE'}"), + "", + "This is a placeholder output. In a real scenario, APL functions would generate", + "cluster-specific gene lists, specificity scores (e.g., gene_specificity_scores.csv),", + "and various plots (e.g., Association Plots as PNGs and/or interactive HTMLs)." + ), file_conn) + close(file_conn) + + # Save a dummy plot (PNG) + p_png <- ggplot2::ggplot(data.frame(x=1:10, y=1:10, cluster=factor(rep(1:2, each=5))), ggplot2::aes(x,y, color=cluster)) + + ggplot2::geom_point() + + ggplot2::ggtitle("Dummy APL Plot (PNG)") + + ggplot2::theme_minimal() + ggplot2::ggsave(file.path(output_dir, "dummy_apl_plot.png"), p_png, width = 7, height = 5) + + # Save a dummy interactive plot (HTML) if requested + if ({'TRUE' if generate_interactive_plots else 'FALSE'}) {{ + p_html <- plotly::ggplotly(p_png) + htmlwidgets::saveWidget(p_html, file.path(output_dir, "dummy_apl_interactive_plot.html")) + }} + + message("Hypothetical APL analysis completed. Check output directory for dummy files.") + + }}, error = function(e) {{ + stop(paste("R Error:", e$message)) + }}) + """ + + # Prepare R-compatible values for optional parameters + selected_cluster_r_val = f"'{selected_cluster}'" if selected_cluster is not None else "NULL" + organism_r_val = f"'{organism}'" if organism is not None else "NULL" + + # Replace placeholders in the R script content + r_script_content = R_SCRIPT_TEMPLATE.format( + input_seurat_object=input_seurat_object.as_posix(), + output_directory=output_directory.as_posix(), + cluster_column=cluster_column, + selected_cluster=selected_cluster, # Used for filename, not R value + selected_cluster_r_val=selected_cluster_r_val, # Used for R code + organism=organism, # Used for filename/summary, not R value + organism_r_val=organism_r_val, # Used for R code + min_genes_per_cluster=min_genes_per_cluster, + top_n_genes_for_report=top_n_genes_for_report, + generate_interactive_plots=generate_interactive_plots, + ) + + # Create a temporary R script file + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".R") as temp_r_script: + temp_r_script.write(r_script_content) + temp_r_script_path = Path(temp_r_script.name) + + command = ["Rscript", temp_r_script_path.as_posix()] + command_executed = " ".join(command) + + stdout = "" + stderr = "" + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + encoding="utf-8" + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + # Clean up temporary R script on error + temp_r_script_path.unlink(missing_ok=True) + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed with exit code {e.returncode}. " + f"See stderr for R-specific error messages.", + "output_files": [], + } + finally: + # Always clean up the temporary R script + temp_r_script_path.unlink(missing_ok=True) + + # Collect all generated files in the output directory + output_files = [str(f) for f in output_directory.rglob("*") if f.is_file()] + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apl/app/bioconductor-apl_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apl/app/bioconductor-apl_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..efd5cdecc96c621c650f4d5d3fb013dcca34ea34 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apl/app/bioconductor-apl_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-apl/app/bioconductor-apl_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_apl' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apl/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apl/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apl/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apl/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apl/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..683057b32a92cff6c48a6b412fe553e6110b0697 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apl/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-apl: + build: . + image: mcp-bioconductor-apl:latest + container_name: mcp-bioconductor-apl + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-apl + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apl/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apl/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4bbe91da143156538097572747ac1998fc242e59 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apl/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-apl + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apl/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apl/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-apl/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-beachmat/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-beachmat/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e2d1ddf443e6b5ba969dbb4c0bd4f54e64efe2ee --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-beachmat/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-beachmat via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-beachmat -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY bioconductor-beachmat_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-beachmat_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-beachmat_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-beachmat/app/__pycache__/bioconductor-beachmat_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-beachmat/app/__pycache__/bioconductor-beachmat_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cf1dcbf88650dbe243c06e6d92fff4d10acef56a Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-beachmat/app/__pycache__/bioconductor-beachmat_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-beachmat/app/bioconductor-beachmat_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-beachmat/app/bioconductor-beachmat_server.py new file mode 100644 index 0000000000000000000000000000000000000000..18ac9eb5a570aadfe3747f1bdf3dd791c51a3dcd --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-beachmat/app/bioconductor-beachmat_server.py @@ -0,0 +1,226 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_beachmat' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def rscript_run_script( + script_path: str, + args: List[str] = [], + vanilla: bool = True, + save: bool = False, + restore: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: bool = False, + verbose: bool = False, + default_packages: Optional[str] = None, +) -> Dict[str, Any]: + """ + Execute an R script file using Rscript, typically used for Bioconductor/beachmat workflows. + + Args: + script_path: Path to the R script file (.R). + args: Additional command line arguments passed to the script. + vanilla: Combine --no-save, --no-restore, --no-site-file, --no-init-file and --no-environ. + save: Do save workspace at the end of the session. + restore: Do restore previously saved objects at startup. + no_environ: Don't read the site and user environment files. + no_site_file: Don't read the site-wide Rprofile. + no_init_file: Don't read the user R profile. + verbose: Print information on progress. + default_packages: Comma-separated set of package names, or 'NULL'. + """ + script_file = Path(script_path) + if not script_file.exists(): + return {"error": f"Script file not found: {script_path}"} + + cmd = ["Rscript"] + + # Add options + if vanilla: + cmd.append("--vanilla") + if save: + cmd.append("--save") + if restore: + cmd.append("--restore") + if no_environ: + cmd.append("--no-environ") + if no_site_file: + cmd.append("--no-site-file") + if no_init_file: + cmd.append("--no-init-file") + if verbose: + cmd.append("--verbose") + if default_packages: + cmd.append(f"--default-packages={default_packages}") + + cmd.append(str(script_file)) + + if args: + cmd.extend(args) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def rscript_run_expression( + expressions: List[str], + vanilla: bool = True, + save: bool = False, + restore: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: bool = False, + verbose: bool = False, + default_packages: Optional[str] = None, +) -> Dict[str, Any]: + """ + Execute one or more R expressions directly from the command line. + Useful for quick beachmat matrix manipulations or checks. + + Args: + expressions: A list of R code strings to execute (each corresponds to a -e flag). + vanilla: Combine --no-save, --no-restore, --no-site-file, --no-init-file and --no-environ. + save: Do save workspace at the end of the session. + restore: Do restore previously saved objects at startup. + no_environ: Don't read the site and user environment files. + no_site_file: Don't read the site-wide Rprofile. + no_init_file: Don't read the user R profile. + verbose: Print information on progress. + default_packages: Comma-separated set of package names, or 'NULL'. + """ + if not expressions: + return {"error": "No expressions provided."} + + cmd = ["Rscript"] + + # Add options + if vanilla: + cmd.append("--vanilla") + if save: + cmd.append("--save") + if restore: + cmd.append("--restore") + if no_environ: + cmd.append("--no-environ") + if no_site_file: + cmd.append("--no-site-file") + if no_init_file: + cmd.append("--no-init-file") + if verbose: + cmd.append("--verbose") + if default_packages: + cmd.append(f"--default-packages={default_packages}") + + for expr in expressions: + cmd.extend(["-e", expr]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def beachmat_inspect_matrix( + rds_path: str, +) -> Dict[str, Any]: + """ + Specific utility to inspect an R matrix object (RDS file) using the beachmat package logic. + Identifies matrix class, dimensions, and storage mode. + + Args: + rds_path: Path to an RDS file containing a matrix-like object. + """ + input_path = Path(rds_path) + if not input_path.exists(): + return {"error": f"RDS file not found: {rds_path}"} + + # R code to inspect the matrix using beachmat-compatible logic + r_code = ( + "suppressPackageStartupMessages(library(beachmat)); " + f"mat <- readRDS('{str(input_path)}'); " + "cat('--- Matrix Metadata ---\\n'); " + "cat('Class:', paste(class(mat), collapse=', '), '\\n'); " + "cat('Dimensions:', paste(dim(mat), collapse=' x '), '\\n'); " + "if(is(mat, 'dgCMatrix')) { cat('Type: Sparse (dgCMatrix)\\n') } " + "else if(is(mat, 'HDF5Matrix')) { cat('Type: HDF5-backed\\n') } " + "else { cat('Type: Dense/Other\\n') }; " + "cat('Storage Mode:', storage.mode(mat), '\\n')" + ) + + cmd = ["Rscript", "--vanilla", "-e", r_code] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Ensure 'beachmat' and 'DelayedArray' are installed in the R environment.", + "status": "error" + } + +@mcp.tool() +def rscript_get_version() -> Dict[str, Any]: + """ + Get the version information for Rscript and the R environment. + """ + cmd = ["Rscript", "--version"] + try: + # Rscript --version often outputs to stderr + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-beachmat/app/bioconductor-beachmat_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-beachmat/app/bioconductor-beachmat_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6bea6437b8fda4e30f7fbc5555813bf1f5332f33 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-beachmat/app/bioconductor-beachmat_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-beachmat/app/bioconductor-beachmat_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_beachmat' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-beachmat/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-beachmat/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..1a3717e241b2cd27a16a8f9aa28e280a06f484e4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-beachmat/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-beachmat: + build: . + image: mcp-bioconductor-beachmat:latest + container_name: mcp-bioconductor-beachmat + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-beachmat + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-beachmat/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-beachmat/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..02751f5276ca8f7f7c000952c3eb4b28cd1a78a6 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-beachmat/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-beachmat + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-beachmat/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-beachmat/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-beachmat/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-bluster/app/__pycache__/bioconductor-bluster_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-bluster/app/__pycache__/bioconductor-bluster_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..367f1981798ab83669339823ae01fe0a9419cf54 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-bluster/app/__pycache__/bioconductor-bluster_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-bluster/app/bioconductor-bluster_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-bluster/app/bioconductor-bluster_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2935b5ce2a4bf310718ff9792ee045ea02f0e2cb --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-bluster/app/bioconductor-bluster_server.py @@ -0,0 +1,618 @@ +import subprocess +import tempfile +import os +from pathlib import Path +from typing import Optional, List, Dict, Any + +# Note: bioconductor-bluster is an R package and does not have a direct command-line interface +# that can be executed via `subprocess.run` in the traditional sense (like `samtools` or `bwa`). +# To wrap its functionality, we need to generate and execute R scripts using `Rscript`. +# This approach effectively creates a "command-line interface" for specific R functions. +# +# The following functions demonstrate how to wrap key functionalities of the 'bluster' R package +# by generating an R script on the fly and executing it. +# +# Prerequisites: +# 1. An R environment must be installed and accessible in the system's PATH. +# 2. The 'bluster' Bioconductor package (and its dependencies) must be installed in the R environment. +# This can typically be done in R with: +# if (!requireNamespace("BiocManager", quietly = TRUE)) +# install.packages("BiocManager") +# BiocManager::install("bluster") +# install.packages("utils") # For read.csv/write.csv + +def _run_r_script(r_script_content: str, output_dir: Path) -> Dict[str, Any]: + """ + Helper function to execute an R script. + """ + with tempfile.TemporaryDirectory() as tmpdir: + script_path = Path(tmpdir) / "bluster_script.R" + with open(script_path, "w") as f: + f.write(r_script_content) + + command = ["Rscript", str(script_path)] + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + cwd=output_dir # Run Rscript in the output directory to simplify file paths + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [] # Specific tools will add their output files + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed with exit code {e.returncode}", + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: Rscript command not found. Please ensure R is installed and in your PATH.", + "error": "Rscript not found", + "output_files": [] + } + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_bluster' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def cluster_rows_kmeans( + input_matrix_file: Path, + k: int, + output_clusters_file: Path, + input_format: str = "csv", + row_names_col: Optional[int] = 1, + seed: Optional[int] = None, + iterations: int = 10, + nstart: int = 1, + min_size: int = 1, + output_dir: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Performs k-means clustering on rows of a matrix using bluster::clusterRows with KmeansParam. + + Args: + input_matrix_file: Path to the input matrix file (e.g., CSV or TSV). + The matrix should have features as columns and samples as rows, + or vice-versa, depending on how 'bluster' interprets it. + Typically, rows are items to be clustered. + k: The number of clusters (k) for k-means. Must be a positive integer. + output_clusters_file: Path to save the output cluster assignments (CSV file). + This file will contain a single column 'cluster' with integer assignments. + input_format: Format of the input matrix file. Can be "csv" or "tsv". + row_names_col: Column index (1-based) to use as row names when reading the input matrix. + Set to None if no row names column is present. + seed: Random seed for reproducibility. If None, no seed is set. + iterations: Maximum number of iterations for k-means. + nstart: Number of random starts for k-means. + min_size: Minimum number of cells in a cluster. Clusters smaller than this are merged. + output_dir: Directory where output files will be written. If None, uses the current working directory. + + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + if not input_matrix_file.exists(): + raise FileNotFoundError(f"Input matrix file not found: {input_matrix_file}") + if not input_matrix_file.is_file(): + raise ValueError(f"Input matrix file is not a regular file: {input_matrix_file}") + + if k <= 0: + raise ValueError("k (number of clusters) must be a positive integer.") + if input_format not in ["csv", "tsv"]: + raise ValueError("input_format must be 'csv' or 'tsv'.") + if row_names_col is not None and row_names_col <= 0: + raise ValueError("row_names_col must be a positive integer or None.") + if iterations <= 0: + raise ValueError("iterations must be a positive integer.") + if nstart <= 0: + raise ValueError("nstart must be a positive integer.") + if min_size <= 0: + raise ValueError("min_size must be a positive integer.") + + if output_dir is None: + output_dir = Path.cwd() + output_dir.mkdir(parents=True, exist_ok=True) + + # Ensure output_clusters_file is just a filename if output_dir is specified + output_clusters_filename = output_clusters_file.name + full_output_clusters_path = output_dir / output_clusters_filename + + # Generate R script content + read_data_func = "read.csv" if input_format == "csv" else "read.delim" + row_names_arg = f"row.names = {row_names_col}" if row_names_col is not None else "" + seed_line = f"set.seed({seed})\n" if seed is not None else "" + + r_script = f""" + library(bluster) + library(utils) # For read.csv/write.csv + + # Set working directory to output_dir for relative paths + setwd("{output_dir.resolve()}") + + {seed_line} + + # Load input matrix + # Using 'tryCatch' for robust error handling within R + data_matrix <- tryCatch({{ + as.matrix({read_data_func}("{input_matrix_file.resolve()}", {row_names_arg})) + }}, error = function(e) {{ + stop(paste("Error reading input matrix file: ", e$message)) + }}) + + # Perform k-means clustering + blus_param <- KmeansParam( + centers = {k}, + iter.max = {iterations}, + nstart = {nstart}, + min.size = {min_size} + ) + + clusters <- tryCatch({{ + clusterRows(data_matrix, blus_param) + }}, error = function(e) {{ + stop(paste("Error during clustering: ", e$message)) + }}) + + # Save cluster assignments + output_df <- data.frame(cluster = clusters) + if (!is.null(rownames(data_matrix))) {{ + rownames(output_df) <- rownames(data_matrix) + }} + write.csv(output_df, "{output_clusters_filename}", row.names = TRUE) + + message("Clustering complete. Results saved to {output_clusters_filename}") + """ + + # Execute R script + result = _run_r_script(r_script, output_dir) + + if "error" not in result: + result["output_files"].append(str(full_output_clusters_path)) + + return result + +@mcp.tool() +def cluster_rows_hclust( + input_matrix_file: Path, + k: Optional[int] = None, + method: str = "ward.D2", + metric: str = "euclidean", + output_clusters_file: Path = Path("hclust_clusters.csv"), + input_format: str = "csv", + row_names_col: Optional[int] = 1, + seed: Optional[int] = None, + output_dir: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Performs hierarchical clustering on rows of a matrix using bluster::clusterRows with HclustParam. + + Args: + input_matrix_file: Path to the input matrix file (e.g., CSV or TSV). + k: The number of clusters to cut the dendrogram into. If None, the full dendrogram is returned + (though for `clusterRows` it will still attempt to cut, so it's usually required). + If not provided, `bluster` might default to a single cluster or error. + It's recommended to provide `k`. + method: The agglomeration method to be used. See `hclust` documentation for options + (e.g., "ward.D2", "single", "complete", "average"). + metric: The distance metric to be used. See `dist` documentation for options + (e.g., "euclidean", "maximum", "manhattan"). + output_clusters_file: Path to save the output cluster assignments (CSV file). + input_format: Format of the input matrix file. Can be "csv" or "tsv". + row_names_col: Column index (1-based) to use as row names when reading the input matrix. + Set to None if no row names column is present. + seed: Random seed for reproducibility. If None, no seed is set. + output_dir: Directory where output files will be written. If None, uses the current working directory. + + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + if not input_matrix_file.exists(): + raise FileNotFoundError(f"Input matrix file not found: {input_matrix_file}") + if not input_matrix_file.is_file(): + raise ValueError(f"Input matrix file is not a regular file: {input_matrix_file}") + + if k is not None and k <= 0: + raise ValueError("k (number of clusters) must be a positive integer or None.") + if method not in ["ward.D", "ward.D2", "single", "complete", "average", "mcquitty", "median", "centroid"]: + raise ValueError(f"Invalid hclust method: {method}. See `hclust` documentation.") + if metric not in ["euclidean", "maximum", "manhattan", "canberra", "binary", "minkowski"]: + raise ValueError(f"Invalid distance metric: {metric}. See `dist` documentation.") + if input_format not in ["csv", "tsv"]: + raise ValueError("input_format must be 'csv' or 'tsv'.") + if row_names_col is not None and row_names_col <= 0: + raise ValueError("row_names_col must be a positive integer or None.") + + if output_dir is None: + output_dir = Path.cwd() + output_dir.mkdir(parents=True, exist_ok=True) + + output_clusters_filename = output_clusters_file.name + full_output_clusters_path = output_dir / output_clusters_filename + + read_data_func = "read.csv" if input_format == "csv" else "read.delim" + row_names_arg = f"row.names = {row_names_col}" if row_names_col is not None else "" + seed_line = f"set.seed({seed})\n" if seed is not None else "" + k_arg = f"cut.k = {k}" if k is not None else "" # bluster::HclustParam uses cut.k + + r_script = f""" + library(bluster) + library(utils) # For read.csv/write.csv + + setwd("{output_dir.resolve()}") + + {seed_line} + + data_matrix <- tryCatch({{ + as.matrix({read_data_func}("{input_matrix_file.resolve()}", {row_names_arg})) + }}, error = function(e) {{ + stop(paste("Error reading input matrix file: ", e$message)) + }}) + + blus_param <- HclustParam( + method = "{method}", + metric = "{metric}" + {f", {k_arg}" if k_arg else ""} + ) + + clusters <- tryCatch({{ + clusterRows(data_matrix, blus_param) + }}, error = function(e) {{ + stop(paste("Error during clustering: ", e$message)) + }}) + + output_df <- data.frame(cluster = clusters) + if (!is.null(rownames(data_matrix))) {{ + rownames(output_df) <- rownames(data_matrix) + }} + write.csv(output_df, "{output_clusters_filename}", row.names = TRUE) + + message("Hierarchical clustering complete. Results saved to {output_clusters_filename}") + """ + + result = _run_r_script(r_script, output_dir) + + if "error" not in result: + result["output_files"].append(str(full_output_clusters_path)) + + return result + +@mcp.tool() +def cluster_rows_snn_graph( + input_matrix_file: Path, + k_neighbors: int, + output_clusters_file: Path = Path("snn_clusters.csv"), + input_format: str = "csv", + row_names_col: Optional[int] = 1, + type: str = "rank", + method: str = "walktrap", + steps: int = 4, + seed: Optional[int] = None, + output_dir: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Performs Shared Nearest Neighbor (SNN) graph-based clustering using bluster::clusterRows with SNNGraphParam. + + Args: + input_matrix_file: Path to the input matrix file (e.g., CSV or TSV). + k_neighbors: Number of nearest neighbors to consider for SNN graph construction. Must be a positive integer. + output_clusters_file: Path to save the output cluster assignments (CSV file). + input_format: Format of the input matrix file. Can be "csv" or "tsv". + row_names_col: Column index (1-based) to use as row names when reading the input matrix. + Set to None if no row names column is present. + type: Type of SNN graph to construct. "rank" (default) or "number". + method: Community detection method for the SNN graph. See `igraph::cluster_walktrap`, `cluster_louvain`, etc. + (e.g., "walktrap", "louvain", "fast_greedy", "leiden"). + steps: Number of random walk steps for "walktrap" method. + seed: Random seed for reproducibility. If None, no seed is set. + output_dir: Directory where output files will be written. If None, uses the current working directory. + + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + if not input_matrix_file.exists(): + raise FileNotFoundError(f"Input matrix file not found: {input_matrix_file}") + if not input_matrix_file.is_file(): + raise ValueError(f"Input matrix file is not a regular file: {input_matrix_file}") + + if k_neighbors <= 0: + raise ValueError("k_neighbors must be a positive integer.") + if input_format not in ["csv", "tsv"]: + raise ValueError("input_format must be 'csv' or 'tsv'.") + if row_names_col is not None and row_names_col <= 0: + raise ValueError("row_names_col must be a positive integer or None.") + if type not in ["rank", "number"]: + raise ValueError("type must be 'rank' or 'number'.") + if method not in ["walktrap", "louvain", "fast_greedy", "leiden", "infomap", "label_prop", "edge_betweenness"]: + raise ValueError(f"Invalid SNN graph community detection method: {method}. See `igraph` documentation.") + if steps <= 0: + raise ValueError("steps must be a positive integer for 'walktrap' method.") + + if output_dir is None: + output_dir = Path.cwd() + output_dir.mkdir(parents=True, exist_ok=True) + + output_clusters_filename = output_clusters_file.name + full_output_clusters_path = output_dir / output_clusters_filename + + read_data_func = "read.csv" if input_format == "csv" else "read.delim" + row_names_arg = f"row.names = {row_names_col}" if row_names_col is not None else "" + seed_line = f"set.seed({seed})\n" if seed is not None else "" + + # Additional arguments for SNNGraphParam based on method + method_args = "" + if method == "walktrap": + method_args = f", steps = {steps}" + # Other methods might have specific args, but for simplicity, we'll keep it general. + + r_script = f""" + library(bluster) + library(utils) # For read.csv/write.csv + library(igraph) # For community detection methods + + setwd("{output_dir.resolve()}") + + {seed_line} + + data_matrix <- tryCatch({{ + as.matrix({read_data_func}("{input_matrix_file.resolve()}", {row_names_arg})) + }}, error = function(e) {{ + stop(paste("Error reading input matrix file: ", e$message)) + }}) + + blus_param <- SNNGraphParam( + k = {k_neighbors}, + type = "{type}", + cluster.fun = "{method}" {method_args} + ) + + clusters <- tryCatch({{ + clusterRows(data_matrix, blus_param) + }}, error = function(e) {{ + stop(paste("Error during clustering: ", e$message)) + }}) + + output_df <- data.frame(cluster = clusters) + if (!is.null(rownames(data_matrix))) {{ + rownames(output_df) <- rownames(data_matrix) + }} + write.csv(output_df, "{output_clusters_filename}", row.names = TRUE) + + message("SNN graph clustering complete. Results saved to {output_clusters_filename}") + """ + + result = _run_r_script(r_script, output_dir) + + if "error" not in result: + result["output_files"].append(str(full_output_clusters_path)) + + return result + +@mcp.tool() +def pairwise_rand_index( + clusters1_file: Path, + clusters2_file: Path, + output_rand_index_file: Path = Path("pairwise_rand_index.csv"), + input_format: str = "csv", + cluster_col_name: str = "cluster", + output_dir: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Calculates the pairwise Rand index between two sets of cluster assignments using bluster::pairwiseRand. + + Args: + clusters1_file: Path to the first cluster assignment file (e.g., CSV). + Expected to have a column named 'cluster_col_name' containing integer cluster IDs. + clusters2_file: Path to the second cluster assignment file (e.g., CSV). + Expected to have a column named 'cluster_col_name' containing integer cluster IDs. + output_rand_index_file: Path to save the output Rand index results (CSV file). + This file will contain the Rand index, adjusted Rand index, etc. + input_format: Format of the input cluster files. Can be "csv" or "tsv". + cluster_col_name: The name of the column containing cluster assignments in the input files. + output_dir: Directory where output files will be written. If None, uses the current working directory. + + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + if not clusters1_file.exists(): + raise FileNotFoundError(f"First cluster file not found: {clusters1_file}") + if not clusters1_file.is_file(): + raise ValueError(f"First cluster file is not a regular file: {clusters1_file}") + if not clusters2_file.exists(): + raise FileNotFoundError(f"Second cluster file not found: {clusters2_file}") + if not clusters2_file.is_file(): + raise ValueError(f"Second cluster file is not a regular file: {clusters2_file}") + + if input_format not in ["csv", "tsv"]: + raise ValueError("input_format must be 'csv' or 'tsv'.") + if not cluster_col_name: + raise ValueError("cluster_col_name cannot be empty.") + + if output_dir is None: + output_dir = Path.cwd() + output_dir.mkdir(parents=True, exist_ok=True) + + output_filename = output_rand_index_file.name + full_output_path = output_dir / output_filename + + read_data_func = "read.csv" if input_format == "csv" else "read.delim" + + r_script = f""" + library(bluster) + library(utils) # For read.csv/write.csv + + setwd("{output_dir.resolve()}") + + clusters1_df <- tryCatch({{ + {read_data_func}("{clusters1_file.resolve()}") + }}, error = function(e) {{ + stop(paste("Error reading first cluster file: ", e$message)) + }}) + + clusters2_df <- tryCatch({{ + {read_data_func}("{clusters2_file.resolve()}") + }}, error = function(e) {{ + stop(paste("Error reading second cluster file: ", e$message)) + }}) + + if (!("{cluster_col_name}" %in% colnames(clusters1_df))) {{ + stop("Column '{cluster_col_name}' not found in first cluster file.") + }} + if (!("{cluster_col_name}" %in% colnames(clusters2_df))) {{ + stop("Column '{cluster_col_name}' not found in second cluster file.") + }} + + clusters1 <- clusters1_df[["{cluster_col_name}"]] + clusters2 <- clusters2_df[["{cluster_col_name}"]] + + # Ensure cluster assignments have the same length + if (length(clusters1) != length(clusters2)) {{ + stop("Cluster assignment vectors have different lengths.") + }} + + rand_results <- tryCatch({{ + pairwiseRand(clusters1, clusters2, adjusted=TRUE) + }}, error = function(e) {{ + stop(paste("Error calculating pairwise Rand index: ", e$message)) + }}) + + # pairwiseRand returns a numeric vector or matrix. + # For two vectors, it's a single value (adjusted Rand index by default). + # We'll create a data frame to save it. + output_df <- data.frame( + AdjustedRandIndex = rand_results + ) + write.csv(output_df, "{output_filename}", row.names = FALSE) + + message("Pairwise Rand index calculation complete. Results saved to {output_filename}") + """ + + result = _run_r_script(r_script, output_dir) + + if "error" not in result: + result["output_files"].append(str(full_output_path)) + + return result + +@mcp.tool() +def pairwise_jaccard_index( + clusters1_file: Path, + clusters2_file: Path, + output_jaccard_index_file: Path = Path("pairwise_jaccard_index.csv"), + input_format: str = "csv", + cluster_col_name: str = "cluster", + output_dir: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Calculates the pairwise Jaccard index between two sets of cluster assignments using bluster::pairwiseJaccard. + + Args: + clusters1_file: Path to the first cluster assignment file (e.g., CSV). + Expected to have a column named 'cluster_col_name' containing integer cluster IDs. + clusters2_file: Path to the second cluster assignment file (e.g., CSV). + Expected to have a column named 'cluster_col_name' containing integer cluster IDs. + output_jaccard_index_file: Path to save the output Jaccard index results (CSV file). + This file will contain the Jaccard index. + input_format: Format of the input cluster files. Can be "csv" or "tsv". + cluster_col_name: The name of the column containing cluster assignments in the input files. + output_dir: Directory where output files will be written. If None, uses the current working directory. + + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + if not clusters1_file.exists(): + raise FileNotFoundError(f"First cluster file not found: {clusters1_file}") + if not clusters1_file.is_file(): + raise ValueError(f"First cluster file is not a regular file: {clusters1_file}") + if not clusters2_file.exists(): + raise FileNotFoundError(f"Second cluster file not found: {clusters2_file}") + if not clusters2_file.is_file(): + raise ValueError(f"Second cluster file is not a regular file: {clusters2_file}") + + if input_format not in ["csv", "tsv"]: + raise ValueError("input_format must be 'csv' or 'tsv'.") + if not cluster_col_name: + raise ValueError("cluster_col_name cannot be empty.") + + if output_dir is None: + output_dir = Path.cwd() + output_dir.mkdir(parents=True, exist_ok=True) + + output_filename = output_jaccard_index_file.name + full_output_path = output_dir / output_filename + + read_data_func = "read.csv" if input_format == "csv" else "read.delim" + + r_script = f""" + library(bluster) + library(utils) # For read.csv/write.csv + + setwd("{output_dir.resolve()}") + + clusters1_df <- tryCatch({{ + {read_data_func}("{clusters1_file.resolve()}") + }}, error = function(e) {{ + stop(paste("Error reading first cluster file: ", e$message)) + }}) + + clusters2_df <- tryCatch({{ + {read_data_func}("{clusters2_file.resolve()}") + }}, error = function(e) {{ + stop(paste("Error reading second cluster file: ", e$message)) + }}) + + if (!("{cluster_col_name}" %in% colnames(clusters1_df))) {{ + stop("Column '{cluster_col_name}' not found in first cluster file.") + }} + if (!("{cluster_col_name}" %in% colnames(clusters2_df))) {{ + stop("Column '{cluster_col_name}' not found in second cluster file.") + }} + + clusters1 <- clusters1_df[["{cluster_col_name}"]] + clusters2 <- clusters2_df[["{cluster_col_name}"]] + + # Ensure cluster assignments have the same length + if (length(clusters1) != length(clusters2)) {{ + stop("Cluster assignment vectors have different lengths.") + }} + + jaccard_results <- tryCatch({{ + pairwiseJaccard(clusters1, clusters2) + }}, error = function(e) {{ + stop(paste("Error calculating pairwise Jaccard index: ", e$message)) + }}) + + output_df <- data.frame( + JaccardIndex = jaccard_results + ) + write.csv(output_df, "{output_filename}", row.names = FALSE) + + message("Pairwise Jaccard index calculation complete. Results saved to {output_filename}") + """ + + result = _run_r_script(r_script, output_dir) + + if "error" not in result: + result["output_files"].append(str(full_output_path)) + + return result + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-bluster/app/bioconductor-bluster_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-bluster/app/bioconductor-bluster_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..17c2cf585075776f3f7d0bcf5f4b8955f18bda5e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-bluster/app/bioconductor-bluster_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-bluster/app/bioconductor-bluster_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_bluster' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-bluster/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-bluster/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f740803f8f3e3ef426d32f4dc6b54cffcdc8160a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-bluster/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-bluster + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-cellhashr/app/__pycache__/bioconductor-cellhashr_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-cellhashr/app/__pycache__/bioconductor-cellhashr_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fe1d60d7a1973940339b428905ddc73190a30e40 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-cellhashr/app/__pycache__/bioconductor-cellhashr_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-clusterfoldsimilarity/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-clusterfoldsimilarity/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b36e4770cf4e0f1bc677e32d925ef1998f2e44fa --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-clusterfoldsimilarity/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-clusterfoldsimilarity: + build: . + image: mcp-bioconductor-clusterfoldsimilarity:latest + container_name: mcp-bioconductor-clusterfoldsimilarity + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-clusterfoldsimilarity + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-curatedatlasqueryr/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-curatedatlasqueryr/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..02ebac92236f7770576c155e661a1d5f225a564f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-curatedatlasqueryr/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-curatedatlasqueryr via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-curatedatlasqueryr -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-curatedatlasqueryr_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-curatedatlasqueryr_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-curatedatlasqueryr_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-curatedatlasqueryr/app/__pycache__/bioconductor-curatedatlasqueryr_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-curatedatlasqueryr/app/__pycache__/bioconductor-curatedatlasqueryr_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..78c51b11cc851f9a61e7a4f0de303e5dac59df56 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-curatedatlasqueryr/app/__pycache__/bioconductor-curatedatlasqueryr_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-curatedatlasqueryr/app/bioconductor-curatedatlasqueryr_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-curatedatlasqueryr/app/bioconductor-curatedatlasqueryr_server.py new file mode 100644 index 0000000000000000000000000000000000000000..38554dd04ca8cb9e9e6cd28a7c0f8a57f28538e4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-curatedatlasqueryr/app/bioconductor-curatedatlasqueryr_server.py @@ -0,0 +1,256 @@ +import subprocess +import os +import json +from pathlib import Path +from typing import Optional, List, Union + +def _run_r_command(r_code: str) -> dict: + """Helper to execute R code and handle errors.""" + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "stdout": result.stdout, + "stderr": result.stderr, + "success": True + } + except subprocess.CalledProcessError as e: + return { + "stdout": e.stdout, + "stderr": e.stderr, + "success": False, + "error": str(e) + } + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_curatedatlasqueryr' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def get_metadata( + output_csv: str, + force_update: bool = False +) -> dict: + """ + Retrieves the full metadata table from curatedAtlasQueryR and saves it as a CSV file. + + Args: + output_csv: Path where the metadata CSV will be saved. + force_update: If True, forces a re-download of the metadata from the remote source. + """ + output_path = Path(output_csv).resolve() + force_r = "TRUE" if force_update else "FALSE" + + r_code = f""" + suppressPackageStartupMessages(library(curatedAtlasQueryR)) + meta <- get_metadata(force = {force_r}) + write.csv(as.data.frame(meta), file = '{str(output_path)}', row.names = FALSE) + """ + + res = _run_r_command(r_code) + + return { + "command_executed": f"curatedAtlasQueryR::get_metadata(force={force_r})", + "stdout": res["stdout"], + "stderr": res["stderr"], + "output_files": [str(output_path)] if output_path.exists() else [], + "status": "success" if res["success"] else "failed" + } + +@mcp.tool() +def list_metadata_fields() -> dict: + """ + Lists all available columns/fields in the curatedAtlasQueryR metadata. + """ + r_code = """ + suppressPackageStartupMessages(library(curatedAtlasQueryR)) + meta <- get_metadata() + cat(paste(colnames(meta), collapse = "\n")) + """ + + res = _run_r_command(r_code) + + if res["success"]: + fields = res["stdout"].strip().split("\n") + return { + "command_executed": "colnames(get_metadata())", + "available_fields": fields, + "stdout": res["stdout"] + } + else: + return { + "error": "Failed to list fields", + "stderr": res["stderr"] + } + +@mcp.tool() +def search_metadata( + query: str, + output_csv: str, + fields: Optional[List[str]] = None +) -> dict: + """ + Searches the curatedAtlasQueryR metadata for specific terms across all or specified fields. + + Args: + query: The search term or regex pattern to look for. + output_csv: Path to save the filtered metadata results. + fields: Optional list of specific metadata columns to search within. + """ + output_path = Path(output_csv).resolve() + + # Handle fields list for R without backslashes in f-string + if fields: + fields_list_str = ", ".join([f"'{f}'" for f in fields]) + fields_r = f"c({fields_list_str})" + else: + fields_r = "NULL" + + r_code = f""" + suppressPackageStartupMessages(library(curatedAtlasQueryR)) + meta <- get_metadata() + search_cols <- {fields_r} + if (is.null(search_cols)) search_cols <- colnames(meta) + + # Filter rows where any of the selected columns match the query + matches <- apply(meta[, search_cols, drop = FALSE], 1, function(row) {{ + any(grepl("{query}", as.character(row), ignore.case = TRUE)) + }}) + + search_res <- meta[matches, ] + write.csv(as.data.frame(search_res), file = '{str(output_path)}', row.names = FALSE) + """ + + res = _run_r_command(r_code) + + return { + "command_executed": f"Searching metadata for '{query}' in fields {fields_r}", + "stdout": res["stdout"], + "stderr": res["stderr"], + "output_files": [str(output_path)] if output_path.exists() else [] + } + +@mcp.tool() +def query_metadata_custom( + r_filter_expression: str, + output_csv: str +) -> dict: + """ + Performs a custom R-style filter on the metadata table using dplyr syntax. + + Args: + r_filter_expression: An R logical expression string (e.g., "tissue == 'liver' & disease == 'normal'"). + output_csv: Path to save the filtered metadata. + """ + output_path = Path(output_csv).resolve() + + r_code = f""" + suppressPackageStartupMessages(library(curatedAtlasQueryR)) + suppressPackageStartupMessages(library(dplyr)) + meta <- get_metadata() + filtered_meta <- meta %>% filter({r_filter_expression}) + write.csv(as.data.frame(filtered_meta), file = '{str(output_path)}', row.names = FALSE) + """ + + res = _run_r_command(r_code) + + return { + "command_executed": f"Metadata filter: {r_filter_expression}", + "stdout": res["stdout"], + "stderr": res["stderr"], + "output_files": [str(output_path)] if output_path.exists() else [] + } + +@mcp.tool() +def get_atlas_data( + sample_ids: List[str], + output_rds: str +) -> dict: + """ + Downloads single-cell data (SingleCellExperiment) for specified sample IDs. + + Args: + sample_ids: A list of sample_id strings to download. + output_rds: Path to save the resulting SingleCellExperiment object (.rds). + """ + output_path = Path(output_rds).resolve() + + if not sample_ids: + return {"error": "No sample_ids provided."} + + ids_list_str = ", ".join([f"'{i}'" for i in sample_ids]) + ids_r = f"c({ids_list_str})" + + r_code = f""" + suppressPackageStartupMessages(library(curatedAtlasQueryR)) + suppressPackageStartupMessages(library(SingleCellExperiment)) + + meta <- get_metadata() + selected_meta <- meta[meta$sample_id %in% {ids_r}, ] + + if(nrow(selected_meta) == 0) stop("No matching sample IDs found in metadata.") + + sce <- get_data(selected_meta) + saveRDS(sce, file = '{str(output_path)}') + """ + + res = _run_r_command(r_code) + + return { + "command_executed": f"curatedAtlasQueryR::get_data() for {len(sample_ids)} samples", + "stdout": res["stdout"], + "stderr": res["stderr"], + "output_files": [str(output_path)] if output_path.exists() else [] + } + +@mcp.tool() +def get_gene_expression( + sample_ids: List[str], + genes: List[str], + output_rds: str +) -> dict: + """ + Retrieves gene expression data for specific genes across specified samples. + + Args: + sample_ids: A list of sample_id strings. + genes: A list of gene symbols or IDs to retrieve. + output_rds: Path to save the resulting SummarizedExperiment object (.rds). + """ + output_path = Path(output_rds).resolve() + + if not sample_ids or not genes: + return {"error": "Both sample_ids and genes must be provided."} + + ids_list_str = ", ".join([f"'{i}'" for i in sample_ids]) + genes_list_str = ", ".join([f"'{g}'" for g in genes]) + + r_code = f""" + suppressPackageStartupMessages(library(curatedAtlasQueryR)) + suppressPackageStartupMessages(library(SummarizedExperiment)) + + meta <- get_metadata() + selected_meta <- meta[meta$sample_id %in% c({ids_list_str}), ] + + if(nrow(selected_meta) == 0) stop("No matching sample IDs found in metadata.") + + se <- get_gene_expression(selected_meta, genes = c({genes_list_str})) + saveRDS(se, file = '{str(output_path)}') + """ + + res = _run_r_command(r_code) + + return { + "command_executed": f"curatedAtlasQueryR::get_gene_expression() for {len(genes)} genes", + "stdout": res["stdout"], + "stderr": res["stderr"], + "output_files": [str(output_path)] if output_path.exists() else [] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-curatedatlasqueryr/app/bioconductor-curatedatlasqueryr_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-curatedatlasqueryr/app/bioconductor-curatedatlasqueryr_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..11cb48dd3d4dd548a72cc2f55597b9ae6a634f2f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-curatedatlasqueryr/app/bioconductor-curatedatlasqueryr_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-curatedatlasqueryr/app/bioconductor-curatedatlasqueryr_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_curatedatlasqueryr' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-curatedatlasqueryr/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-curatedatlasqueryr/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-curatedatlasqueryr/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-curatedatlasqueryr/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-curatedatlasqueryr/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..61ced17959568e3d32fc631fcbb885443248c4d9 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-curatedatlasqueryr/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-curatedatlasqueryr: + build: . + image: mcp-bioconductor-curatedatlasqueryr:latest + container_name: mcp-bioconductor-curatedatlasqueryr + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-curatedatlasqueryr + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-curatedatlasqueryr/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-curatedatlasqueryr/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f4ebc5295ee989236a3cdfaf8847d8072211ef33 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-curatedatlasqueryr/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-curatedatlasqueryr + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-curatedatlasqueryr/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-curatedatlasqueryr/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-curatedatlasqueryr/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ebseq/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ebseq/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ebseq/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-edger/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-edger/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..afa6508a4a79e041e41e6dba488188175d2bf18b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-edger/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-edger via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-edger -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-edger_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-edger_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-edger_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-edger/app/__pycache__/bioconductor-edger_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-edger/app/__pycache__/bioconductor-edger_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6142501dc67aab22a2801321313f6142a560dbae Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-edger/app/__pycache__/bioconductor-edger_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-edger/app/bioconductor-edger_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-edger/app/bioconductor-edger_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a54a68420dd5092a56d6fb0567bcfad5c714dfad --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-edger/app/bioconductor-edger_server.py @@ -0,0 +1,291 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Literal + +# MCP decorator stub. In a real environment, this would be: +# from mcp import mcp +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def run_edger_glm( + counts_file: Path, + metadata_file: Path, + design_formula: str, + contrast: List[str], + output_prefix: str, + min_cpm: float = 1.0, + min_samples_fraction: float = 0.5, + norm_method: Literal["TMM", "TMMwsp", "RLE", "upperquartile", "none"] = "TMM", + estimate_disp_robust: bool = True, + glm_fit_robust: bool = True, + test_method: Literal["QLFTest", "LRT"] = "QLFTest", +) -> dict: + """ + Performs differential expression analysis using the edgeR GLM workflow. + + This tool is suitable for complex experimental designs (e.g., multiple factors, + batch effects, interactions) that can be specified with a design formula. + + Args: + counts_file: Path to the input counts matrix file (CSV format). + Rows should be genes and columns should be samples. + metadata_file: Path to the sample metadata file (CSV format). + Rows should be samples (matching counts_file columns) and + columns should be experimental factors. + design_formula: The design formula for the model matrix (e.g., "~ batch + condition"). + Must start with '~'. + contrast: A list of three strings defining the contrast to be tested: + [factor, level1, level2]. This tests level1 vs level2 for the given factor. + output_prefix: The prefix for the output results file. + min_cpm: The minimum counts-per-million (CPM) a gene must have to be considered + for filtering. Defaults to 1.0. + min_samples_fraction: The fraction of samples in the smallest group that must + meet the min_cpm threshold for a gene to be kept. Defaults to 0.5. + norm_method: Normalization method to be used. Defaults to "TMM". + estimate_disp_robust: Use robust estimation for dispersion. Defaults to True. + glm_fit_robust: Use robust estimation for GLM fitting. Defaults to True. + test_method: The statistical test to perform (Quasi-likelihood F-test or + Likelihood Ratio Test). Defaults to "QLFTest". + + Returns: + A dictionary containing the execution command, stdout, stderr, and output file paths. + """ + # --- Input Validation --- + if not counts_file.is_file(): + raise FileNotFoundError(f"Counts file not found: {counts_file}") + if not metadata_file.is_file(): + raise FileNotFoundError(f"Metadata file not found: {metadata_file}") + if not design_formula.startswith("~"): + raise ValueError("design_formula must start with '~'") + if len(contrast) != 3: + raise ValueError("contrast must be a list of three strings: [factor, level1, level2]") + if not (0 < min_samples_fraction <= 1): + raise ValueError("min_samples_fraction must be between 0 and 1") + + output_file = Path(f"{output_prefix}_edger_glm_results.csv") + + # --- R Script Generation --- + r_script_content = f""" + # Load libraries + library(edgeR) + options(warn=-1) + + # --- Parameters --- + counts_file <- "{counts_file.resolve()}" + metadata_file <- "{metadata_file.resolve()}" + output_file <- "{output_file.resolve()}" + design_formula_str <- "{design_formula}" + contrast_factor <- "{contrast[0]}" + contrast_level1 <- "{contrast[1]}" + contrast_level2 <- "{contrast[2]}" + min_cpm <- {min_cpm} + min_samples_fraction <- {min_samples_fraction} + norm_method <- "{norm_method}" + estimate_disp_robust_r <- {"TRUE" if estimate_disp_robust else "FALSE"} + glm_fit_robust_r <- {"TRUE" if glm_fit_robust else "FALSE"} + test_method <- "{test_method}" + + # --- Data Loading --- + counts <- read.csv(counts_file, row.names=1, check.names=FALSE) + metadata <- read.csv(metadata_file, row.names=1, check.names=FALSE) + + if (!all(colnames(counts) %in% rownames(metadata))) {{ + stop("Not all column names in counts_file are present as row names in metadata_file.") + }} + metadata <- metadata[colnames(counts), , drop=FALSE] + + # --- edgeR Workflow --- + dge <- DGEList(counts=counts, samples=metadata) + + # Filtering + design_for_filter <- model.matrix(as.formula(design_formula_str), data=dge$samples) + min_samples <- floor(min(colSums(design_for_filter)) * min_samples_fraction) + if (min_samples < 1) {{ min_samples <- 1 }} + cat(paste("Filtering: Keeping genes with >", min_cpm, "CPM in at least", min_samples, "samples.\\n")) + keep <- rowSums(cpm(dge) > min_cpm) >= min_samples + dge <- dge[keep, , keep.lib.sizes=FALSE] + cat(paste(sum(keep), "genes remaining after filtering.\\n")) + + # Normalization + dge <- calcNormFactors(dge, method=norm_method) + + # Design matrix + design <- model.matrix(as.formula(design_formula_str), data=dge$samples) + + # Check if contrast levels are valid + c1 <- paste0(contrast_factor, contrast_level1) + c2 <- paste0(contrast_factor, contrast_level2) + if (!c1 %in% colnames(design)) stop(paste("Contrast level", c1, "not found in design matrix columns:", paste(colnames(design), collapse=", "))) + if (!c2 %in% colnames(design)) stop(paste("Contrast level", c2, "not found in design matrix columns:", paste(colnames(design), collapse=", "))) + + # Estimate dispersion + dge <- estimateDisp(dge, design, robust=estimate_disp_robust_r) + + # Model fitting and testing + contrast_str <- paste0(c1, "-", c2) + contrast_arg <- makeContrasts(contrasts=contrast_str, levels=design) + + if (test_method == "QLFTest") {{ + fit <- glmQLFit(dge, design, robust=glm_fit_robust_r) + test <- glmQLFTest(fit, contrast=contrast_arg) + }} else if (test_method == "LRT") {{ + fit <- glmFit(dge, design, robust=glm_fit_robust_r) + test <- glmLRT(fit, contrast=contrast_arg) + }} else {{ + stop("Unsupported test method.") + }} + + results <- topTags(test, n=Inf)$table + write.csv(results, file=output_file, row.names=TRUE) + cat(paste("edgeR GLM analysis completed. Results saved to", output_file, "\\n")) + """ + + # --- Subprocess Execution --- + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R", encoding='utf-8') as tmp_r_script: + tmp_r_script.write(r_script_content) + script_path = tmp_r_script.name + + command = ["Rscript", script_path] + command_executed = " ".join(command) + + try: + result = subprocess.run(command, capture_output=True, text=True, check=True) + stdout = result.stdout + stderr = result.stderr + except FileNotFoundError: + return {"command_executed": command_executed, "stdout": "", "stderr": "Error: Rscript not found. Please ensure R is installed and in your system's PATH.", "output_files": []} + except subprocess.CalledProcessError as e: + return {"command_executed": command_executed, "stdout": e.stdout, "stderr": e.stderr, "output_files": []} + finally: + Path(script_path).unlink() + + return {"command_executed": command_executed, "stdout": stdout, "stderr": stderr, "output_files": [str(output_file)] if output_file.exists() else []} + + +@mcp.tool +def run_edger_exact_test( + counts_file: Path, + metadata_file: Path, + group_column: str, + group1: str, + group2: str, + output_prefix: str, + min_cpm: float = 1.0, + min_samples_fraction: float = 0.7, + norm_method: Literal["TMM", "TMMwsp", "RLE", "upperquartile", "none"] = "TMM", + dispersion_method: Literal["common", "trended", "tagwise"] = "tagwise", +) -> dict: + """ + Performs DE analysis for a two-group comparison using edgeR's exact test. + + This tool is optimized for simple experiments comparing two groups (e.g., treatment vs. control). + + Args: + counts_file: Path to the input counts matrix file (CSV format). + metadata_file: Path to the sample metadata file (CSV format). + group_column: The name of the column in metadata_file that contains group information. + group1: The name of the first group (numerator in logFC, e.g., 'treatment'). + group2: The name of the second group (denominator in logFC, e.g., 'control'). + output_prefix: The prefix for the output results file. + min_cpm: The minimum counts-per-million (CPM) a gene must have. Defaults to 1.0. + min_samples_fraction: The fraction of samples in the smallest group that must + meet the min_cpm threshold for a gene to be kept. Defaults to 0.7. + norm_method: Normalization method to be used. Defaults to "TMM". + dispersion_method: The method for dispersion estimation. 'tagwise' is recommended. + Defaults to "tagwise". + + Returns: + A dictionary containing the execution command, stdout, stderr, and output file paths. + """ + # --- Input Validation --- + if not counts_file.is_file(): + raise FileNotFoundError(f"Counts file not found: {counts_file}") + if not metadata_file.is_file(): + raise FileNotFoundError(f"Metadata file not found: {metadata_file}") + if not (0 < min_samples_fraction <= 1): + raise ValueError("min_samples_fraction must be between 0 and 1") + + output_file = Path(f"{output_prefix}_edger_exact_test_results.csv") + + # --- R Script Generation --- + r_script_content = f""" + library(edgeR) + options(warn=-1) + + # --- Parameters --- + counts_file <- "{counts_file.resolve()}" + metadata_file <- "{metadata_file.resolve()}" + output_file <- "{output_file.resolve()}" + group_column <- "{group_column}" + group1 <- "{group1}" + group2 <- "{group2}" + min_cpm <- {min_cpm} + min_samples_fraction <- {min_samples_fraction} + norm_method <- "{norm_method}" + dispersion_method <- "{dispersion_method}" + + # --- Data Loading --- + counts <- read.csv(counts_file, row.names=1, check.names=FALSE) + metadata <- read.csv(metadata_file, row.names=1, check.names=FALSE) + + metadata_subset <- metadata[metadata[[group_column]] %in% c(group1, group2), ] + if (nrow(metadata_subset) == 0) stop("No samples found for the specified groups.") + counts_subset <- counts[, rownames(metadata_subset)] + + # --- edgeR Workflow --- + group <- factor(metadata_subset[[group_column]]) + dge <- DGEList(counts=counts_subset, group=group) + + # Filtering + min_samples <- floor(min(table(group)) * min_samples_fraction) + if (min_samples < 1) {{ min_samples <- 1 }} + cat(paste("Filtering: Keeping genes with >", min_cpm, "CPM in at least", min_samples, "samples.\\n")) + keep <- rowSums(cpm(dge) > min_cpm) >= min_samples + dge <- dge[keep, , keep.lib.sizes=FALSE] + cat(paste(sum(keep), "genes remaining after filtering.\\n")) + + # Normalization + dge <- calcNormFactors(dge, method=norm_method) + + # Estimate dispersion + if (dispersion_method == "common") {{ + dge <- estimateCommonDisp(dge) + }} else if (dispersion_method == "trended") {{ + dge <- estimateCommonDisp(dge) + dge <- estimateTrendedDisp(dge) + }} else {{ + dge <- estimateDisp(dge) + }} + + # Perform exact test (group1 vs group2) + et <- exactTest(dge, pair=c(group2, group1)) + + results <- topTags(et, n=Inf)$table + write.csv(results, file=output_file, row.names=TRUE) + cat(paste("edgeR exact test completed. Results saved to", output_file, "\\n")) + """ + + # --- Subprocess Execution --- + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R", encoding='utf-8') as tmp_r_script: + tmp_r_script.write(r_script_content) + script_path = tmp_r_script.name + + command = ["Rscript", script_path] + command_executed = " ".join(command) + + try: + result = subprocess.run(command, capture_output=True, text=True, check=True) + stdout = result.stdout + stderr = result.stderr + except FileNotFoundError: + return {"command_executed": command_executed, "stdout": "", "stderr": "Error: Rscript not found. Please ensure R is installed and in your system's PATH.", "output_files": []} + except subprocess.CalledProcessError as e: + return {"command_executed": command_executed, "stdout": e.stdout, "stderr": e.stderr, "output_files": []} + finally: + Path(script_path).unlink() + + return {"command_executed": command_executed, "stdout": stdout, "stderr": stderr, "output_files": [str(output_file)] if output_file.exists() else []} \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-edger/app/bioconductor-edger_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-edger/app/bioconductor-edger_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8abe51678d0ce5daf6fea73656b83613c09ebd5c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-edger/app/bioconductor-edger_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-edger/app/bioconductor-edger_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_edger' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-edger/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-edger/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-edger/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-edger/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-edger/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..3c2d48e4be4ae96adc8e3d2a236e22da2a3d7e41 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-edger/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-edger: + build: . + image: mcp-bioconductor-edger:latest + container_name: mcp-bioconductor-edger + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-edger + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-edger/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-edger/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6dc7924789c820fb39041415eb915f5b2f3558e6 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-edger/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-edger + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-edger/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-edger/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-edger/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicalignments/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicalignments/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1df8854d574f92a14aab64756ce0ad45c64c831b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicalignments/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-genomicalignments via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-genomicalignments -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-genomicalignments_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-genomicalignments_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-genomicalignments_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicalignments/app/__pycache__/bioconductor-genomicalignments_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicalignments/app/__pycache__/bioconductor-genomicalignments_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c5eb05a88a3c2e3990778d20fd669976b4786058 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicalignments/app/__pycache__/bioconductor-genomicalignments_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicalignments/app/bioconductor-genomicalignments_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicalignments/app/bioconductor-genomicalignments_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e811700f205898119c69efbfbeb9177c46e9baf4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicalignments/app/bioconductor-genomicalignments_server.py @@ -0,0 +1,247 @@ +import subprocess +import tempfile +import logging +from pathlib import Path +from typing import List, Dict, Any + +# Configure logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# R script template to be executed. This script is a self-contained wrapper +# for the summarizeOverlaps function. +R_SCRIPT_TEMPLATE = """ +# Load required libraries quietly +suppressPackageStartupMessages(library(optparse)) +suppressPackageStartupMessages(library(GenomicAlignments)) +suppressPackageStartupMessages(library(Rsamtools)) +suppressPackageStartupMessages(library(rtracklayer)) +suppressPackageStartupMessages(library(GenomicFeatures)) + +# Define command-line options +option_list <- list( + make_option("--features", type="character", help="Path to features file (GFF/GTF/BED)"), + make_option("--reads", type="character", help="Path to alignment file (BAM)"), + make_option("--output", type="character", help="Path to output count matrix file (TSV)"), + make_option("--mode", type="character", default="Union", help="Counting mode [Union, IntersectionStrict, IntersectionNotEmpty]"), + make_option("--single_end", type="logical", default=FALSE, help="Set TRUE for single-end reads"), + make_option("--ignore_strand", type="logical", default=FALSE, help="Set TRUE to ignore strand information"), + make_option("--fragments", type="logical", default=FALSE, help="Count fragments (pairs) instead of reads for paired-end data"), + make_option("--inter_feature", type="logical", default=TRUE, help="If TRUE, reads overlapping multiple features are dropped"), + make_option("--mapq_filter", type="integer", default=0, help="Minimum mapping quality (MAPQ)"), + make_option("--filter_secondary", type="logical", default=TRUE, help="If TRUE, filter out secondary alignments"), + make_option("--filter_unmapped", type="logical", default=TRUE, help="If TRUE, filter out unmapped reads"), + make_option("--filter_improper", type="logical", default=TRUE, help="If TRUE, filter out reads not in a proper pair (for PE data)") +) + +# Parse options +opt_parser <- OptionParser(option_list=option_list) +opt <- parse_args(opt_parser) + +# Check for required arguments +if (is.null(opt$features) || is.null(opt$reads) || is.null(opt$output)) { + print_help(opt_parser) + stop("Input features, reads, and output files must be supplied.", call.=FALSE) +} + +# Read features from GFF/GTF/BED +tryCatch({ + cat("INFO: Reading features from:", opt$features, "\\n") + features <- rtracklayer::import(opt$features) +}, error = function(e) { + stop(paste("Failed to read features file:", opt$features, "\\nError:", e$message)) +}) + +# Create BamFile object to stream the BAM file +bam_file <- BamFile(opt$reads, asMates=!opt$single_end) + +# Construct ScanBamParam for filtering alignments +# Note: Rsamtools flags specify what to KEEP. +# So, filter_secondary=TRUE (Python) means isSecondaryAlignment=FALSE (R). +flag <- scanBamFlag( + isNotPrimaryAlignment = FALSE, # Always keep primary alignments + isSecondaryAlignment = !opt$filter_secondary, + isUnmappedQuery = !opt$filter_unmapped, + isProperPair = if (opt$single_end) NA else !opt$filter_improper, + isDuplicate = FALSE # We are not filtering duplicates by default in this wrapper +) +param <- ScanBamParam(mapqFilter = opt$mapq_filter, flag = flag) + +# Run the core function: summarizeOverlaps +cat("INFO: Running summarizeOverlaps with mode '", opt$mode, "'...\\n", sep="") +se <- summarizeOverlaps( + features = features, + reads = bam_file, + mode = opt$mode, + singleEnd = opt$single_end, + ignore.strand = opt$ignore_strand, + fragments = opt$fragments, + inter.feature = opt$inter_feature, + param = param +) + +# Extract and write the count matrix +cat("INFO: Writing counts to:", opt$output, "\\n") +counts <- assay(se) +counts_df <- as.data.frame(counts) + +# Attempt to get meaningful feature IDs from the GRanges object +feature_ids <- names(features) +if (is.null(feature_ids)) { + # Fallback to metadata columns if names are not set + if ("ID" %in% colnames(mcols(features))) { + feature_ids <- mcols(features)$ID + } else if ("gene_id" %in% colnames(mcols(features))) { + feature_ids <- mcols(features)$gene_id + } else { + feature_ids <- paste0("feature_", seq_len(nrow(counts_df))) + } +} +# Ensure feature IDs are unique to prevent row name conflicts +feature_ids <- make.unique(as.character(feature_ids)) + +# Combine feature IDs with the count data +output_df <- cbind(feature_id = feature_ids, counts_df) + +# Write to a tab-separated file +write.table( + output_df, + file = opt$output, + sep = "\\t", + quote = FALSE, + row.names = FALSE, + col.names = TRUE +) + +cat("INFO: Process completed successfully.\\n") +""" + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_genomicalignments' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def summarize_overlaps( + features_file: Path, + reads_file: Path, + output_file: Path, + mode: str = "Union", + single_end: bool = False, + ignore_strand: bool = False, + fragments: bool = False, + inter_feature: bool = True, + mapq_filter: int = 0, + filter_secondary_alignments: bool = True, + filter_unmapped_reads: bool = True, + filter_improper_pairs: bool = True, +) -> Dict[str, Any]: + """ + Generates a feature count matrix from alignment and annotation files. + + This tool is a wrapper for the `summarizeOverlaps` function from the + R/Bioconductor package 'GenomicAlignments'. It quantifies reads from a + BAM file that overlap with genomic features defined in a GFF, GTF, or BED file. + + **Prerequisites**: The execution environment must have R installed, along with + the Bioconductor packages: GenomicAlignments, Rsamtools, rtracklayer, + GenomicFeatures, and the CRAN package optparse. + + Args: + features_file: Path to the input genomic features file (e.g., GFF, GTF, BED). + reads_file: Path to the input alignments file (BAM format). + output_file: Path for the output count matrix (will be saved as a TSV file). + mode: The counting mode. Must be one of 'Union', 'IntersectionStrict', + or 'IntersectionNotEmpty'. Defaults to 'Union'. + single_end: Set to True if the sequencing data is single-end. Defaults to False (paired-end). + ignore_strand: Set to True to perform non-strand-specific counting. Defaults to False. + fragments: For paired-end data, count fragments (read pairs) instead of individual + reads. Defaults to False. + inter_feature: If True, reads that overlap multiple features are not counted. + If False, they are counted for each feature they overlap. Defaults to True. + mapq_filter: Minimum mapping quality (MAPQ) score for a read to be included. + Defaults to 0 (no filtering). + filter_secondary_alignments: If True, secondary alignments are excluded from counting. + Defaults to True. + filter_unmapped_reads: If True, unmapped reads are excluded. Defaults to True. + filter_improper_pairs: For paired-end data, if True, reads that are not part of a + proper pair are excluded. Defaults to True. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list + of output files. + """ + # --- Input Validation --- + if not features_file.exists(): + raise FileNotFoundError(f"Features file not found: {features_file}") + if not reads_file.exists(): + raise FileNotFoundError(f"Reads file not found: {reads_file}") + if not output_file.parent.exists(): + raise FileNotFoundError(f"Output directory does not exist: {output_file.parent}") + + valid_modes = ["Union", "IntersectionStrict", "IntersectionNotEmpty"] + if mode not in valid_modes: + raise ValueError(f"Invalid mode '{mode}'. Must be one of {valid_modes}.") + + if mapq_filter < 0: + raise ValueError("mapq_filter must be a non-negative integer.") + + if fragments and single_end: + logger.warning("'fragments' is set to True but 'single_end' is also True. 'fragments' is only applicable to paired-end data.") + + # --- R Script and Command Preparation --- + r_script_path = None + try: + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R", encoding='utf-8') as fp: + fp.write(R_SCRIPT_TEMPLATE) + r_script_path = fp.name + + cmd = [ + "Rscript", r_script_path, + "--features", str(features_file), + "--reads", str(reads_file), + "--output", str(output_file), + "--mode", mode, + "--mapq_filter", str(mapq_filter), + "--single_end", str(single_end).upper(), + "--ignore_strand", str(ignore_strand).upper(), + "--fragments", str(fragments).upper(), + "--inter_feature", str(inter_feature).upper(), + "--filter_secondary", str(filter_secondary_alignments).upper(), + "--filter_unmapped", str(filter_unmapped_reads).upper(), + "--filter_improper", str(filter_improper_pairs).upper(), + ] + + command_executed = " ".join(cmd) + logger.info(f"Executing command: {command_executed}") + + # --- Subprocess Execution --- + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_file)] + } + + except FileNotFoundError: + logger.error("Rscript not found. Please ensure R is installed and in your system's PATH.") + raise + except subprocess.CalledProcessError as e: + logger.error(f"R script execution failed with exit code {e.returncode}.") + logger.error(f"Stderr:\n{e.stderr}") + logger.error(f"Stdout:\n{e.stdout}") + raise + finally: + # --- Cleanup --- + if r_script_path and Path(r_script_path).exists(): + Path(r_script_path).unlink() + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicalignments/app/bioconductor-genomicalignments_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicalignments/app/bioconductor-genomicalignments_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b7e7d5288f03802f7bc90706884dc8aa4066fac1 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicalignments/app/bioconductor-genomicalignments_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicalignments/app/bioconductor-genomicalignments_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_genomicalignments' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicalignments/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicalignments/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicalignments/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicalignments/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicalignments/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..abb740c24ddfef04f23dc41a049518a7b7c7e21f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicalignments/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-genomicalignments: + build: . + image: mcp-bioconductor-genomicalignments:latest + container_name: mcp-bioconductor-genomicalignments + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-genomicalignments + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicalignments/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicalignments/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0d43bf092a97ea39850977042b15a1c8a2d642c7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicalignments/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-genomicalignments + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicalignments/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicalignments/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-genomicalignments/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ggsc/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ggsc/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8e4385ba0e7fd397a459e7260eff11f045abdb1a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ggsc/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-ggsc via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-ggsc -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-ggsc_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-ggsc_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-ggsc_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ggsc/app/__pycache__/bioconductor-ggsc_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ggsc/app/__pycache__/bioconductor-ggsc_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9abcd0998aca8c7c53d5d0d527a97a7895a022c5 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ggsc/app/__pycache__/bioconductor-ggsc_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ggsc/app/bioconductor-ggsc_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ggsc/app/bioconductor-ggsc_server.py new file mode 100644 index 0000000000000000000000000000000000000000..be9b1a9963625fc0cc3c808a70155fc8972db3e9 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ggsc/app/bioconductor-ggsc_server.py @@ -0,0 +1,368 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, List + +# This script assumes the presence of a companion R script (e.g., 'run_ggsc.R') +# that acts as a command-line interface for the 'ggsc' R package. +# The R environment must have 'ggsc', 'SingleCellExperiment', 'ggplot2', +# and an argument parser like 'optparse' installed. +R_SCRIPT_EXECUTABLE = "run_ggsc.R" + +# Per instructions, the @mcp.tool decorator is used. +# A dummy decorator is defined here for syntax validity in a standalone context. +# In a true MCP environment, this would be provided by the MCP framework. +def tool(func): + """Dummy decorator to match the required syntax.""" + return func + +class MCP: + """Dummy class to hold the tool decorator.""" + tool = staticmethod(tool) + +mcp = MCP() + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_ggsc' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def plot_reduced_dim( + input_rds: Path, + output_plot: Path, + dim_red: str, + color_by: str, + facet_by: Optional[str] = None, + plot_title: Optional[str] = None, + img_width: int = 7, + img_height: int = 7 +) -> dict: + """ + Generates a reduced dimension plot (e.g., UMAP, t-SNE) from a SingleCellExperiment object. + + This tool wraps the `plot_reduced_dim_sce` function from the R/Bioconductor package `ggsc`. + The input must be a .rds file containing a SingleCellExperiment object. + + Args: + input_rds: Path to the input RDS file containing a SingleCellExperiment object. + output_plot: Path to save the output plot image (e.g., plot.png). + dim_red: Name of the dimension reduction to use (e.g., "UMAP", "TSNE"). + color_by: Variable in colData to color the points by (e.g., "label", "cluster"). + facet_by: Optional variable in colData to facet the plot by. + plot_title: Optional title for the plot. + img_width: Width of the output image in inches. + img_height: Height of the output image in inches. + + Returns: + A dictionary containing the execution details and output file path. + """ + # --- Input Validation --- + if not input_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {input_rds}") + if img_width <= 0 or img_height <= 0: + raise ValueError("Image width and height must be positive integers.") + + # Ensure output directory exists + output_plot.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd = [ + "Rscript", + R_SCRIPT_EXECUTABLE, + "reduced_dim", + "--input_rds", str(input_rds), + "--output_plot", str(output_plot), + "--dim_red", dim_red, + "--color_by", color_by, + "--img_width", str(img_width), + "--img_height", str(img_height) + ] + + if facet_by: + cmd.extend(["--facet_by", facet_by]) + if plot_title: + cmd.extend(["--plot_title", plot_title]) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + except FileNotFoundError: + raise RuntimeError("Rscript or the wrapper script not found. Please ensure R and the tool's R script are in the system's PATH.") + except subprocess.CalledProcessError as e: + error_message = f"ggsc R script failed for reduced_dim plot.\nSTDOUT: {e.stdout}\nSTDERR: {e.stderr}" + logging.error(error_message) + raise RuntimeError(error_message) from e + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_plot)] + } + + +@mcp.tool() +def plot_gene_expression( + input_rds: Path, + output_plot: Path, + gene: str, + dim_red: str, + assay: str = "logcounts", + plot_title: Optional[str] = None, + img_width: int = 7, + img_height: int = 7 +) -> dict: + """ + Plots the expression of a single gene on a reduced dimension plot. + + This tool wraps the `plot_gene_sce` function from the R/Bioconductor package `ggsc`. + The input must be a .rds file containing a SingleCellExperiment object. + + Args: + input_rds: Path to the input RDS file containing a SingleCellExperiment object. + output_plot: Path to save the output plot image. + gene: The name of the gene to plot. + dim_red: Name of the dimension reduction to use (e.g., "UMAP"). + assay: The assay to use for expression values (default: "logcounts"). + plot_title: Optional title for the plot. + img_width: Width of the output image in inches. + img_height: Height of the output image in inches. + + Returns: + A dictionary containing the execution details and output file path. + """ + # --- Input Validation --- + if not input_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {input_rds}") + if not gene: + raise ValueError("A gene name must be provided.") + if img_width <= 0 or img_height <= 0: + raise ValueError("Image width and height must be positive integers.") + + output_plot.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd = [ + "Rscript", + R_SCRIPT_EXECUTABLE, + "gene_plot", + "--input_rds", str(input_rds), + "--output_plot", str(output_plot), + "--gene", gene, + "--dim_red", dim_red, + "--assay", assay, + "--img_width", str(img_width), + "--img_height", str(img_height) + ] + + if plot_title: + cmd.extend(["--plot_title", plot_title]) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + except FileNotFoundError: + raise RuntimeError("Rscript or the wrapper script not found. Please ensure R and the tool's R script are in the system's PATH.") + except subprocess.CalledProcessError as e: + error_message = f"ggsc R script failed for gene expression plot.\nSTDOUT: {e.stdout}\nSTDERR: {e.stderr}" + logging.error(error_message) + raise RuntimeError(error_message) from e + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_plot)] + } + + +@mcp.tool() +def plot_expression_heatmap( + input_rds: Path, + output_plot: Path, + genes: List[str], + annotation_col: str, + assay: str = "logcounts", + plot_title: Optional[str] = None, + img_width: int = 7, + img_height: int = 10 +) -> dict: + """ + Generates a heatmap of gene expression for a set of genes. + + This tool wraps the `plot_heatmap_sce` function from the R/Bioconductor package `ggsc`. + The input must be a .rds file containing a SingleCellExperiment object. + + Args: + input_rds: Path to the input RDS file containing a SingleCellExperiment object. + output_plot: Path to save the output plot image. + genes: A list of gene names to include in the heatmap. + annotation_col: Column in colData to use for cell annotation. + assay: The assay to use for expression values (default: "logcounts"). + plot_title: Optional title for the plot. + img_width: Width of the output image in inches. + img_height: Height of the output image in inches. + + Returns: + A dictionary containing the execution details and output file path. + """ + # --- Input Validation --- + if not input_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {input_rds}") + if not genes: + raise ValueError("At least one gene must be provided in the list.") + if img_width <= 0 or img_height <= 0: + raise ValueError("Image width and height must be positive integers.") + + output_plot.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + genes_str = ",".join(genes) + cmd = [ + "Rscript", + R_SCRIPT_EXECUTABLE, + "heatmap", + "--input_rds", str(input_rds), + "--output_plot", str(output_plot), + "--genes", genes_str, + "--annotation_col", annotation_col, + "--assay", assay, + "--img_width", str(img_width), + "--img_height", str(img_height) + ] + + if plot_title: + cmd.extend(["--plot_title", plot_title]) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + except FileNotFoundError: + raise RuntimeError("Rscript or the wrapper script not found. Please ensure R and the tool's R script are in the system's PATH.") + except subprocess.CalledProcessError as e: + error_message = f"ggsc R script failed for expression heatmap.\nSTDOUT: {e.stdout}\nSTDERR: {e.stderr}" + logging.error(error_message) + raise RuntimeError(error_message) from e + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_plot)] + } + + +@mcp.tool() +def plot_expression_violin( + input_rds: Path, + output_plot: Path, + gene: str, + group_by: str, + assay: str = "logcounts", + plot_title: Optional[str] = None, + img_width: int = 7, + img_height: int = 5 +) -> dict: + """ + Generates a violin plot of gene expression across different groups. + + This tool wraps the `plot_violin_sce` function from the R/Bioconductor package `ggsc`. + The input must be a .rds file containing a SingleCellExperiment object. + + Args: + input_rds: Path to the input RDS file containing a SingleCellExperiment object. + output_plot: Path to save the output plot image. + gene: The name of the gene to plot. + group_by: Variable in colData to group the violins by (e.g., "cluster"). + assay: The assay to use for expression values (default: "logcounts"). + plot_title: Optional title for the plot. + img_width: Width of the output image in inches. + img_height: Height of the output image in inches. + + Returns: + A dictionary containing the execution details and output file path. + """ + # --- Input Validation --- + if not input_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {input_rds}") + if not gene: + raise ValueError("A gene name must be provided.") + if img_width <= 0 or img_height <= 0: + raise ValueError("Image width and height must be positive integers.") + + output_plot.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd = [ + "Rscript", + R_SCRIPT_EXECUTABLE, + "violin", + "--input_rds", str(input_rds), + "--output_plot", str(output_plot), + "--gene", gene, + "--group_by", group_by, + "--assay", assay, + "--img_width", str(img_width), + "--img_height", str(img_height) + ] + + if plot_title: + cmd.extend(["--plot_title", plot_title]) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + except FileNotFoundError: + raise RuntimeError("Rscript or the wrapper script not found. Please ensure R and the tool's R script are in the system's PATH.") + except subprocess.CalledProcessError as e: + error_message = f"ggsc R script failed for expression violin plot.\nSTDOUT: {e.stdout}\nSTDERR: {e.stderr}" + logging.error(error_message) + raise RuntimeError(error_message) from e + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_plot)] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ggsc/app/bioconductor-ggsc_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ggsc/app/bioconductor-ggsc_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6c7540ba933f6b2bb52b9fd62d2c66bdddb619a0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ggsc/app/bioconductor-ggsc_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ggsc/app/bioconductor-ggsc_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_ggsc' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ggsc/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ggsc/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..66d94a739f2052f5fb7c429bf4b4e1aec1181186 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ggsc/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-ggsc: + build: . + image: mcp-bioconductor-ggsc:latest + container_name: mcp-bioconductor-ggsc + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-ggsc + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ggsc/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ggsc/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..179d5ec77128b05773abab6ecc408a5b49d85d51 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ggsc/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-ggsc + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ggsc/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ggsc/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-ggsc/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-interactivedisplaybase/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-interactivedisplaybase/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6f4cd2a5c71838a423aa572705e3c4403719003d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-interactivedisplaybase/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-interactivedisplaybase via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-interactivedisplaybase -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-interactivedisplaybase_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-interactivedisplaybase_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-interactivedisplaybase_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-interactivedisplaybase/app/__pycache__/bioconductor-interactivedisplaybase_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-interactivedisplaybase/app/__pycache__/bioconductor-interactivedisplaybase_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d6e955a902f6f69a88f1a6e5efd495d763eaa92c Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-interactivedisplaybase/app/__pycache__/bioconductor-interactivedisplaybase_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-interactivedisplaybase/app/bioconductor-interactivedisplaybase_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-interactivedisplaybase/app/bioconductor-interactivedisplaybase_server.py new file mode 100644 index 0000000000000000000000000000000000000000..946a310cb225b723168c968dd57606144ddd720b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-interactivedisplaybase/app/bioconductor-interactivedisplaybase_server.py @@ -0,0 +1,44 @@ +import subprocess +from pathlib import Path +from typing import Optional + +# MCP decorator is omitted as per instructions +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_interactivedisplaybase' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() + +def interactive_display_base(): + """ + Placeholder for the deprecated Bioconductor R library 'interactiveDisplayBase'. + + This package is an R library for building interactive Shiny applications and does not + provide a command-line interface. It is also deprecated and has been removed from + Bioconductor. As such, it cannot be executed as a standard command-line tool. + This function returns an informative message instead of executing a command. + """ + # This is not a command-line tool. The core functionality is to provide + # methods within an R session to generate interactive Shiny displays. + # This is fundamentally incompatible with the non-interactive MCP model. + # The package is also deprecated. + # Therefore, this function does not execute any subprocess. + # It returns a structured message explaining the situation. + + info_message = ( + "The 'bioconductor-interactivedisplaybase' package is an R library for " + "creating interactive Shiny applications and does not have a command-line interface. " + "It is also deprecated and removed from Bioconductor. " + "Therefore, it cannot be executed as a command-line tool." + ) + + return { + "command_executed": "", + "stdout": info_message, + "stderr": "This is an informational message, not an error.", + "output_files": [] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-interactivedisplaybase/app/bioconductor-interactivedisplaybase_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-interactivedisplaybase/app/bioconductor-interactivedisplaybase_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..81eeaeb6e1e6f86a7f35fa57c90ac17a9a1297c2 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-interactivedisplaybase/app/bioconductor-interactivedisplaybase_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-interactivedisplaybase/app/bioconductor-interactivedisplaybase_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_interactivedisplaybase' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-interactivedisplaybase/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-interactivedisplaybase/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-interactivedisplaybase/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-interactivedisplaybase/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-interactivedisplaybase/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..27fcbcd7b100fb67df8f591cfedd0287e52a7609 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-interactivedisplaybase/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-interactivedisplaybase: + build: . + image: mcp-bioconductor-interactivedisplaybase:latest + container_name: mcp-bioconductor-interactivedisplaybase + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-interactivedisplaybase + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-interactivedisplaybase/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-interactivedisplaybase/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..638e635c19674a5a595d4c598bcfedd9f61d7e11 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-interactivedisplaybase/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-interactivedisplaybase + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-interactivedisplaybase/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-interactivedisplaybase/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-interactivedisplaybase/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3610c0c4ce00dcc7bd542c046f85f7b176810e64 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-metabolomicsworkbenchr via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-metabolomicsworkbenchr -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY bioconductor-metabolomicsworkbenchr_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-metabolomicsworkbenchr_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-metabolomicsworkbenchr_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/app/__pycache__/bioconductor-metabolomicsworkbenchr_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/app/__pycache__/bioconductor-metabolomicsworkbenchr_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ac2dd476272cb0f83ddebb8b871e0ab24bd19b95 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/app/__pycache__/bioconductor-metabolomicsworkbenchr_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/app/bioconductor-metabolomicsworkbenchr_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/app/bioconductor-metabolomicsworkbenchr_server.py new file mode 100644 index 0000000000000000000000000000000000000000..df5e345233e617e0087595bfa61be17692c96fe6 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/app/bioconductor-metabolomicsworkbenchr_server.py @@ -0,0 +1,125 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +# The user's prompt mentions `bioconductor-metabolomicsworkbenchr`, which is an R package. +# The provided help output is for `Rscript`, the command-line tool used to execute R scripts. +# This MCP tool correctly wraps the `Rscript` executable, which can then be used to run +# scripts that utilize packages like `bioconductor-metabolomicsworkbenchr`. + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_metabolomicsworkbenchr' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def rscript( + script_file: Optional[Path] = None, + expressions: Optional[List[str]] = None, + script_args: Optional[List[str]] = None, + verbose: bool = False, + default_packages: Optional[str] = None, + save: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: bool = False, + restore: bool = False, + vanilla: bool = False +) -> Dict[str, Any]: + """ + Executes an R script or R expressions using the Rscript command-line tool. + + This tool serves as a wrapper around the `Rscript` executable, allowing for the execution + of R code from a file or directly as string expressions. It mirrors the command-line + options of Rscript and can be used to run any R script, including those that use + Bioconductor packages like metabolomicsworkbenchr. + + Args: + script_file: Path to the R script file to be executed. Mutually exclusive with 'expressions'. + expressions: A list of R expressions to execute. Use instead of 'script_file'. + script_args: A list of arguments to be passed to the R script itself. + verbose: If True, enables verbose output from Rscript (--verbose). + default_packages: A comma-separated string of R package names to be loaded by default (--default-packages). + save: If True, the R workspace will be saved at the end of the session (--save). Ignored if 'vanilla' is True. + no_environ: If True, site and user environment files will not be read (--no-environ). Ignored if 'vanilla' is True. + no_site_file: If True, the site-wide Rprofile will not be read (--no-site-file). Ignored if 'vanilla' is True. + no_init_file: If True, the user's R profile will not be read (--no-init-file). Ignored if 'vanilla' is True. + restore: If True, previously saved objects will be restored at startup (--restore). Ignored if 'vanilla' is True. + vanilla: If True, provides a "clean" R session by combining --no-save, --no-restore, --no-site-file, + --no-init-file, and --no-environ. If set, it overrides the individual flags it controls. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + Note: `output_files` will be empty as this wrapper cannot determine what files the user's R script might generate. + """ + # --- Input Validation --- + if not script_file and not expressions: + raise ValueError("Either 'script_file' or 'expressions' must be provided.") + if script_file and expressions: + raise ValueError("'script_file' and 'expressions' are mutually exclusive and cannot be used together.") + + if script_file: + if not script_file.is_file(): + raise FileNotFoundError(f"The specified script file does not exist: {script_file}") + + # --- Command Construction --- + cmd = ["Rscript"] + + if vanilla: + cmd.append("--vanilla") + else: + if save: + cmd.append("--save") + if no_environ: + cmd.append("--no-environ") + if no_site_file: + cmd.append("--no-site-file") + if no_init_file: + cmd.append("--no-init-file") + if restore: + cmd.append("--restore") + + if verbose: + cmd.append("--verbose") + + if default_packages: + cmd.extend(["--default-packages", default_packages]) + + if expressions: + for expr in expressions: + cmd.extend(["-e", expr]) + + if script_file: + cmd.append(str(script_file)) + + if script_args: + cmd.extend(script_args) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + raise RuntimeError("Rscript executable not found. Please ensure R is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + # Return a structured error response + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Rscript execution failed with return code {e.returncode}" + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/app/bioconductor-metabolomicsworkbenchr_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/app/bioconductor-metabolomicsworkbenchr_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..425c84ae588fe2882428d835b4a8969535d6738e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/app/bioconductor-metabolomicsworkbenchr_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-metabolomicsworkbenchr/app/bioconductor-metabolomicsworkbenchr_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_metabolomicsworkbenchr' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c2a2cdedf09310946c0907818a3eeadb20437bc4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-metabolomicsworkbenchr: + build: . + image: mcp-bioconductor-metabolomicsworkbenchr:latest + container_name: mcp-bioconductor-metabolomicsworkbenchr + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-metabolomicsworkbenchr + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9bde03c685868257823a92c9790c2ff89f26edee --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-metabolomicsworkbenchr + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-metabolomicsworkbenchr/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-mzr/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-mzr/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-mzr/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rbgl/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rbgl/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..53e2341acd3b052248da950dc9a85edca62d94d0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rbgl/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-rbgl via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-rbgl -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-rbgl_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-rbgl_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-rbgl_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rbgl/app/bioconductor-rbgl_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rbgl/app/bioconductor-rbgl_server.py new file mode 100644 index 0000000000000000000000000000000000000000..027c8b4f141ddbb6a7163ed87d3b281391f9fef5 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rbgl/app/bioconductor-rbgl_server.py @@ -0,0 +1,137 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Dict, Any + +# No mcp import needed as per instructions + +# The bioconductor-rbgl package is an R library and does not expose a direct +# command-line interface with subcommands or parameters that can be parsed +# from standard CLI help. The provided documentation confirms this by showing +# an Rscript error and directing users to R-specific documentation (vignettes, +# reference manual) for usage. +# +# To interact with RBGL, one typically writes an R script that loads the +# package and calls its functions. Since the specific R functions, their +# arguments, and return types are not detailed in the provided documentation, +# it is impossible to create individual MCP tools for "EVERY internal functions" +# of the RBGL package. +# +# This MCP tool provides a generic interface to execute R code, allowing users +# to leverage RBGL's functionality by supplying the necessary R script. + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_rbgl' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def execute_rbgl_r_code( + r_code: str, + output_file_patterns: Optional[List[str]] = None, + r_args: Optional[List[str]] = None, + working_directory: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Executes R code that can utilize the Bioconductor RBGL package. + + This tool provides a generic interface to run R scripts that leverage + the RBGL library for graph algorithms. Since RBGL is an R package and + does not expose a direct command-line interface, users are expected + to provide the R code directly. The R code should typically include + `library(RBGL)` to load the package. + + Args: + r_code: A string containing the R code to execute. This code should + include `library(RBGL)` and calls to RBGL functions as needed. + output_file_patterns: An optional list of glob patterns (e.g., "*.csv", "output_*.txt") + to identify and collect output files generated by the R script + within the working directory. + r_args: Optional list of additional arguments to pass to Rscript. + These can be accessed within the R script via `commandArgs(trailingOnly=TRUE)`. + working_directory: Optional path to a directory where the R script + should be executed. If not provided, a temporary + directory will be used. + + Returns: + A dictionary containing the command executed, stdout, stderr, and + a list of any output files generated. + """ + if not r_code: + raise ValueError("R code cannot be empty.") + + command = ["Rscript", "-e", r_code] + + if r_args: + command.extend(r_args) + + output_files: List[Path] = [] + temp_dir: Optional[tempfile.TemporaryDirectory] = None + actual_working_dir: Path + + try: + if working_directory: + if not working_directory.is_dir(): + raise ValueError(f"Working directory '{working_directory}' does not exist or is not a directory.") + actual_working_dir = working_directory + else: + temp_dir = tempfile.TemporaryDirectory() + actual_working_dir = Path(temp_dir.name) + + process = subprocess.run( + command, + cwd=actual_working_dir, + capture_output=True, + text=True, + check=True + ) + + # Collect output files based on provided patterns or list all if no patterns + if output_file_patterns: + for pattern in output_file_patterns: + for f in actual_working_dir.glob(pattern): + if f.is_file(): + output_files.append(f) + else: + # If no patterns, collect all non-hidden files in the working directory + for f in actual_working_dir.iterdir(): + if f.is_file() and not f.name.startswith("."): + output_files.append(f) + + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(f) for f in output_files] + } + + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Rscript execution failed with exit code {e.returncode}", + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: Rscript command not found. Is R installed and in PATH?", + "error": "Rscript command not found", + "output_files": [] + } + except ValueError as e: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": str(e), + "error": "Input validation error", + "output_files": [] + } + finally: + if temp_dir: + temp_dir.cleanup() + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rbgl/app/bioconductor-rbgl_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rbgl/app/bioconductor-rbgl_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a4bcbd638957fe106a6847e91d9575c628f3929d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rbgl/app/bioconductor-rbgl_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/app/bioconductor-rbgl_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_rbgl' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rbgl/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rbgl/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8476e0fe29a2433391cebe3367ae4506229d61e0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rbgl/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-rbgl + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-reactomegsa.data/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-reactomegsa.data/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a70a7575b3d2098adb631cc68af8591f602439f8 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-reactomegsa.data/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-reactomegsa.data via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-reactomegsa.data -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-reactomegsa.data_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-reactomegsa.data_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-reactomegsa.data_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-reactomegsa.data/app/__pycache__/bioconductor-reactomegsa.data_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-reactomegsa.data/app/__pycache__/bioconductor-reactomegsa.data_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00e0cca6a756283de4435ba91f0b0ea6e5e81fa5 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-reactomegsa.data/app/__pycache__/bioconductor-reactomegsa.data_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-reactomegsa.data/app/bioconductor-reactomegsa.data_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-reactomegsa.data/app/bioconductor-reactomegsa.data_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8b745015a1c26661592b7c4de48237bbc4f35b61 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-reactomegsa.data/app/bioconductor-reactomegsa.data_server.py @@ -0,0 +1,120 @@ +import subprocess +from pathlib import Path +from typing import Optional, List + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_reactomegsa_data' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def get_citation( + rscript_path: Path = Path("Rscript"), + output_file: Optional[Path] = None, +) -> dict: + """ + Retrieves the citation information for the bioconductor-reactomegsa.data R package. + + This package is a Bioconductor data package for the R environment and does not + expose direct command-line subcommands in the traditional sense. This function + wraps an Rscript call to ensure the package and its manager (BiocManager) are + installed, then loads the package, and finally extracts its citation information. + + Args: + rscript_path: Path to the Rscript executable. Defaults to 'Rscript', + assuming it's in the system's PATH. + output_file: Optional path to save the citation output to a file. + If not provided, the citation will be returned in stdout. + + Returns: + A dictionary containing the command executed, stdout, stderr, and + a list of any output files. + """ + # Validate rscript_path + rscript_executable: str + if not rscript_path.is_absolute(): + try: + # Check if 'Rscript' is in PATH + subprocess.run(["which", "Rscript"], check=True, capture_output=True) + rscript_executable = "Rscript" + except subprocess.CalledProcessError: + raise FileNotFoundError( + f"Rscript not found in system PATH. Please ensure R is installed " + "and Rscript is accessible, or provide an absolute path to Rscript." + ) + elif not rscript_path.is_file(): + raise FileNotFoundError(f"Rscript not found at the specified path: {rscript_path}") + else: + rscript_executable = str(rscript_path) + + # R command to: + # 1. Install BiocManager if not already installed. + # 2. Install ReactomeGSA.data if not already installed (using BiocManager). + # 3. Load the ReactomeGSA.data library. + # 4. Print the citation information. + r_code = ( + 'if (!require("BiocManager", quietly = TRUE)) install.packages("BiocManager"); ' + 'if (!require("ReactomeGSA.data", quietly = TRUE)) BiocManager::install("ReactomeGSA.data", update = FALSE, ask = FALSE); ' + 'library(ReactomeGSA.data); ' + 'print(citation("ReactomeGSA.data"))' + ) + + command = [ + rscript_executable, + "-e", + r_code + ] + + stdout_capture = "" + stderr_capture = "" + output_files_list: List[str] = [] + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True + ) + stdout_capture = process.stdout + stderr_capture = process.stderr + + if output_file: + output_file.parent.mkdir(parents=True, exist_ok=True) + output_file.write_text(stdout_capture) + output_files_list.append(str(output_file)) + + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": f"Rscript execution failed with exit code {e.returncode}. Stderr: {e.stderr}" + } + except FileNotFoundError as e: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": str(e), + "output_files": [], + "error": f"Executable not found: {e}" + } + except Exception as e: + return { + "command_executed": " ".join(command), + "stdout": stdout_capture, + "stderr": stderr_capture, + "output_files": [], + "error": f"An unexpected error occurred: {str(e)}" + } + + return { + "command_executed": " ".join(command), + "stdout": stdout_capture, + "stderr": stderr_capture, + "output_files": output_files_list + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-reactomegsa.data/app/bioconductor-reactomegsa.data_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-reactomegsa.data/app/bioconductor-reactomegsa.data_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0d1ff24b3e4c830afe24e4f9f50df4d988ac618a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-reactomegsa.data/app/bioconductor-reactomegsa.data_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-reactomegsa.data/app/bioconductor-reactomegsa.data_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_reactomegsa_data' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-reactomegsa.data/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-reactomegsa.data/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..60dee9c55100465544eb8f835941791188519aa1 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-reactomegsa.data/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-reactomegsa.data: + build: . + image: mcp-bioconductor-reactomegsa.data:latest + container_name: mcp-bioconductor-reactomegsa.data + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-reactomegsa.data + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-reactomegsa.data/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-reactomegsa.data/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ac58425c4535a7f2f525163a6ee1f38aff304abc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-reactomegsa.data/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-reactomegsa.data + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-reactomegsa.data/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-reactomegsa.data/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-reactomegsa.data/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rhdf5lib/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rhdf5lib/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..092f3d6b4424cc3647a52adc9af228e1cb8277d7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rhdf5lib/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-rhdf5lib via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-rhdf5lib -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-rhdf5lib_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-rhdf5lib_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-rhdf5lib_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rhdf5lib/app/__pycache__/bioconductor-rhdf5lib_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rhdf5lib/app/__pycache__/bioconductor-rhdf5lib_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00c8d0709abd6005ef50803898d5731879113f98 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rhdf5lib/app/__pycache__/bioconductor-rhdf5lib_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rhdf5lib/app/bioconductor-rhdf5lib_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rhdf5lib/app/bioconductor-rhdf5lib_server.py new file mode 100644 index 0000000000000000000000000000000000000000..13b68eed5256245769e3e0b77bcff4c62d34a6b0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rhdf5lib/app/bioconductor-rhdf5lib_server.py @@ -0,0 +1,33 @@ +import subprocess +from pathlib import Path +from typing import Optional, List + +# NOTE: The 'mcp' import is not included as per the instructions. +# import mcp + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_rhdf5lib' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def rhdf5lib_info(): + """ + Provides information about the bioconductor-rhdf5lib package. + + This package is a library and does not provide any command-line executables. + It offers the HDF5 C and C++ libraries for other R packages to link against. + Therefore, this function is for informational purposes only and does not + execute any subprocess. + """ + # This is a library package with no executable. + # The return dictionary reflects that no command can be executed. + return { + "command_executed": "N/A (bioconductor-rhdf5lib is a library, not a command-line tool)", + "stdout": "This package provides C and C++ HDF5 libraries for use within the R environment. It has no direct command-line interface.", + "stderr": "", + "output_files": [] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rhdf5lib/app/bioconductor-rhdf5lib_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rhdf5lib/app/bioconductor-rhdf5lib_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..be58be4673ae03c74476c95791c724eeb10ff8ca --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rhdf5lib/app/bioconductor-rhdf5lib_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5lib/app/bioconductor-rhdf5lib_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_rhdf5lib' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rhdf5lib/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rhdf5lib/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rhdf5lib/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rhdf5lib/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rhdf5lib/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..76b1d4811a976df2b79fe83db8d4a84fd0ba1942 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rhdf5lib/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-rhdf5lib: + build: . + image: mcp-bioconductor-rhdf5lib:latest + container_name: mcp-bioconductor-rhdf5lib + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-rhdf5lib + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rhdf5lib/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rhdf5lib/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..017af4d64e893f7c7b7ba39e41e213740bfc4479 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rhdf5lib/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-rhdf5lib + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rhdf5lib/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rhdf5lib/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-rhdf5lib/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scalign/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scalign/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b59bf89a693f43400c771a6d529f61bafc3eafa5 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scalign/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-scalign via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scalign -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-scalign_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-scalign_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-scalign_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scalign/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scalign/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scalign/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scater/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scater/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ecac8858d36b4624367e8f98d559c4516e813f36 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scater/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-scater via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scater -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-scater_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-scater_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-scater_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scater/app/__pycache__/bioconductor-scater_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scater/app/__pycache__/bioconductor-scater_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a7603dc8053576720ec64cbe402d5bf16e7a7fd8 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scater/app/__pycache__/bioconductor-scater_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scater/app/bioconductor-scater_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scater/app/bioconductor-scater_server.py new file mode 100644 index 0000000000000000000000000000000000000000..073da0c304d07ed6cf2081cc74be6357b8e69b36 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scater/app/bioconductor-scater_server.py @@ -0,0 +1,215 @@ +import subprocess +import tempfile +import textwrap +from pathlib import Path +from typing import List, Optional + + +def _validate_r_input(input_path: Path): + """Check if the input file exists and has a .rds extension.""" + if not input_path.exists(): + raise FileNotFoundError(f"Input file not found: {input_path}") + if input_path.suffix.lower() != ".rds": + raise ValueError(f"Input file must be an RDS file (*.rds), but got: {input_path}") + +# @mcp.tool() decorator would be here in a real MCP environment +def run_scater_workflow( + input_sce_rds: Path, + output_prefix: str = "scater_analysis", + mito_pattern: str = "^MT-", + nmads: float = 3.0, + min_library_size: Optional[int] = None, + min_features: Optional[int] = None, + max_mito_percent: Optional[float] = None, + run_pca: bool = True, + n_pca_components: int = 50, + run_tsne: bool = True, + tsne_perplexity: int = 30, + run_umap: bool = True, + umap_n_neighbors: int = 15, + n_top_features_plot: int = 20, + plot_format: str = "png", +) -> dict: + """ + Executes a standard scRNA-seq QC and visualization workflow using the scater R package. + + This tool takes a SingleCellExperiment object (in RDS format), calculates quality + control metrics, performs filtering, normalizes the data, runs dimensionality + reduction (PCA, t-SNE, UMAP), and generates diagnostic plots. + + Args: + input_sce_rds: Path to the input SingleCellExperiment object saved as an RDS file. + output_prefix: Prefix for all output files (e.g., plots, processed RDS). + mito_pattern: Regex pattern to identify mitochondrial genes for QC. + nmads: Number of median absolute deviations (MADs) to use for adaptive thresholding in QC filtering. + min_library_size: If set, filters cells with a total library size (sum of counts) below this value. Overrides MAD-based filtering for library size. + min_features: If set, filters cells with a number of detected features below this value. Overrides MAD-based filtering for features. + max_mito_percent: If set, filters cells with a mitochondrial read percentage above this value. Overrides MAD-based filtering for mito percent. + run_pca: Whether to perform Principal Component Analysis (PCA). + n_pca_components: Number of principal components to compute. + run_tsne: Whether to perform t-SNE dimensionality reduction. + tsne_perplexity: Perplexity parameter for the t-SNE algorithm. + run_umap: Whether to perform UMAP dimensionality reduction. + umap_n_neighbors: Number of neighbors parameter for the UMAP algorithm. + n_top_features_plot: Number of top expressed features to include in the summary plot. + plot_format: The file format for the output plots ('png', 'pdf', 'svg'). + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output file paths. + """ + # --- Input Validation --- + _validate_r_input(input_sce_rds) + if n_pca_components <= 0: + raise ValueError("n_pca_components must be a positive integer.") + if tsne_perplexity <= 0: + raise ValueError("tsne_perplexity must be a positive integer.") + if umap_n_neighbors <= 0: + raise ValueError("umap_n_neighbors must be a positive integer.") + if n_top_features_plot <= 0: + raise ValueError("n_top_features_plot must be a positive integer.") + if plot_format.lower() not in ["png", "pdf", "svg"]: + raise ValueError("plot_format must be one of 'png', 'pdf', or 'svg'.") + + # --- R Script Generation --- + # Note: Modern scater relies heavily on scuttle for QC and normalization. + # The script reflects current best practices. + r_script_content = textwrap.dedent(f""" + # Load necessary libraries + suppressPackageStartupMessages(library(scater)) + suppressPackageStartupMessages(library(scuttle)) + suppressPackageStartupMessages(library(SingleCellExperiment)) + suppressPackageStartupMessages(library(ggplot2)) + suppressPackageStartupMessages(library(BiocParallel)) + + # Set a seed for reproducibility + set.seed(42) + + # --- 1. Load Data --- + cat("Loading input SingleCellExperiment object from {input_sce_rds}\\n") + sce <- readRDS("{input_sce_rds}") + + # --- 2. Quality Control --- + cat("Calculating per-cell QC metrics...\\n") + mito_genes <- grepl("{mito_pattern}", rownames(sce)) + sce <- addPerCellQC(sce, subsets=list(Mito=mito_genes), BPPARAM=SerialParam()) + + # --- 3. Filtering --- + cat("Filtering low-quality cells...\\n") + # Using isOutlier from scuttle for adaptive filtering + qc_reasons <- perCellQCFilters(sce, sub.fields="subsets_Mito_percent", nmads={nmads}) + + # Override with fixed thresholds if provided + if (!is.null({min_library_size if min_library_size is not None else 'NULL'})) {{ + qc_reasons$low_libsize <- sce$sum < {min_library_size} + }} + if (!is.null({min_features if min_features is not None else 'NULL'})) {{ + qc_reasons$low_n_features <- sce$detected < {min_features} + }} + if (!is.null({max_mito_percent if max_mito_percent is not None else 'NULL'})) {{ + qc_reasons$high_subsets_Mito_percent <- sce$subsets_Mito_percent > {max_mito_percent} + }} + + # Combine filters and subset the object + colData(sce)$discard <- qc_reasons$discard + sce_filtered <- sce[, !sce$discard] + cat(paste("Removed", sum(sce$discard), "cells out of", ncol(sce), "\\n")) + cat(paste("Remaining cells:", ncol(sce_filtered), "\\n")) + + # --- 4. Normalization --- + cat("Performing log-normalization...\\n") + sce_filtered <- logNormCounts(sce_filtered) + + # --- 5. Dimensionality Reduction --- + if ({str(run_pca).upper()}) {{ + cat("Running PCA...\\n") + sce_filtered <- runPCA(sce_filtered, ncomponents={n_pca_components}) + }} + if ({str(run_tsne).upper()}) {{ + cat("Running t-SNE...\\n") + sce_filtered <- runTSNE(sce_filtered, dimred="PCA", perplexity={tsne_perplexity}, BPPARAM=SerialParam()) + }} + if ({str(run_umap).upper()}) {{ + cat("Running UMAP...\\n") + sce_filtered <- runUMAP(sce_filtered, dimred="PCA", n_neighbors={umap_n_neighbors}) + }} + + # --- 6. Visualization --- + cat("Generating plots...\\n") + plot_ext <- ".{plot_format.lower()}" + + # Plot QC metrics on original data + p1 <- plotColData(sce, x="sum", y="detected", colour_by="discard", + other_fields="subsets_Mito_percent") + + scale_x_log10() + scale_y_log10() + + labs(title="QC: Library Size vs Features", x="Total Counts (log10)", y="Detected Features (log10)") + + guides(colour=guide_legend(title="Discarded"), size=guide_legend(title="Mito %")) + ggsave(paste0("{output_prefix}_qc_metrics", plot_ext), p1, width=7, height=5) + + # Plot highest expressed features + p2 <- plotHighestExprs(sce_filtered, n={n_top_features_plot}) + + labs(title="Top Expressed Features") + ggsave(paste0("{output_prefix}_highest_exprs", plot_ext), p2, width=8, height=6) + + # Plot reduced dimensions + if ({str(run_pca).upper()}) {{ + p_pca <- plotReducedDim(sce_filtered, "PCA", colour_by="sum") + + labs(title="PCA colored by Library Size") + ggsave(paste0("{output_prefix}_pca", plot_ext), p_pca, width=6, height=5) + }} + if ({str(run_tsne).upper()}) {{ + p_tsne <- plotReducedDim(sce_filtered, "TSNE", colour_by="detected") + + labs(title="t-SNE colored by Detected Features") + ggsave(paste0("{output_prefix}_tsne", plot_ext), p_tsne, width=6, height=5) + }} + if ({str(run_umap).upper()}) {{ + p_umap <- plotReducedDim(sce_filtered, "UMAP", colour_by="subsets_Mito_percent") + + labs(title="UMAP colored by Mito %") + ggsave(paste0("{output_prefix}_umap", plot_ext), p_umap, width=6, height=5) + }} + + # --- 7. Save Processed Object --- + output_rds_path <- paste0("{output_prefix}_processed.rds") + cat(paste("Saving processed SingleCellExperiment object to", output_rds_path, "\\n")) + saveRDS(sce_filtered, file=output_rds_path) + + cat("Workflow completed successfully.\\n") + """) + + with tempfile.TemporaryDirectory() as temp_dir: + temp_path = Path(temp_dir) + r_script_path = temp_path / "scater_script.R" + with open(r_script_path, "w") as f: + f.write(r_script_content) + + cmd = ["Rscript", str(r_script_path)] + command_executed = " ".join(cmd) + + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + cwd=temp_path, # Run in temp_dir to catch output files + ) + + # --- Collect Output Files --- + output_files: List[str] = [] + for f in temp_path.glob(f"{output_prefix}*"): + # In a real scenario, you'd move these to a persistent output directory + output_files.append(str(f.resolve())) + + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Scater R script execution failed.", + "return_code": e.returncode, + } diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scater/app/bioconductor-scater_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scater/app/bioconductor-scater_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c47cf4739272b6fa86f0c3b477265ef4fd21fdcb --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scater/app/bioconductor-scater_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scater/app/bioconductor-scater_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_scater' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scater/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scater/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scater/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scater/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scater/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..2cee130eee4b88d8d1c1eb77ebf9173ae81d9e07 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scater/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-scater: + build: . + image: mcp-bioconductor-scater:latest + container_name: mcp-bioconductor-scater + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-scater + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scater/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scater/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4e2a13db73602caa732ca760f80d8e2a9c6c4493 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scater/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-scater + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scater/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scater/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scater/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scider/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scider/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e46a957702f3848c6506b86567b32db307d5f4d9 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scider/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-scider via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scider -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-scider_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-scider_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-scider_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scider/app/__pycache__/bioconductor-scider_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scider/app/__pycache__/bioconductor-scider_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08378d46480352463619acd9264d83c857a21b98 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scider/app/__pycache__/bioconductor-scider_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scider/app/bioconductor-scider_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scider/app/bioconductor-scider_server.py new file mode 100644 index 0000000000000000000000000000000000000000..60c8a7734bc57a8b48d1237b09ddec16cf0f4364 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scider/app/bioconductor-scider_server.py @@ -0,0 +1,465 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Literal, Optional + +# It is assumed that the mcp package is installed and its decorator is available. +# from mcp import tool as mcp_tool +# For the purpose of this example, we will use a dummy decorator. +class mcp: + def tool(func): + return func + +TEST_USE_METHODS = Literal[ + "wilcox", "bimod", "roc", "t", "negbinom", "poisson", "LR", "MAST", "DESeq2" +] + +def _execute_r_script(r_script_content: str, command_name: str) -> dict: + """ + A helper function to execute an R script using a temporary file. + + Args: + r_script_content: A string containing the R code to execute. + command_name: The name of the scider function being called, for error reporting. + + Returns: + A dictionary containing the execution results. + """ + try: + with tempfile.NamedTemporaryFile( + mode="w", suffix=".R", delete=False + ) as r_script_file: + r_script_path = Path(r_script_file.name) + r_script_file.write(r_script_content) + + command = ["Rscript", str(r_script_path)] + process = subprocess.run( + command, capture_output=True, text=True, check=True + ) + + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + } + except FileNotFoundError: + return { + "command_executed": " ".join(command) if 'command' in locals() else "Rscript not found", + "stdout": "", + "stderr": "Rscript not found. Please ensure R and Rscript are in your system's PATH.", + "error": "Prerequisite not met." + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed for {command_name}.", + "return_code": e.returncode, + } + finally: + if "r_script_path" in locals() and r_script_path.exists(): + r_script_path.unlink() + + +@mcp.tool +def recluster( + input_rds: Path, + output_rds: Path, + recluster_method: Literal["Default", "SNN", "hclust"] = "Default", + resolution: float = 0.5, + num_pc: int = 10, +): + """ + Re-clusters a Seurat object using methods from the scider package. + + Args: + input_rds: Path to the input Seurat object saved as an RDS file. + output_rds: Path to save the re-clustered Seurat object as an RDS file. + recluster_method: Method to use for reclustering. + resolution: Resolution parameter for clustering. + num_pc: Number of principal components to use. + """ + if not input_rds.is_file(): + raise FileNotFoundError(f"Input file not found: {input_rds}") + + output_rds.parent.mkdir(parents=True, exist_ok=True) + + r_script = f""" + library(scider) + library(Seurat) + + seurat_object <- readRDS("{input_rds.resolve()}") + + updated_object <- recluster( + object = seurat_object, + recluster_method = "{recluster_method}", + resolution = {resolution}, + num_pc = {num_pc} + ) + + saveRDS(updated_object, file = "{output_rds.resolve()}") + print("Reclustering completed successfully.") + """ + + result = _execute_r_script(r_script, "recluster") + if "error" not in result: + result["output_files"] = [str(output_rds.resolve())] + return result + + +@mcp.tool +def find_isc( + input_rds: Path, + output_rds: Path, + species: Literal["human", "mouse"] = "human", + tissue: str = "Default", + isc_genes_default: str = "Default", + isc_genes_user: Optional[Path] = None, + isc_method: Literal["Default", "Average"] = "Default", + isc_threshold: float = 0.5, + assay: str = "RNA", + slot: str = "data", +): + """ + Calculates the In-Situ Co-expression (ISC) score for a Seurat object. + + Args: + input_rds: Path to the input Seurat object saved as an RDS file. + output_rds: Path to save the updated Seurat object as an RDS file. + species: Species of the sample ('human' or 'mouse'). + tissue: Tissue type for default gene lists. + isc_genes_default: Default ISC gene list to use. + isc_genes_user: Path to a file with a user-provided list of ISC genes. + isc_method: Method for ISC calculation. + isc_threshold: Threshold for ISC score. + assay: Assay to use from the Seurat object. + slot: Slot to use from the assay. + """ + if not input_rds.is_file(): + raise FileNotFoundError(f"Input file not found: {input_rds}") + if isc_genes_user and not isc_genes_user.is_file(): + raise FileNotFoundError(f"User ISC genes file not found: {isc_genes_user}") + + output_rds.parent.mkdir(parents=True, exist_ok=True) + + isc_genes_user_r = f"'{isc_genes_user.resolve()}'" if isc_genes_user else "NULL" + + r_script = f""" + library(scider) + library(Seurat) + + seurat_object <- readRDS("{input_rds.resolve()}") + + updated_object <- findISC( + object = seurat_object, + species = "{species}", + tissue = "{tissue}", + ISC_genes_default = "{isc_genes_default}", + ISC_genes_user = {isc_genes_user_r}, + ISC_method = "{isc_method}", + ISC_threshold = {isc_threshold}, + assay = "{assay}", + slot = "{slot}" + ) + + saveRDS(updated_object, file = "{output_rds.resolve()}") + print("ISC calculation completed successfully.") + """ + + result = _execute_r_script(r_script, "findISC") + if "error" not in result: + result["output_files"] = [str(output_rds.resolve())] + return result + + +@mcp.tool +def find_de_genes( + input_rds: Path, + output_rds: Path, + logfc_threshold: float = 0.25, + test_use: TEST_USE_METHODS = "wilcox", + min_pct: float = 0.1, + min_diff_pct: Optional[float] = None, + only_pos: bool = False, + max_cells_per_ident: Optional[int] = None, + random_seed: int = 1, + min_cells_group: int = 3, + pseudocount_use: int = 1, + verbose: bool = True, + assay: str = "RNA", + slot: str = "data", +): + """ + Finds differentially expressed (DE) genes between cell clusters. + + Args: + input_rds: Path to the input Seurat object saved as an RDS file. + output_rds: Path to save the updated Seurat object as an RDS file. + logfc_threshold: Log-fold change threshold. + test_use: Statistical test to use. + min_pct: Minimum percentage of cells expressing the gene in either group. + min_diff_pct: Minimum percentage difference between the two groups. Defaults to -Inf. + only_pos: Only return positive markers. + max_cells_per_ident: Max cells per identity to subsample. Defaults to Inf. + random_seed: Random seed for reproducibility. + min_cells_group: Minimum number of cells in a group. + pseudocount_use: Pseudocount to add to averaged expression values. + verbose: Print progress and informational messages. + assay: Assay to use from the Seurat object. + slot: Slot to use from the assay. + """ + if not input_rds.is_file(): + raise FileNotFoundError(f"Input file not found: {input_rds}") + + output_rds.parent.mkdir(parents=True, exist_ok=True) + + min_diff_pct_r = str(min_diff_pct) if min_diff_pct is not None else "-Inf" + max_cells_per_ident_r = ( + str(max_cells_per_ident) if max_cells_per_ident is not None else "Inf" + ) + + r_script = f""" + library(scider) + library(Seurat) + + seurat_object <- readRDS("{input_rds.resolve()}") + + updated_object <- findDEgenes( + object = seurat_object, + logfc.threshold = {logfc_threshold}, + test.use = "{test_use}", + min.pct = {min_pct}, + min.diff.pct = {min_diff_pct_r}, + only.pos = {str(only_pos).upper()}, + max.cells.per.ident = {max_cells_per_ident_r}, + random.seed = {random_seed}, + min.cells.group = {min_cells_group}, + pseudocount.use = {pseudocount_use}, + verbose = {str(verbose).upper()}, + assay = "{assay}", + slot = "{slot}" + ) + + saveRDS(updated_object, file = "{output_rds.resolve()}") + print("DE gene analysis completed successfully.") + """ + + result = _execute_r_script(r_script, "findDEgenes") + if "error" not in result: + result["output_files"] = [str(output_rds.resolve())] + return result + + +@mcp.tool +def find_dr_genes( + input_rds: Path, + output_rds: Path, + logfc_threshold: float = 0.25, + test_use: TEST_USE_METHODS = "wilcox", + min_pct: float = 0.1, + min_diff_pct: Optional[float] = None, + only_pos: bool = False, + max_cells_per_ident: Optional[int] = None, + random_seed: int = 1, + min_cells_group: int = 3, + pseudocount_use: int = 1, + verbose: bool = True, + assay: str = "RNA", + slot: str = "data", +): + """ + Finds differentially regulated (DR) genes between cell clusters. + + Args: + input_rds: Path to the input Seurat object saved as an RDS file. + output_rds: Path to save the updated Seurat object as an RDS file. + logfc_threshold: Log-fold change threshold. + test_use: Statistical test to use. + min_pct: Minimum percentage of cells expressing the gene in either group. + min_diff_pct: Minimum percentage difference between the two groups. Defaults to -Inf. + only_pos: Only return positive markers. + max_cells_per_ident: Max cells per identity to subsample. Defaults to Inf. + random_seed: Random seed for reproducibility. + min_cells_group: Minimum number of cells in a group. + pseudocount_use: Pseudocount to add to averaged expression values. + verbose: Print progress and informational messages. + assay: Assay to use from the Seurat object. + slot: Slot to use from the assay. + """ + if not input_rds.is_file(): + raise FileNotFoundError(f"Input file not found: {input_rds}") + + output_rds.parent.mkdir(parents=True, exist_ok=True) + + min_diff_pct_r = str(min_diff_pct) if min_diff_pct is not None else "-Inf" + max_cells_per_ident_r = ( + str(max_cells_per_ident) if max_cells_per_ident is not None else "Inf" + ) + + r_script = f""" + library(scider) + library(Seurat) + + seurat_object <- readRDS("{input_rds.resolve()}") + + updated_object <- findDRgenes( + object = seurat_object, + logfc.threshold = {logfc_threshold}, + test.use = "{test_use}", + min.pct = {min_pct}, + min.diff.pct = {min_diff_pct_r}, + only.pos = {str(only_pos).upper()}, + max.cells.per.ident = {max_cells_per_ident_r}, + random.seed = {random_seed}, + min.cells.group = {min_cells_group}, + pseudocount.use = {pseudocount_use}, + verbose = {str(verbose).upper()}, + assay = "{assay}", + slot = "{slot}" + ) + + saveRDS(updated_object, file = "{output_rds.resolve()}") + print("DR gene analysis completed successfully.") + """ + + result = _execute_r_script(r_script, "findDRgenes") + if "error" not in result: + result["output_files"] = [str(output_rds.resolve())] + return result + + +@mcp.tool +def run_scider( + input_rds: Path, + output_dir: Path, + project: str = "scider", + method: Literal["DE", "DR", "ISC"] = "DE", + de_method: TEST_USE_METHODS = "wilcox", + dr_method: TEST_USE_METHODS = "wilcox", + logfc_threshold: float = 0.25, + test_use: TEST_USE_METHODS = "wilcox", + min_pct: float = 0.1, + min_diff_pct: Optional[float] = None, + return_thresh: float = 0.01, + only_pos: bool = False, + max_cells_per_ident: Optional[int] = None, + random_seed: int = 1, + min_cells_group: int = 3, + pseudocount_use: int = 1, + verbose: bool = True, + assay: str = "RNA", + slot: str = "data", + isc_method: Literal["Default", "Average"] = "Default", + isc_threshold: float = 0.5, + recluster_method: Literal["Default", "SNN", "hclust"] = "Default", + resolution: float = 0.5, + num_pc: int = 10, + species: Literal["human", "mouse"] = "human", + tissue: str = "Default", + isc_genes_default: str = "Default", + isc_genes_user: Optional[Path] = None, + marker_genes_default: str = "Default", + marker_genes_user: Optional[Path] = None, +): + """ + Run the main scider pipeline for cell type identification. + + Args: + input_rds: Path to the input Seurat object saved as an RDS file. + output_dir: Directory to save the output files. + project: Name for the project. + method: Main analysis method to run ('DE', 'DR', or 'ISC'). + de_method: Test to use for DE analysis. + dr_method: Test to use for DR analysis. + logfc_threshold: Log-fold change threshold. + test_use: Statistical test to use (often same as de_method). + min_pct: Minimum percentage of cells expressing a gene. + min_diff_pct: Minimum percentage difference. Defaults to -Inf. + return_thresh: P-value threshold for returning genes. + only_pos: Only return positive markers. + max_cells_per_ident: Max cells to subsample. Defaults to Inf. + random_seed: Random seed for reproducibility. + min_cells_group: Minimum number of cells in a group. + pseudocount_use: Pseudocount for expression averaging. + verbose: Print progress messages. + assay: Assay to use from the Seurat object. + slot: Slot to use from the assay. + isc_method: Method for ISC calculation. + isc_threshold: Threshold for ISC score. + recluster_method: Method for reclustering. + resolution: Resolution for clustering. + num_pc: Number of principal components. + species: Species of the sample. + tissue: Tissue type for default gene lists. + isc_genes_default: Default ISC gene list. + isc_genes_user: Path to user-provided ISC genes. + marker_genes_default: Default marker gene list. + marker_genes_user: Path to user-provided marker genes. + """ + if not input_rds.is_file(): + raise FileNotFoundError(f"Input file not found: {input_rds}") + if isc_genes_user and not isc_genes_user.is_file(): + raise FileNotFoundError(f"User ISC genes file not found: {isc_genes_user}") + if marker_genes_user and not marker_genes_user.is_file(): + raise FileNotFoundError(f"User marker genes file not found: {marker_genes_user}") + + output_dir.mkdir(parents=True, exist_ok=True) + + min_diff_pct_r = str(min_diff_pct) if min_diff_pct is not None else "-Inf" + max_cells_per_ident_r = ( + str(max_cells_per_ident) if max_cells_per_ident is not None else "Inf" + ) + isc_genes_user_r = f"'{isc_genes_user.resolve()}'" if isc_genes_user else "NULL" + marker_genes_user_r = ( + f"'{marker_genes_user.resolve()}'" if marker_genes_user else "NULL" + ) + + r_script = f""" + library(scider) + library(Seurat) + + seurat_object <- readRDS("{input_rds.resolve()}") + + runScider( + object = seurat_object, + method = "{method}", + de.method = "{de_method}", + dr.method = "{dr_method}", + logfc.threshold = {logfc_threshold}, + test.use = "{test_use}", + min.pct = {min_pct}, + min.diff.pct = {min_diff_pct_r}, + return.thresh = {return_thresh}, + only.pos = {str(only_pos).upper()}, + max.cells.per.ident = {max_cells_per_ident_r}, + random.seed = {random_seed}, + min.cells.group = {min_cells_group}, + pseudocount.use = {pseudocount_use}, + verbose = {str(verbose).upper()}, + assay = "{assay}", + slot = "{slot}", + ISC_method = "{isc_method}", + ISC_threshold = {isc_threshold}, + recluster_method = "{recluster_method}", + resolution = {resolution}, + num_pc = {num_pc}, + species = "{species}", + tissue = "{tissue}", + ISC_genes_default = "{isc_genes_default}", + ISC_genes_user = {isc_genes_user_r}, + marker_genes_default = "{marker_genes_default}", + marker_genes_user = {marker_genes_user_r}, + output_dir = "{output_dir.resolve()}", + project = "{project}" + ) + + print("scider analysis completed successfully.") + """ + + result = _execute_r_script(r_script, "runScider") + if "error" not in result: + result["output_files"] = [ + str(f) for f in output_dir.resolve().glob(f"{project}*") + ] + return result \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scider/app/bioconductor-scider_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scider/app/bioconductor-scider_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..20b4b706b2e329378750262eeed0408b9525682c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scider/app/bioconductor-scider_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scider/app/bioconductor-scider_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_scider' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scider/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scider/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scider/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scider/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scider/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..1b88e208285fa5607f1149c009f5c374d3dafc66 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scider/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-scider: + build: . + image: mcp-bioconductor-scider:latest + container_name: mcp-bioconductor-scider + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-scider + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scider/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scider/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4510862e3080f9e7b6678fbf28cb472d328a3b90 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scider/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-scider + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scider/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scider/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scider/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-screpertoire/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-screpertoire/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..58a8ac114185fc2d3241b13de38466865743288e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-screpertoire/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-screpertoire via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-screpertoire -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY bioconductor-screpertoire_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-screpertoire_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-screpertoire_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-screpertoire/app/__pycache__/bioconductor-screpertoire_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-screpertoire/app/__pycache__/bioconductor-screpertoire_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cca1c3d94f8f615aaa1c10d628df703b43782180 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-screpertoire/app/__pycache__/bioconductor-screpertoire_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-screpertoire/app/bioconductor-screpertoire_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-screpertoire/app/bioconductor-screpertoire_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c206962a9def5f0b82562d4b9fd95aa78f29a002 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-screpertoire/app/bioconductor-screpertoire_server.py @@ -0,0 +1,124 @@ +import subprocess +from pathlib import Path +from typing import List, Optional + +# MCP-ready code for the Rscript command-line tool. +# This tool is often used to execute scripts from Bioconductor packages +# like 'bioconductor-screpertoire'. + +# @mcp.tool() is a placeholder for the actual decorator. +# In a real MCP environment, you would import it: +# from mcp import tool as mcp_tool +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def rscript( + file: Optional[Path] = None, + expressions: Optional[List[str]] = None, + script_args: Optional[List[str]] = None, + verbose: bool = False, + default_packages: Optional[str] = None, + save: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: bool = False, + restore: bool = False, + vanilla: bool = False, +): + """ + Executes an R script or R expressions using the Rscript command-line tool. + + This tool serves as a wrapper for Rscript, allowing execution of R code from + the command line. You must provide either a script file or a list of R + expressions to execute. + + Args: + file: Path to the R script file to be executed. Mutually exclusive with 'expressions'. + expressions: A list of R expressions to execute using the '-e' flag. Mutually exclusive with 'file'. + script_args: A list of arguments to be passed to the R script specified by 'file'. + verbose: If True, corresponds to the --verbose flag, printing information on progress. + default_packages: A comma-separated list of package names to be loaded by default (e.g., "utils,graphics"). + save: If True, corresponds to the --save flag to save the workspace at the end of the session. Ignored if 'vanilla' is True. + no_environ: If True, corresponds to the --no-environ flag. Do not read site and user environment files. Ignored if 'vanilla' is True. + no_site_file: If True, corresponds to the --no-site-file flag. Do not read the site-wide Rprofile. Ignored if 'vanilla' is True. + no_init_file: If True, corresponds to the --no-init-file flag. Do not read the user R profile. Ignored if 'vanilla' is True. + restore: If True, corresponds to the --restore flag to restore previously saved objects at startup. Ignored if 'vanilla' is True. + vanilla: If True, combines --no-save, --no-restore, --no-site-file, --no-init-file, and --no-environ for a clean session. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + Note: Rscript itself does not define output files; any generated files are the responsibility of the R code being executed. + """ + # 1. Input Validation + if file and expressions: + raise ValueError("Cannot specify both 'file' and 'expressions'. They are mutually exclusive.") + if not file and not expressions: + raise ValueError("Must specify either 'file' or 'expressions' to execute.") + + if file: + if not file.is_file(): + raise FileNotFoundError(f"The specified R script file does not exist: {file}") + + if script_args and not file: + raise ValueError("'script_args' can only be provided when a 'file' is specified.") + + # 2. Command Construction + cmd = ["Rscript"] + + if vanilla: + cmd.append("--vanilla") + else: + if save: + cmd.append("--save") + if no_environ: + cmd.append("--no-environ") + if no_site_file: + cmd.append("--no-site-file") + if no_init_file: + cmd.append("--no-init-file") + if restore: + cmd.append("--restore") + + if verbose: + cmd.append("--verbose") + + if default_packages: + cmd.append(f"--default-packages={default_packages}") + + if expressions: + for expr in expressions: + cmd.extend(["-e", expr]) + elif file: + cmd.append(str(file)) + if script_args: + cmd.extend(script_args) + + # 3. Subprocess Execution + command_executed = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + raise RuntimeError("Rscript executable not found. Please ensure R is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + # Return a structured error response for failed executions + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Rscript execution failed with return code {e.returncode}", + "output_files": [] + } \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-screpertoire/app/bioconductor-screpertoire_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-screpertoire/app/bioconductor-screpertoire_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..de9059de52219c43f72262fed455c8a4e6be2761 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-screpertoire/app/bioconductor-screpertoire_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-screpertoire/app/bioconductor-screpertoire_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_screpertoire' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-screpertoire/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-screpertoire/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b0a54f57c7ea6cef53e891f8efe2038866bf1b3a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-screpertoire/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-screpertoire: + build: . + image: mcp-bioconductor-screpertoire:latest + container_name: mcp-bioconductor-screpertoire + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-screpertoire + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-screpertoire/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-screpertoire/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b21e34b0e36c58e80823e092ef267594f1c79970 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-screpertoire/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-screpertoire + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-screpertoire/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-screpertoire/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-screpertoire/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scuttle/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scuttle/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6ee53d55bd3a3c228d647c5517fa0f11641009fd --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scuttle/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-scuttle via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-scuttle -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-scuttle_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-scuttle_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-scuttle_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scuttle/app/__pycache__/bioconductor-scuttle_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scuttle/app/__pycache__/bioconductor-scuttle_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..61c31c7f242771c58455b1ba9fb8ffb353b00690 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scuttle/app/__pycache__/bioconductor-scuttle_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scuttle/app/bioconductor-scuttle_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scuttle/app/bioconductor-scuttle_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c4d1c90a5a6e03d5e29904c75261e066724ab28f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scuttle/app/bioconductor-scuttle_server.py @@ -0,0 +1,213 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional + +# Assume @mcp.tool is imported +# from mcp import tool as mcp_tool + +# This is a placeholder for the actual decorator as per instructions. +def mcp_tool_placeholder(*args, **kwargs): + def decorator(func): + return func + return decorator + +mcp = type("MCP", (), {"tool": mcp_tool_placeholder}) + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_scuttle' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def normalize_counts( + counts_matrix: Path, + output_matrix: Path, + size_factors_file: Optional[Path] = None, + center_size_factors: bool = True, + log_transform: bool = True, + pseudo_count: float = 1.0, +): + """ + Performs scaling normalization on a count matrix using scuttle::normalizeCounts. + + This function can compute normalized expression values, optionally on the log-scale. + It serves as a versatile wrapper for one of scuttle's primary normalization functions. + + Args: + counts_matrix: Path to the input count matrix file in CSV format. + The first column should contain gene names, and the header should contain cell names. + output_matrix: Path to save the output normalized matrix in CSV format. + size_factors_file: Optional path to a single-column file containing size factors for each cell. + If not provided, library sizes are used as size factors. + center_size_factors: A boolean indicating whether to center the size factors to have a mean of 1. + log_transform: A boolean indicating whether to apply a log2-transformation to the normalized counts. + pseudo_count: A positive pseudo-count to be added to counts before log-transformation. + This is only used if log_transform is True. + """ + # Input validation + if not counts_matrix.is_file(): + raise FileNotFoundError(f"Input counts matrix not found at {counts_matrix}") + if log_transform and pseudo_count <= 0: + raise ValueError("pseudo_count must be a positive number when log_transform is True.") + + size_factors_r_arg = "NULL" + if size_factors_file: + if not size_factors_file.is_file(): + raise FileNotFoundError(f"Size factors file not found at {size_factors_file}") + size_factors_r_arg = f'"{size_factors_file.resolve()}"' + + # Convert Python bool to R's TRUE/FALSE strings + center_sf_r = "TRUE" if center_size_factors else "FALSE" + log_transform_r = "TRUE" if log_transform else "FALSE" + + r_script_content = f""" + library(scuttle) + library(SingleCellExperiment) + + # Read the counts matrix + counts <- as.matrix(read.csv("{counts_matrix.resolve()}", row.names=1, check.names=FALSE)) + sce <- SingleCellExperiment(assays = list(counts = counts)) + + # Handle size factors if provided + size_factors_path <- {size_factors_r_arg} + size_factors_arg <- NULL + if (!is.null(size_factors_path)) {{ + sf <- read.table(size_factors_path, header=FALSE) + size_factors_arg <- as.numeric(sf[,1]) + }} + + # Perform normalization + normalized_matrix <- normalizeCounts( + sce, + size.factors=size_factors_arg, + center.size.factors={center_sf_r}, + log={log_transform_r}, + pseudo.count={pseudo_count} + ) + + # Write the output + write.csv(normalized_matrix, file="{output_matrix.resolve()}", row.names=TRUE, quote=FALSE) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_script: + script_path = Path(tmp_script.name) + tmp_script.write(r_script_content) + + cmd = ["Rscript", str(script_path)] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_matrix)] + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"R script execution failed with exit code {e.returncode}.\n" + f"Command: {command_executed}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) from e + finally: + # Ensure temporary script is always cleaned up + if script_path.exists(): + script_path.unlink() + + +@mcp.tool() +def aggregate_across_cells( + counts_matrix: Path, + ids_file: Path, + output_aggregated_matrix: Path, + use_assay_type: str = "counts", +): + """ + Aggregates counts across cells for specified groups using scuttle::aggregateAcrossCells. + + This is useful for creating pseudo-bulk expression profiles from single-cell data. + + Args: + counts_matrix: Path to the input count matrix file in CSV format. + The first column should contain gene names, and the header should contain cell names. + ids_file: Path to a single-column file containing group IDs (e.g., cluster or sample IDs) for each cell. + The order of IDs must match the order of columns (cells) in the counts_matrix. + output_aggregated_matrix: Path to save the output aggregated matrix in CSV format. + use_assay_type: The name of the assay in the SingleCellExperiment object to use for aggregation. + Defaults to "counts". + """ + # Input validation + if not counts_matrix.is_file(): + raise FileNotFoundError(f"Input counts matrix not found at {counts_matrix}") + if not ids_file.is_file(): + raise FileNotFoundError(f"IDs file not found at {ids_file}") + + r_script_content = f""" + library(scuttle) + library(SingleCellExperiment) + + # Read the counts matrix + counts <- as.matrix(read.csv("{counts_matrix.resolve()}", row.names=1, check.names=FALSE)) + sce <- SingleCellExperiment(assays = list(counts = counts)) + + # Read the IDs + ids <- read.table("{ids_file.resolve()}", header=FALSE, stringsAsFactors=TRUE) + ids_vector <- ids[,1] + + # Check if dimensions match + if (length(ids_vector) != ncol(sce)) {{ + stop(paste0("Number of IDs (", length(ids_vector), ") does not match the number of cells (", ncol(sce), ") in the count matrix.")) + }} + + # Perform aggregation + aggregated_sce <- aggregateAcrossCells(sce, ids=ids_vector, use.assay.type="{use_assay_type}") + + # Write the output + # The output assay from aggregateAcrossCells is named 'counts' by default. + aggregated_matrix <- assay(aggregated_sce, "counts") + write.csv(aggregated_matrix, file="{output_aggregated_matrix.resolve()}", row.names=TRUE, quote=FALSE) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_script: + script_path = Path(tmp_script.name) + tmp_script.write(r_script_content) + + cmd = ["Rscript", str(script_path)] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_aggregated_matrix)] + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"R script execution failed with exit code {e.returncode}.\n" + f"Command: {command_executed}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) from e + finally: + # Ensure temporary script is always cleaned up + if script_path.exists(): + script_path.unlink() + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scuttle/app/bioconductor-scuttle_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scuttle/app/bioconductor-scuttle_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0e3f9034d3bc8484de3e948658b1e5dfa679901d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scuttle/app/bioconductor-scuttle_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-scuttle/app/bioconductor-scuttle_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_scuttle' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scuttle/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scuttle/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scuttle/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scuttle/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scuttle/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7c909d0bead237aa9ab2f732c37ddf5c18ebc617 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scuttle/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-scuttle: + build: . + image: mcp-bioconductor-scuttle:latest + container_name: mcp-bioconductor-scuttle + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-scuttle + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scuttle/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scuttle/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5e6f64cd74a25ad0f22345f422a742ec8fde9ad4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scuttle/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-scuttle + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scuttle/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scuttle/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-scuttle/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-shortread/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-shortread/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..49ed5db0945a4bc42fc7769b3635b498da4a576b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-shortread/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-shortread via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-shortread -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-shortread_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-shortread_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-shortread_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-shortread/app/__pycache__/bioconductor-shortread_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-shortread/app/__pycache__/bioconductor-shortread_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..66ec71d469543db4d10d2b823a91343c9ace5a40 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-shortread/app/__pycache__/bioconductor-shortread_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-shortread/app/bioconductor-shortread_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-shortread/app/bioconductor-shortread_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d760f9f183b4fd02fb45dc064e1277e2e23cac21 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-shortread/app/bioconductor-shortread_server.py @@ -0,0 +1,278 @@ +import subprocess +import os +from pathlib import Path +from typing import Optional, List, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_shortread' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def shortread_qa( + input_dir: str, + pattern: str = ".*\\.fastq$", + output_dir: str = "qa_report", + sample_size: int = 1000000 +) -> Dict[str, Any]: + """ + Performs Quality Assessment (QA) on FASTQ files in a directory and generates an HTML report. + + Args: + input_dir: Directory containing FASTQ files. + pattern: Regular expression to match FASTQ filenames. + output_dir: Directory where the HTML report will be saved. + sample_size: Number of reads to sample for QA (default 1M). + """ + input_path = Path(input_dir) + if not input_path.is_dir(): + return {"error": f"Input directory {input_dir} does not exist."} + + # R script to run QA + r_code = f""" + suppressPackageStartupMessages(library(ShortRead)) + qa_results <- qa(dirPath = "{input_dir}", pattern = "{pattern}", sample = TRUE, n = {sample_size}) + report(qa_results, dest = "{output_dir}") + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"ShortRead::qa() on {input_dir}", + "stdout": result.stdout, + "stderr": result.stderr, + "output_directory": str(Path(output_dir).absolute()) + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def shortread_trim_tails( + input_file: str, + output_file: str, + k: int = 2, + a: str = "I", + successive: bool = True +) -> Dict[str, Any]: + """ + Trims low-quality ends from reads using the trimTails algorithm. + + Args: + input_file: Path to input FASTQ file. + output_file: Path to save the trimmed FASTQ file. + k: Number of successive nucleotides with quality <= 'a' to trigger trimming. + a: The quality threshold character (e.g., 'I' for Phred 40, '#' for Phred 2). + successive: Whether the low quality scores must be successive. + """ + if not Path(input_file).exists(): + return {"error": f"Input file {input_file} not found."} + + successive_r = "TRUE" if successive else "FALSE" + + r_code = f""" + suppressPackageStartupMessages(library(ShortRead)) + fq <- readFastq("{input_file}") + trimmed <- trimTails(fq, k = {k}, a = "{a}", successive = {successive_r}) + writeFastq(trimmed, "{output_file}") + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"ShortRead::trimTails({input_file})", + "stdout": result.stdout, + "output_file": str(Path(output_file).absolute()) + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} + +@mcp.tool() +def shortread_filter_n( + input_file: str, + output_file: str, + max_n: int = 0 +) -> Dict[str, Any]: + """ + Filters out reads containing more than the specified number of 'N' (ambiguous) nucleotides. + + Args: + input_file: Path to input FASTQ file. + output_file: Path to save the filtered FASTQ file. + max_n: Maximum number of Ns allowed per read (default 0). + """ + if not Path(input_file).exists(): + return {"error": f"Input file {input_file} not found."} + + r_code = f""" + suppressPackageStartupMessages(library(ShortRead)) + fq <- readFastq("{input_file}") + filt <- nFilter(threshold = {max_n}) + filtered_fq <- fq[filt(fq)] + writeFastq(filtered_fq, "{output_file}") + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"ShortRead::nFilter(threshold={max_n})", + "stdout": result.stdout, + "output_file": str(Path(output_file).absolute()) + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} + +@mcp.tool() +def shortread_alphabet_frequency( + input_file: str, + base_only: bool = True +) -> Dict[str, Any]: + """ + Calculates the frequency of nucleotides (A, C, G, T, N) across all reads in a FASTQ file. + + Args: + input_file: Path to input FASTQ file. + base_only: If True, only report standard DNA bases. + """ + if not Path(input_file).exists(): + return {"error": f"Input file {input_file} not found."} + + base_only_r = "TRUE" if base_only else "FALSE" + + r_code = f""" + suppressPackageStartupMessages(library(ShortRead)) + fq <- readFastq("{input_file}") + freqs <- alphabetFrequency(sread(fq), baseOnly = {base_only_r}) + total_freqs <- colSums(freqs) + print(total_freqs) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"ShortRead::alphabetFrequency({input_file})", + "stdout": result.stdout, + "nucleotide_counts": result.stdout.strip() + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} + +@mcp.tool() +def shortread_fastq_count( + input_file: str +) -> Dict[str, Any]: + """ + Quickly counts the number of reads in a FASTQ file using ShortRead's optimized reader. + + Args: + input_file: Path to input FASTQ file. + """ + if not Path(input_file).exists(): + return {"error": f"Input file {input_file} not found."} + + r_code = f""" + suppressPackageStartupMessages(library(ShortRead)) + # countFastq returns a data.frame with elements, records, and bytes + cnt <- countFastq("{input_file}") + cat(cnt$records) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"ShortRead::countFastq({input_file})", + "read_count": int(result.stdout.strip()) if result.stdout.strip().isdigit() else result.stdout.strip() + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} + +@mcp.tool() +def shortread_trim_lr_patterns( + input_file: str, + output_file: str, + left_pattern: str = "", + right_pattern: str = "", + max_l_mismatch: int = 0, + max_r_mismatch: int = 0, + with_l_indels: bool = False, + with_r_indels: bool = False +) -> Dict[str, Any]: + """ + Trims fixed patterns (like adapters or primers) from the left and/or right ends of reads. + + Args: + input_file: Path to input FASTQ file. + output_file: Path to save the trimmed FASTQ file. + left_pattern: DNA sequence pattern to trim from the 5' end. + right_pattern: DNA sequence pattern to trim from the 3' end. + max_l_mismatch: Maximum allowed mismatches for the left pattern. + max_r_mismatch: Maximum allowed mismatches for the right pattern. + with_l_indels: Allow indels in left pattern matching. + with_r_indels: Allow indels in right pattern matching. + """ + if not Path(input_file).exists(): + return {"error": f"Input file {input_file} not found."} + + l_indels = "TRUE" if with_l_indels else "FALSE" + r_indels = "TRUE" if with_r_indels else "FALSE" + + r_code = f""" + suppressPackageStartupMessages(library(ShortRead)) + fq <- readFastq("{input_file}") + trimmed <- trimLRPatterns( + Lpattern = "{left_pattern}", + Rpattern = "{right_pattern}", + subject = fq, + max.Lmismatch = {max_l_mismatch}, + max.Rmismatch = {max_r_mismatch}, + with.Lindels = {l_indels}, + with.Rindels = {r_indels} + ) + writeFastq(trimmed, "{output_file}") + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "ShortRead::trimLRPatterns", + "stdout": result.stdout, + "output_file": str(Path(output_file).absolute()) + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-shortread/app/bioconductor-shortread_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-shortread/app/bioconductor-shortread_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..65b4191ee49b748354e8dfc4718c15ef3ea889d5 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-shortread/app/bioconductor-shortread_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-shortread/app/bioconductor-shortread_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_shortread' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-shortread/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-shortread/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-shortread/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-shortread/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-shortread/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e5fbe972d4c91c6e95055b2deae82e8adf07186e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-shortread/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-shortread: + build: . + image: mcp-bioconductor-shortread:latest + container_name: mcp-bioconductor-shortread + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-shortread + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-shortread/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-shortread/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..42305183482f14a6b1c00be1d192ded37a6392c2 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-shortread/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-shortread + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-shortread/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-shortread/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-shortread/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellexperiment/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellexperiment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7c4e95eca297e7d55c4cfa497a9c13afe4e69936 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellexperiment/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-singlecellexperiment via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-singlecellexperiment -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-singlecellexperiment_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-singlecellexperiment_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-singlecellexperiment_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellexperiment/app/__pycache__/bioconductor-singlecellexperiment_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellexperiment/app/__pycache__/bioconductor-singlecellexperiment_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c29e47f023875fe4eea9ba0ba45eb9054537f61 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellexperiment/app/__pycache__/bioconductor-singlecellexperiment_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellexperiment/app/bioconductor-singlecellexperiment_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellexperiment/app/bioconductor-singlecellexperiment_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d7e629be6b5f73a7ee1ac6527ac60d762ac69660 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellexperiment/app/bioconductor-singlecellexperiment_server.py @@ -0,0 +1,183 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# @mcp.tool() - This decorator is commented out as per the instructions not to import mcp +def create_sce_from_files( + counts_matrix: Path, + output_rds: Path, + row_data: Optional[Path] = None, + col_data: Optional[Path] = None, + counts_header: bool = True, + counts_row_names_col: int = 1, + row_data_header: bool = True, + row_data_row_names_col: int = 1, + col_data_header: bool = True, + col_data_row_names_col: int = 1, +) -> dict: + """ + Creates a SingleCellExperiment object from tabular data files and saves it as an RDS file. + + This tool serves as a command-line wrapper for the Bioconductor SingleCellExperiment R package, + which itself is a library without a direct command-line interface. This function constructs + and executes an R script to load count data, optional row (gene) metadata, and optional + column (cell) metadata into a SingleCellExperiment object. + + Args: + counts_matrix: Path to the input count matrix file (e.g., CSV or TSV). + Rows should represent features (genes) and columns represent samples (cells). + output_rds: Path for the output RDS file where the SingleCellExperiment object will be saved. + row_data: Optional path to a file containing row/feature metadata. + The row names must correspond to the row names in the counts_matrix. + col_data: Optional path to a file containing column/sample metadata. + The row names must correspond to the column names in the counts_matrix. + counts_header: Whether the counts matrix file has a header row. + counts_row_names_col: The column number in the counts matrix file to be used as row names. + row_data_header: Whether the row data file has a header row. + row_data_row_names_col: The column number in the row data file to be used as row names. + col_data_header: Whether the column data file has a header row. + col_data_row_names_col: The column number in the column data file to be used as row names. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not counts_matrix.is_file(): + raise FileNotFoundError(f"Input counts matrix not found at: {counts_matrix}") + if row_data and not row_data.is_file(): + raise FileNotFoundError(f"Input row data file not found at: {row_data}") + if col_data and not col_data.is_file(): + raise FileNotFoundError(f"Input column data file not found at: {col_data}") + + if counts_row_names_col < 1: + raise ValueError("counts_row_names_col must be a positive integer.") + if row_data_row_names_col < 1: + raise ValueError("row_data_row_names_col must be a positive integer.") + if col_data_row_names_col < 1: + raise ValueError("col_data_row_names_col must be a positive integer.") + + # --- R Script Generation --- + r_script_content = f""" + # Load necessary library + if (!requireNamespace("SingleCellExperiment", quietly = TRUE)) {{ + stop("SingleCellExperiment package is not installed.") + }} + library(SingleCellExperiment) + + # --- Function to read data --- + # Using read.delim to be more generic for CSV/TSV + read_data <- function(file_path, header, row_names_col) {{ + tryCatch({{ + read.delim( + file_path, + header = as.logical(header), + row.names = row_names_col, + check.names = FALSE, + stringsAsFactors = FALSE + ) + }}, error = function(e) {{ + stop(paste("Failed to read file:", file_path, "\\nError:", e$message)) + }}) + }} + + # --- Read input files --- + cat("Reading counts matrix from: {counts_matrix}\\n") + counts_df <- read_data("{counts_matrix}", "{str(counts_header).upper()}", {counts_row_names_col}) + counts_mat <- as.matrix(counts_df) + + row_data_df <- NULL + """ + if row_data: + r_script_content += f""" + cat("Reading row data from: {row_data}\\n") + row_data_df <- read_data("{row_data}", "{str(row_data_header).upper()}", {row_data_row_names_col}) + # Ensure row data matches counts matrix rows + if (!all(rownames(counts_mat) %in% rownames(row_data_df))) {{ + stop("Some row names in the counts matrix are not present in the row data file.") + }} + row_data_df <- row_data_df[rownames(counts_mat), , drop = FALSE] + """ + + r_script_content += """ + col_data_df <- NULL + """ + if col_data: + r_script_content += f""" + cat("Reading column data from: {col_data}\\n") + col_data_df <- read_data("{col_data}", "{str(col_data_header).upper()}", {col_data_row_names_col}) + # Ensure col data matches counts matrix columns + if (!all(colnames(counts_mat) %in% rownames(col_data_df))) {{ + stop("Some column names in the counts matrix are not present in the column data file.") + }} + col_data_df <- col_data_df[colnames(counts_mat), , drop = FALSE] + """ + + r_script_content += f""" + # --- Create SingleCellExperiment object --- + cat("Creating SingleCellExperiment object...\\n") + sce <- SingleCellExperiment( + assays = list(counts = counts_mat), + rowData = row_data_df, + colData = col_data_df + ) + + # --- Save the object --- + output_file <- "{output_rds}" + cat(paste("Saving object to:", output_file, "\\n")) + tryCatch({{ + saveRDS(sce, file = output_file) + }}, error = function(e) {{ + stop(paste("Failed to save RDS file to:", output_file, "\\nError:", e$message)) + }}) + + cat("Successfully created and saved SingleCellExperiment object.\\n") + """ + + # --- Subprocess Execution --- + command: List[str] = [] + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + script_path = r_script_file.name + + command = ["Rscript", script_path] + + # Ensure output directory exists + output_rds.parent.mkdir(parents=True, exist_ok=True) + + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + + # Clean up the temporary script file + Path(script_path).unlink() + + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_rds)] + } + + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + # Clean up the temporary script file in case of error + if 'script_path' in locals() and Path(script_path).exists(): + Path(script_path).unlink() + + error_message = ( + f"R script execution failed with return code {e.returncode}.\n" + f"Stderr:\n{e.stderr}\n" + f"Stdout:\n{e.stdout}" + ) + raise RuntimeError(error_message) + except Exception as e: + # Clean up the temporary script file in case of other errors + if 'script_path' in locals() and Path(script_path).exists(): + Path(script_path).unlink() + raise e diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellexperiment/app/bioconductor-singlecellexperiment_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellexperiment/app/bioconductor-singlecellexperiment_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1e06d3143da9589b156c119bafed9cbb358733b3 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellexperiment/app/bioconductor-singlecellexperiment_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-singlecellexperiment/app/bioconductor-singlecellexperiment_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_singlecellexperiment' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellexperiment/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellexperiment/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellexperiment/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellexperiment/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellexperiment/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..955eed6c91ad8c7e5894ef429958ee1a3dfa2cfa --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellexperiment/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-singlecellexperiment: + build: . + image: mcp-bioconductor-singlecellexperiment:latest + container_name: mcp-bioconductor-singlecellexperiment + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-singlecellexperiment + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellexperiment/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellexperiment/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d6be8c97a2959b32a4427e954d009d82de100f7a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellexperiment/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-singlecellexperiment + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellexperiment/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellexperiment/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-singlecellexperiment/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spacetrooper/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spacetrooper/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f723bb954274e39466224af0e0cb709f767fb2a9 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spacetrooper/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-spacetrooper via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-spacetrooper -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-spacetrooper_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-spacetrooper_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-spacetrooper_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spacetrooper/app/__pycache__/bioconductor-spacetrooper_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spacetrooper/app/__pycache__/bioconductor-spacetrooper_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ab2b3c5ea9f86ae3b65c29a6e26c4ecbc910db3f Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spacetrooper/app/__pycache__/bioconductor-spacetrooper_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spacetrooper/app/bioconductor-spacetrooper_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spacetrooper/app/bioconductor-spacetrooper_server.py new file mode 100644 index 0000000000000000000000000000000000000000..71321684c65f065a93366e603c106047cd0b67f9 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spacetrooper/app/bioconductor-spacetrooper_server.py @@ -0,0 +1,288 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_spacetrooper' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def spacetrooper_deconvolve( + spe_path: str, + reference_path: str, + output_path: str, + n_iter: int = 1000, + n_burnin: int = 500, + n_chains: int = 1, + interactions: bool = True, + alpha: float = 1.0, + beta: float = 1.0, +) -> Dict[str, Any]: + """ + Perform spatial deconvolution using the spacetrooper Bayesian model. + + Args: + spe_path: Path to the input SpatialExperiment object (RDS format). + reference_path: Path to the reference scRNA-seq data (RDS format). + output_path: Path where the resulting spacetrooper object will be saved (RDS format). + n_iter: Number of MCMC iterations. + n_burnin: Number of burn-in iterations. + n_chains: Number of MCMC chains to run. + interactions: Whether to model spatial interactions between cell types. + alpha: Hyperparameter for the Dirichlet prior on cell type proportions. + beta: Hyperparameter for the spatial interaction terms. + """ + # Input validation + spe_file = Path(spe_path) + ref_file = Path(reference_path) + out_file = Path(output_path) + + if not spe_file.exists(): + raise FileNotFoundError(f"SpatialExperiment file not found: {spe_path}") + if not ref_file.exists(): + raise FileNotFoundError(f"Reference file not found: {reference_path}") + + if n_iter <= 0 or n_burnin < 0: + raise ValueError("n_iter must be positive and n_burnin must be non-negative.") + if n_iter <= n_burnin: + raise ValueError("n_iter must be greater than n_burnin.") + + # Construct R command + interactions_r = "TRUE" if interactions else "FALSE" + r_script = f""" + library(spacetrooper) + spe <- readRDS('{spe_path}') + ref <- readRDS('{reference_path}') + + results <- spacetrooper( + spe = spe, + reference = ref, + n_iter = {n_iter}, + n_burnin = {n_burnin}, + n_chains = {n_chains}, + interactions = {interactions_r}, + alpha = {alpha}, + beta = {beta} + ) + + saveRDS(results, '{output_path}') + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"spacetrooper::spacetrooper(n_iter={n_iter}, ...)", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(out_file)] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd + } + +@mcp.tool() +def spacetrooper_extract_weights( + results_path: str, + output_csv: str, + summary_stat: str = "mean" +) -> Dict[str, Any]: + """ + Extract cell type proportion weights from a spacetrooper results object. + + Args: + results_path: Path to the spacetrooper results RDS file. + output_csv: Path to save the extracted weights as a CSV file. + summary_stat: Statistic to use for weights ('mean', 'median', or 'mode'). + """ + res_file = Path(results_path) + if not res_file.exists(): + raise FileNotFoundError(f"Results file not found: {results_path}") + + if summary_stat not in ["mean", "median", "mode"]: + raise ValueError("summary_stat must be one of: 'mean', 'median', 'mode'") + + r_script = f""" + library(spacetrooper) + res <- readRDS('{results_path}') + weights <- get_weights(res, stat = '{summary_stat}') + write.csv(weights, '{output_csv}', row.names = TRUE) + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"spacetrooper::get_weights(stat='{summary_stat}')", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [output_csv] + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to extract weights", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def spacetrooper_plot_spatial_weights( + results_path: str, + output_plot: str, + cell_type: Optional[str] = None, + point_size: float = 1.5, + colorscale: str = "viridis" +) -> Dict[str, Any]: + """ + Generate spatial plots of cell type weights. + + Args: + results_path: Path to the spacetrooper results RDS file. + output_plot: Path to save the plot (e.g., .png, .pdf). + cell_type: Specific cell type to plot. If None, plots all major types. + point_size: Size of the spots in the spatial plot. + colorscale: R color palette to use. + """ + res_file = Path(results_path) + if not res_file.exists(): + raise FileNotFoundError(f"Results file not found: {results_path}") + + cell_type_arg = f"'{cell_type}'" if cell_type else "NULL" + + r_script = f""" + library(spacetrooper) + library(ggplot2) + res <- readRDS('{results_path}') + p <- plot_weights(res, cell_type = {cell_type_arg}, point_size = {point_size}) + + scale_fill_viridis_c(option = '{colorscale}') + + ggsave('{output_plot}', plot = p, width = 10, height = 8) + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "spacetrooper::plot_weights()", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [output_plot] + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to generate plot", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def spacetrooper_compute_interactions( + results_path: str, + output_csv: str, + prob_threshold: float = 0.95 +) -> Dict[str, Any]: + """ + Compute and extract significant spatial interactions between cell types. + + Args: + results_path: Path to the spacetrooper results RDS file. + output_csv: Path to save the interaction matrix/list. + prob_threshold: Posterior probability threshold for significance. + """ + res_file = Path(results_path) + if not res_file.exists(): + raise FileNotFoundError(f"Results file not found: {results_path}") + + if not (0 <= prob_threshold <= 1): + raise ValueError("prob_threshold must be between 0 and 1.") + + r_script = f""" + library(spacetrooper) + res <- readRDS('{results_path}') + interactions <- get_interactions(res, threshold = {prob_threshold}) + write.csv(interactions, '{output_csv}', row.names = TRUE) + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"spacetrooper::get_interactions(threshold={prob_threshold})", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [output_csv] + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to compute interactions", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def spacetrooper_check_convergence( + results_path: str, + output_plot: str +) -> Dict[str, Any]: + """ + Generate diagnostic plots to check MCMC convergence (trace plots). + + Args: + results_path: Path to the spacetrooper results RDS file. + output_plot: Path to save the diagnostic plot. + """ + res_file = Path(results_path) + if not res_file.exists(): + raise FileNotFoundError(f"Results file not found: {results_path}") + + r_script = f""" + library(spacetrooper) + library(ggplot2) + res <- readRDS('{results_path}') + p <- plot_convergence(res) + ggsave('{output_plot}', plot = p, width = 12, height = 10) + """ + + try: + process = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "spacetrooper::plot_convergence()", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [output_plot] + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to generate convergence plots", + "stdout": e.stdout, + "stderr": e.stderr + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spacetrooper/app/bioconductor-spacetrooper_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spacetrooper/app/bioconductor-spacetrooper_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..edf6a3989b086c31d518385db01a49efa15ae8e1 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spacetrooper/app/bioconductor-spacetrooper_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spacetrooper/app/bioconductor-spacetrooper_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_spacetrooper' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spacetrooper/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spacetrooper/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spacetrooper/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spacetrooper/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spacetrooper/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e520262603580702d9ded9e960c50dc9955e9c81 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spacetrooper/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-spacetrooper: + build: . + image: mcp-bioconductor-spacetrooper:latest + container_name: mcp-bioconductor-spacetrooper + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-spacetrooper + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spacetrooper/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spacetrooper/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d13143d2e6f39fd174a35176490a38513e71b479 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spacetrooper/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-spacetrooper + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spacetrooper/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spacetrooper/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spacetrooper/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialdmelxsim/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialdmelxsim/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9b5f92c5899e14a5efb0406a0c032c420dbe7183 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialdmelxsim/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-spatialdmelxsim via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-spatialdmelxsim -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-spatialdmelxsim_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-spatialdmelxsim_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-spatialdmelxsim_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialdmelxsim/app/__pycache__/bioconductor-spatialdmelxsim_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialdmelxsim/app/__pycache__/bioconductor-spatialdmelxsim_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7e106323cd2f31a84df7e5dcc643dfa1fe89a9ae Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialdmelxsim/app/__pycache__/bioconductor-spatialdmelxsim_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialdmelxsim/app/bioconductor-spatialdmelxsim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialdmelxsim/app/bioconductor-spatialdmelxsim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c2a20efc41b3e550e1cda60e0118ff251fe888b6 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialdmelxsim/app/bioconductor-spatialdmelxsim_server.py @@ -0,0 +1,214 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any +import tempfile + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_spatialdmelxsim' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def fetch_spatial_dmelxsim_rds( + output_path: str, +) -> Dict[str, Any]: + """ + Downloads the spatialDmelxsim dataset and saves it as an R RDS file. + + The dataset contains spatial allelic expression counts from Combs & Fraser (2018) + for a Drosophila melanogaster x Drosophila simulans cross embryo, + stored as a SummarizedExperiment object. + + Args: + output_path: The file path where the RDS file should be saved (e.g., 'data.rds'). + """ + output_file = Path(output_path) + + # Ensure the directory exists + output_file.parent.mkdir(parents=True, exist_ok=True) + + r_script = f""" + suppressPackageStartupMessages(library(spatialDmelxsim)) + suppressPackageStartupMessages(library(SummarizedExperiment)) + + # Load the dataset + se <- spatialDmelxsim() + + # Save to RDS + saveRDS(se, file = "{str(output_file)}") + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e '...'", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file.absolute())] + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to fetch spatialDmelxsim data", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd + } + +@mcp.tool() +def export_spatial_dmelxsim_to_csv( + output_directory: str, +) -> Dict[str, Any]: + """ + Exports the spatialDmelxsim dataset components (counts, colData, rowData) to CSV files. + + This is useful for analyzing the spatial transcriptomics data in tools outside of R. + It generates: + - counts.csv: Allelic expression counts. + - metadata.csv: Sample/slice metadata (colData). + - features.csv: Gene/feature metadata (rowData). + + Args: + output_directory: The directory where the CSV files will be saved. + """ + out_dir = Path(output_directory) + out_dir.mkdir(parents=True, exist_ok=True) + + counts_path = out_dir / "counts.csv" + metadata_path = out_dir / "metadata.csv" + features_path = out_dir / "features.csv" + + r_script = f""" + suppressPackageStartupMessages(library(spatialDmelxsim)) + suppressPackageStartupMessages(library(SummarizedExperiment)) + + se <- spatialDmelxsim() + + # Export Assay (Counts) + write.csv(as.matrix(assay(se)), file = "{str(counts_path)}") + + # Export colData (Metadata) + write.csv(as.data.frame(colData(se)), file = "{str(metadata_path)}") + + # Export rowData (Features) + write.csv(as.data.frame(rowData(se)), file = "{str(features_path)}") + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "Rscript -e '...'", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [ + str(counts_path.absolute()), + str(metadata_path.absolute()), + str(features_path.absolute()) + ] + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to export spatialDmelxsim to CSV", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd + } + +@mcp.tool() +def get_spatial_dmelxsim_summary() -> Dict[str, Any]: + """ + Retrieves a summary of the spatialDmelxsim dataset without saving files. + + Returns information about the number of genes, number of spatial slices, + available assays, and metadata columns. + """ + r_script = """ + suppressPackageStartupMessages(library(spatialDmelxsim)) + suppressPackageStartupMessages(library(SummarizedExperiment)) + + se <- spatialDmelxsim() + + cat("--- Dataset Summary ---\\n") + cat("Dimensions (Genes x Slices):", paste(dim(se), collapse = " x "), "\\n") + cat("Assay Names:", paste(assayNames(se), collapse = ", "), "\\n") + cat("Metadata Columns (colData):", paste(colnames(colData(se)), collapse = ", "), "\\n") + cat("Feature Columns (rowData):", paste(colnames(rowData(se)), collapse = ", "), "\\n") + cat("--- Sample Metadata Preview ---\\n") + print(head(colData(se))) + """ + + 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 retrieve spatialDmelxsim summary", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd + } + +@mcp.tool() +def run_custom_spatial_dmelxsim_query( + r_expression: str, +) -> Dict[str, Any]: + """ + Executes a custom R expression on the spatialDmelxsim SummarizedExperiment object. + + The object is available in the R environment as 'se'. + Example: 'mean(assay(se))' or 'table(se$slice)' + + Args: + r_expression: The R code to execute. + """ + # Basic validation to prevent empty strings + if not r_expression.strip(): + return {"error": "R expression cannot be empty"} + + r_script = f""" + suppressPackageStartupMessages(library(spatialDmelxsim)) + suppressPackageStartupMessages(library(SummarizedExperiment)) + se <- spatialDmelxsim() + print({r_expression}) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e '... print({r_expression})'", + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to execute custom R query", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialdmelxsim/app/bioconductor-spatialdmelxsim_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialdmelxsim/app/bioconductor-spatialdmelxsim_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..49c562addefcb3cfebb70c7f2e3916a773a5efdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialdmelxsim/app/bioconductor-spatialdmelxsim_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spatialdmelxsim/app/bioconductor-spatialdmelxsim_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_spatialdmelxsim' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialdmelxsim/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialdmelxsim/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialdmelxsim/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialdmelxsim/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialdmelxsim/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d9e30f4a85ea53174eda1cb5623e5f99057e4800 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialdmelxsim/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-spatialdmelxsim: + build: . + image: mcp-bioconductor-spatialdmelxsim:latest + container_name: mcp-bioconductor-spatialdmelxsim + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-spatialdmelxsim + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialdmelxsim/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialdmelxsim/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d4b636ae9e789d2935364f58b54bb9e2810bf177 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialdmelxsim/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-spatialdmelxsim + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialdmelxsim/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialdmelxsim/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialdmelxsim/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialexperimentio/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialexperimentio/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..98cc94cca9af084a6cb227c60ff769c5af2d6ea8 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialexperimentio/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-spatialexperimentio via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-spatialexperimentio -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-spatialexperimentio_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-spatialexperimentio_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-spatialexperimentio_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialexperimentio/app/__pycache__/bioconductor-spatialexperimentio_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialexperimentio/app/__pycache__/bioconductor-spatialexperimentio_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..96c623ad7122148a4fe7b60409cccd4a4d632985 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialexperimentio/app/__pycache__/bioconductor-spatialexperimentio_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialexperimentio/app/bioconductor-spatialexperimentio_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialexperimentio/app/bioconductor-spatialexperimentio_server.py new file mode 100644 index 0000000000000000000000000000000000000000..446babb44f912ee6de43543c0d22505e4c2ef85a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialexperimentio/app/bioconductor-spatialexperimentio_server.py @@ -0,0 +1,346 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Dict, List, Literal, Optional + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided by the MCP framework. +def tool(func): + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + return wrapper + +mcp = type("mcp", (), {"tool": tool}) + + +@mcp.tool +def read_xenium( + xenium_dir: Path, + output_rds_path: Path, + type: Literal["spe", "sce"] = "spe", + z_option: str = "3D", + mols_as_assay: bool = False, + add_molecules: bool = True, +) -> Dict: + """ + Reads 10X Genomics Xenium data and creates a SpatialExperiment or SingleCellExperiment object. + + Args: + xenium_dir: Path to the Xenium output directory. + output_rds_path: Path to save the output RDS file. + type: Type of object to return, either 'spe' (SpatialExperiment) or 'sce' (SingleCellExperiment). + z_option: How to handle z-planes. Can be '3D' (default), 'split', or an integer specifying a z-plane. + mols_as_assay: Whether to store molecules as an assay. + add_molecules: Whether to add molecules to rowData. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output RDS file. + """ + # Input validation + if not xenium_dir.is_dir(): + raise ValueError(f"Input directory not found: {xenium_dir}") + if type not in ["spe", "sce"]: + raise ValueError("`type` must be either 'spe' or 'sce'.") + + # Validate z_option: must be '3D', 'split', or a valid integer string + is_valid_z_option = z_option in ["3D", "split"] or z_option.isdigit() + if not is_valid_z_option: + raise ValueError("`z_option` must be '3D', 'split', or an integer string.") + + # Format z_option for R script: strings need quotes, integers do not + z_option_r = f"'{z_option}'" if z_option in ["3D", "split"] else z_option + + # Format booleans for R + mols_as_assay_r = str(mols_as_assay).upper() + add_molecules_r = str(add_molecules).upper() + + r_script_content = f""" + library(SpatialExperimentIO) + + message("Reading Xenium data from: {xenium_dir}") + spe_object <- readXenium( + xenium_dir = "{xenium_dir}", + type = "{type}", + z_option = {z_option_r}, + mols_as_assay = {mols_as_assay_r}, + add_molecules = {add_molecules_r} + ) + + message("Saving object to: {output_rds_path}") + saveRDS(spe_object, file = "{output_rds_path}") + message("Done.") + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_r_script: + tmp_r_script.write(r_script_content) + script_path = tmp_r_script.name + + cmd = ["Rscript", script_path] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + # Clean up the temporary script file + Path(script_path).unlink() + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_rds_path)], + } + except subprocess.CalledProcessError as e: + # Clean up the temporary script file even on error + Path(script_path).unlink() + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode, + } + + +@mcp.tool +def read_cosmx( + cosmx_dir: Path, + output_rds_path: Path, + type: Literal["spe", "sce"] = "spe", + z_option: str = "3D", + mols_as_assay: bool = False, + add_molecules: bool = True, +) -> Dict: + """ + Reads Nanostring CosMx data and creates a SpatialExperiment or SingleCellExperiment object. + + Args: + cosmx_dir: Path to the CosMx output directory. + output_rds_path: Path to save the output RDS file. + type: Type of object to return, either 'spe' (SpatialExperiment) or 'sce' (SingleCellExperiment). + z_option: How to handle z-planes. Can be '3D' (default), 'split', or an integer specifying a z-plane. + mols_as_assay: Whether to store molecules as an assay. + add_molecules: Whether to add molecules to rowData. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output RDS file. + """ + # Input validation + if not cosmx_dir.is_dir(): + raise ValueError(f"Input directory not found: {cosmx_dir}") + if type not in ["spe", "sce"]: + raise ValueError("`type` must be either 'spe' or 'sce'.") + + is_valid_z_option = z_option in ["3D", "split"] or z_option.isdigit() + if not is_valid_z_option: + raise ValueError("`z_option` must be '3D', 'split', or an integer string.") + + z_option_r = f"'{z_option}'" if z_option in ["3D", "split"] else z_option + mols_as_assay_r = str(mols_as_assay).upper() + add_molecules_r = str(add_molecules).upper() + + r_script_content = f""" + library(SpatialExperimentIO) + + message("Reading CosMx data from: {cosmx_dir}") + spe_object <- readCosMx( + cosmx_dir = "{cosmx_dir}", + type = "{type}", + z_option = {z_option_r}, + mols_as_assay = {mols_as_assay_r}, + add_molecules = {add_molecules_r} + ) + + message("Saving object to: {output_rds_path}") + saveRDS(spe_object, file = "{output_rds_path}") + message("Done.") + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_r_script: + tmp_r_script.write(r_script_content) + script_path = tmp_r_script.name + + cmd = ["Rscript", script_path] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + Path(script_path).unlink() + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_rds_path)], + } + except subprocess.CalledProcessError as e: + Path(script_path).unlink() + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode, + } + + +@mcp.tool +def read_merscope( + merscope_dir: Path, + output_rds_path: Path, + type: Literal["spe", "sce"] = "spe", + z_option: str = "3D", + mols_as_assay: bool = False, + add_molecules: bool = True, +) -> Dict: + """ + Reads Vizgen MERSCOPE data and creates a SpatialExperiment or SingleCellExperiment object. + + Args: + merscope_dir: Path to the MERSCOPE output directory. + output_rds_path: Path to save the output RDS file. + type: Type of object to return, either 'spe' (SpatialExperiment) or 'sce' (SingleCellExperiment). + z_option: How to handle z-planes. Can be '3D' (default), 'split', or an integer specifying a z-plane. + mols_as_assay: Whether to store molecules as an assay. + add_molecules: Whether to add molecules to rowData. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output RDS file. + """ + # Input validation + if not merscope_dir.is_dir(): + raise ValueError(f"Input directory not found: {merscope_dir}") + if type not in ["spe", "sce"]: + raise ValueError("`type` must be either 'spe' or 'sce'.") + + is_valid_z_option = z_option in ["3D", "split"] or z_option.isdigit() + if not is_valid_z_option: + raise ValueError("`z_option` must be '3D', 'split', or an integer string.") + + z_option_r = f"'{z_option}'" if z_option in ["3D", "split"] else z_option + mols_as_assay_r = str(mols_as_assay).upper() + add_molecules_r = str(add_molecules).upper() + + r_script_content = f""" + library(SpatialExperimentIO) + + message("Reading MERSCOPE data from: {merscope_dir}") + spe_object <- readMerscope( + merscope_dir = "{merscope_dir}", + type = "{type}", + z_option = {z_option_r}, + mols_as_assay = {mols_as_assay_r}, + add_molecules = {add_molecules_r} + ) + + message("Saving object to: {output_rds_path}") + saveRDS(spe_object, file = "{output_rds_path}") + message("Done.") + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_r_script: + tmp_r_script.write(r_script_content) + script_path = tmp_r_script.name + + cmd = ["Rscript", script_path] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + Path(script_path).unlink() + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_rds_path)], + } + except subprocess.CalledProcessError as e: + Path(script_path).unlink() + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode, + } + + +@mcp.tool +def read_starmap_plus( + starmap_dir: Path, + output_rds_path: Path, + type: Literal["spe", "sce"] = "spe", +) -> Dict: + """ + Reads Broad Institute STARmapPLUS data and creates a SpatialExperiment or SingleCellExperiment object. + + Args: + starmap_dir: Path to the STARmapPLUS output directory. + output_rds_path: Path to save the output RDS file. + type: Type of object to return, either 'spe' (SpatialExperiment) or 'sce' (SingleCellExperiment). + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the output RDS file. + """ + # Input validation + if not starmap_dir.is_dir(): + raise ValueError(f"Input directory not found: {starmap_dir}") + if type not in ["spe", "sce"]: + raise ValueError("`type` must be either 'spe' or 'sce'.") + + r_script_content = f""" + library(SpatialExperimentIO) + + message("Reading STARmapPLUS data from: {starmap_dir}") + spe_object <- readStarmapPLUS( + starmap_dir = "{starmap_dir}", + type = "{type}" + ) + + message("Saving object to: {output_rds_path}") + saveRDS(spe_object, file = "{output_rds_path}") + message("Done.") + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_r_script: + tmp_r_script.write(r_script_content) + script_path = tmp_r_script.name + + cmd = ["Rscript", script_path] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + Path(script_path).unlink() + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_rds_path)], + } + except subprocess.CalledProcessError as e: + Path(script_path).unlink() + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode, + } \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialexperimentio/app/bioconductor-spatialexperimentio_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialexperimentio/app/bioconductor-spatialexperimentio_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0c79a337cd655c674f728a3574f90a3919b8220d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialexperimentio/app/bioconductor-spatialexperimentio_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spatialexperimentio/app/bioconductor-spatialexperimentio_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_spatialexperimentio' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialexperimentio/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialexperimentio/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialexperimentio/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialexperimentio/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialexperimentio/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..746a09393525cfddf784759fbf929e2e2b937ce5 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialexperimentio/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-spatialexperimentio: + build: . + image: mcp-bioconductor-spatialexperimentio:latest + container_name: mcp-bioconductor-spatialexperimentio + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-spatialexperimentio + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialexperimentio/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialexperimentio/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..022e4233e0946773a6bb568d4611dd4fcbd6a10e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialexperimentio/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-spatialexperimentio + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialexperimentio/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialexperimentio/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spatialexperimentio/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spotsweeper/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spotsweeper/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e782bd83642892e2d7253881f0e837fe8b06828d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spotsweeper/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-spotsweeper via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-spotsweeper -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-spotsweeper_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-spotsweeper_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-spotsweeper_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spotsweeper/app/__pycache__/bioconductor-spotsweeper_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spotsweeper/app/__pycache__/bioconductor-spotsweeper_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..765ce5c81c82f239c3786034eea7982741fc38fb Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spotsweeper/app/__pycache__/bioconductor-spotsweeper_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spotsweeper/app/bioconductor-spotsweeper_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spotsweeper/app/bioconductor-spotsweeper_server.py new file mode 100644 index 0000000000000000000000000000000000000000..01aea87502f0f31157258a767336c8efeedb05f6 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spotsweeper/app/bioconductor-spotsweeper_server.py @@ -0,0 +1,316 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any +import logging + +# Configure logging +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +log = logging.getLogger(__name__) + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_spotsweeper' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def local_outliers( + spe_input_rds: str, + spe_output_rds: str, + metrics: List[str], + direction: str = "both", + k: int = 36, + l: float = 0.5, + log_transform: bool = True, + n_workers: int = 1, +) -> Dict[str, Any]: + """ + Identifies outlier spots based on local distributions of QC metrics using the localOutliers function. + + Args: + spe_input_rds: Path to the input SpatialExperiment object in RDS format. + spe_output_rds: Path to save the output SpatialExperiment object. + metrics: List of QC metrics columns in colData to use (e.g., ["sum", "detected"]). + direction: Direction of outlier detection ("higher", "lower", or "both"). + k: Number of nearest neighbors to use for local distribution. + l: The number of standard deviations to use as a threshold (default 0.5). + log_transform: Whether to log-transform the metrics before analysis. + n_workers: Number of cores for parallel processing. + """ + # Input validation + input_path = Path(spe_input_rds) + output_path = Path(spe_output_rds) + if not input_path.is_file(): + raise FileNotFoundError(f"Input file not found: {spe_input_rds}") + if direction not in ["higher", "lower", "both"]: + raise ValueError("direction must be 'higher', 'lower', or 'both'") + if k <= 0: + raise ValueError("k must be a positive integer") + if n_workers <= 0: + raise ValueError("n_workers must be a positive integer") + if not metrics: + raise ValueError("metrics list cannot be empty") + + output_path.parent.mkdir(parents=True, exist_ok=True) + + # Prepare R-compatible strings + metrics_formatted = ", ".join([f'"{m}"' for m in metrics]) + r_metrics = f"c({metrics_formatted})" + r_log = "TRUE" if log_transform else "FALSE" + + with tempfile.TemporaryDirectory() as temp_dir: + r_script_path = Path(temp_dir) / "run_local_outliers.R" + + r_script_content = f""" + library(SpotSweeper) + library(SpatialExperiment) + library(BiocParallel) + + if (.Platform$OS.type == "windows") {{ + bpparam <- SnowParam(workers = {n_workers}) + }} else {{ + bpparam <- MulticoreParam(workers = {n_workers}) + }} + + spe <- readRDS("{input_path.resolve().as_posix()}") + metrics_to_run <- {r_metrics} + + for (m in metrics_to_run) {{ + message(paste("Processing metric:", m)) + spe <- localOutliers( + spe, + metric = m, + direction = "{direction}", + k = {k}, + l = {l}, + log = {r_log}, + BPPARAM = bpparam + ) + }} + + saveRDS(spe, file = "{output_path.resolve().as_posix()}") + """ + + with open(r_script_path, "w") as f: + f.write(r_script_content) + + try: + result = subprocess.run(["Rscript", str(r_script_path)], capture_output=True, text=True, check=True) + return { + "command_executed": f"localOutliers on {metrics}", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stdout": e.stdout, "stderr": e.stderr} + + +@mcp.tool() +def find_artifacts( + spe_input_rds: str, + spe_output_rds: str, + metrics: List[str], + direction: str = "both", + k: int = 36, + n_rings: int = 5, + log_transform: bool = True, + n_workers: int = 1, +) -> Dict[str, Any]: + """ + Identifies technical artifacts (large clusters of outliers) using the findArtifacts function. + + Args: + spe_input_rds: Path to the input SpatialExperiment object. + spe_output_rds: Path to save the output SpatialExperiment object. + metrics: List of QC metrics columns in colData to use. + direction: Direction of outlier detection ("higher", "lower", or "both"). + k: Number of nearest neighbors. + n_rings: Number of rings of neighbors to consider for artifact detection. + log_transform: Whether to log-transform the metrics. + n_workers: Number of cores for parallel processing. + """ + input_path = Path(spe_input_rds) + output_path = Path(spe_output_rds) + if not input_path.is_file(): + raise FileNotFoundError(f"Input file not found: {spe_input_rds}") + if n_rings <= 0: + raise ValueError("n_rings must be a positive integer") + + output_path.parent.mkdir(parents=True, exist_ok=True) + + metrics_formatted = ", ".join([f'"{m}"' for m in metrics]) + r_metrics = f"c({metrics_formatted})" + r_log = "TRUE" if log_transform else "FALSE" + + with tempfile.TemporaryDirectory() as temp_dir: + r_script_path = Path(temp_dir) / "run_find_artifacts.R" + + r_script_content = f""" + library(SpotSweeper) + library(SpatialExperiment) + library(BiocParallel) + + if (.Platform$OS.type == "windows") {{ + bpparam <- SnowParam(workers = {n_workers}) + }} else {{ + bpparam <- MulticoreParam(workers = {n_workers}) + }} + + spe <- readRDS("{input_path.resolve().as_posix()}") + metrics_to_run <- {r_metrics} + + for (m in metrics_to_run) {{ + message(paste("Processing metric for artifacts:", m)) + spe <- findArtifacts( + spe, + metric = m, + direction = "{direction}", + k = {k}, + n_rings = {n_rings}, + log = {r_log}, + BPPARAM = bpparam + ) + }} + + saveRDS(spe, file = "{output_path.resolve().as_posix()}") + """ + + with open(r_script_path, "w") as f: + f.write(r_script_content) + + try: + result = subprocess.run(["Rscript", str(r_script_path)], capture_output=True, text=True, check=True) + return { + "command_executed": f"findArtifacts on {metrics}", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stdout": e.stdout, "stderr": e.stderr} + + +@mcp.tool() +def plot_qc( + spe_input_rds: str, + output_image_path: str, + metric: str, + annotate: Optional[str] = None, + palette: Optional[str] = None, + size: float = 1.0, + sample_id: Optional[str] = None, +) -> Dict[str, Any]: + """ + Generates spatial quality control plots using the plotQC function. + + Args: + spe_input_rds: Path to the input SpatialExperiment object. + output_image_path: Path to save the plot (e.g., plot.png or plot.pdf). + metric: The name of the column in colData to visualize. + annotate: Optional column name to use for highlighting specific spots (e.g., outliers). + palette: Optional color palette name or vector. + size: Point size for the spatial plot. + sample_id: Optional sample identifier if multiple samples exist in the object. + """ + input_path = Path(spe_input_rds) + output_path = Path(output_image_path) + if not input_path.is_file(): + raise FileNotFoundError(f"Input file not found: {spe_input_rds}") + + output_path.parent.mkdir(parents=True, exist_ok=True) + + r_annotate = f'"{annotate}"' if annotate else "NULL" + r_palette = f'"{palette}"' if palette else "NULL" + r_sample_id = f'"{sample_id}"' if sample_id else "NULL" + + with tempfile.TemporaryDirectory() as temp_dir: + r_script_path = Path(temp_dir) / "run_plot_qc.R" + + r_script_content = f""" + library(SpotSweeper) + library(SpatialExperiment) + library(ggplot2) + + spe <- readRDS("{input_path.resolve().as_posix()}") + + p <- plotQC( + spe, + metric = "{metric}", + annotate = {r_annotate}, + palette = {r_palette}, + size = {size}, + sample_id = {r_sample_id} + ) + + ggsave("{output_path.resolve().as_posix()}", plot = p, width = 8, height = 7) + """ + + with open(r_script_path, "w") as f: + f.write(r_script_content) + + try: + result = subprocess.run(["Rscript", str(r_script_path)], capture_output=True, text=True, check=True) + return { + "command_executed": f"plotQC for {metric}", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stdout": e.stdout, "stderr": e.stderr} + + +@mcp.tool() +def dist_to_nearest( + spe_input_rds: str, + spe_output_rds: str, + k: int = 100, +) -> Dict[str, Any]: + """ + Calculates the distance to the kth nearest neighbor for each spot. + Useful for identifying edge spots or density variations. + + Args: + spe_input_rds: Path to the input SpatialExperiment object. + spe_output_rds: Path to save the output SpatialExperiment object. + k: The neighbor index to calculate distance to. + """ + input_path = Path(spe_input_rds) + output_path = Path(spe_output_rds) + if not input_path.is_file(): + raise FileNotFoundError(f"Input file not found: {spe_input_rds}") + if k <= 0: + raise ValueError("k must be a positive integer") + + output_path.parent.mkdir(parents=True, exist_ok=True) + + with tempfile.TemporaryDirectory() as temp_dir: + r_script_path = Path(temp_dir) / "run_dist_to_nearest.R" + + r_script_content = f""" + library(SpotSweeper) + library(SpatialExperiment) + + spe <- readRDS("{input_path.resolve().as_posix()}") + spe <- distToNearest(spe, k = {k}) + + saveRDS(spe, file = "{output_path.resolve().as_posix()}") + """ + + with open(r_script_path, "w") as f: + f.write(r_script_content) + + try: + result = subprocess.run(["Rscript", str(r_script_path)], capture_output=True, text=True, check=True) + return { + "command_executed": f"distToNearest with k={k}", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stdout": e.stdout, "stderr": e.stderr} + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spotsweeper/app/bioconductor-spotsweeper_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spotsweeper/app/bioconductor-spotsweeper_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f5a93c2485e945ea3120c6a297d39676dd984388 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spotsweeper/app/bioconductor-spotsweeper_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-spotsweeper/app/bioconductor-spotsweeper_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_spotsweeper' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spotsweeper/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spotsweeper/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spotsweeper/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spotsweeper/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spotsweeper/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..02f67e1fc0d1995d710035d99d01ae7f62b868ec --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spotsweeper/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-spotsweeper: + build: . + image: mcp-bioconductor-spotsweeper:latest + container_name: mcp-bioconductor-spotsweeper + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-spotsweeper + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spotsweeper/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spotsweeper/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d0a0748510b4e88c86a3264657f8d217494c538b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spotsweeper/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-spotsweeper + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spotsweeper/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spotsweeper/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-spotsweeper/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-stjoincount/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-stjoincount/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e7982812c75379d65d8fc0cab45bc528f424f309 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-stjoincount/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-stjoincount via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-stjoincount -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-stjoincount_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-stjoincount_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-stjoincount_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-stjoincount/app/__pycache__/bioconductor-stjoincount_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-stjoincount/app/__pycache__/bioconductor-stjoincount_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16f28d9ab518a0719b70596a41d15a771786499a Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-stjoincount/app/__pycache__/bioconductor-stjoincount_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-stjoincount/app/bioconductor-stjoincount_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-stjoincount/app/bioconductor-stjoincount_server.py new file mode 100644 index 0000000000000000000000000000000000000000..74f9ac140fc78a08c0be026f52d03355cddfc08f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-stjoincount/app/bioconductor-stjoincount_server.py @@ -0,0 +1,444 @@ +import subprocess +import tempfile +import shutil +from pathlib import Path +from typing import Optional, List, Literal + +# Assume mcp.tool is imported from a framework library +class mcp: + def tool(func): + return func + +def _check_rscript(): + """Checks if Rscript is available in the system's PATH.""" + if not shutil.which("Rscript"): + raise RuntimeError( + "Rscript not found in PATH. Please install R and ensure it is accessible." + ) + +def _run_r_script(script_content: str, output_dir: Path): + """ + Creates and executes a temporary R script. + + Args: + script_content: A string containing the R code to execute. + output_dir: The directory where the script will be run. + + Returns: + A dictionary containing the command executed, stdout, and stderr. + """ + _check_rscript() + r_script_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", delete=False, suffix=".R", dir=output_dir + ) as r_script_file: + r_script_file.write(script_content) + r_script_path = r_script_file.name + + cmd = ["Rscript", r_script_path] + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + cwd=output_dir, + ) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + } + except subprocess.CalledProcessError as e: + error_message = ( + f"R script execution failed with exit code {e.returncode}.\n" + f"Command: {' '.join(e.cmd)}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) + raise RuntimeError(error_message) from e + finally: + if r_script_path and Path(r_script_path).exists(): + Path(r_script_path).unlink() + + +@mcp.tool +def stjoincount_find_colocalized_genes( + spe_rds: Path, + col_graph_name: str, + sample_id: str, + gene_names: List[str], + output_summary_csv: Path, + p_adj_method: Literal[ + "holm", "hochberg", "hommel", "bonferroni", "BH", "BY", "fdr", "none" + ] = "BH", + p_adj_threshold: float = 0.05, + min_sub_spots: int = 10, + min_gene_spots: int = 10, + min_jaccard: float = 0.0, + return_details: bool = False, + output_details_csv: Optional[Path] = None, +): + """ + Finds colocalized gene pairs using the stJoincount package. + + This tool wraps the find_colocalized_genes function from the R/Bioconductor + package stJoincount. It identifies pairs of genes that are expressed in + spatially adjacent spots more often than expected by chance. + + Requires an R installation with the 'stJoincount', 'SpatialExperiment', + and 'SingleCellExperiment' packages installed. + """ + # Input validation + if not spe_rds.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {spe_rds}") + if not (0.0 <= p_adj_threshold <= 1.0): + raise ValueError("p_adj_threshold must be between 0 and 1.") + if min_sub_spots < 1: + raise ValueError("min_sub_spots must be a positive integer.") + if min_gene_spots < 1: + raise ValueError("min_gene_spots must be a positive integer.") + if not (0.0 <= min_jaccard <= 1.0): + raise ValueError("min_jaccard must be between 0 and 1.") + if not gene_names: + raise ValueError("gene_names list cannot be empty.") + if return_details and output_details_csv is None: + raise ValueError("output_details_csv must be provided when return_details is True.") + + output_dir = output_summary_csv.parent + output_dir.mkdir(parents=True, exist_ok=True) + + r_gene_vector = "c(" + ", ".join(f'"{g}"' for g in gene_names) + ")" + + r_script = f""" + options(warn = -1) + if (!requireNamespace("stJoincount", quietly = TRUE)) {{ + stop("Package 'stJoincount' is not installed. Please install it from Bioconductor.") + }} + library(stJoincount) + library(SpatialExperiment) + library(SingleCellExperiment) + + spe <- readRDS("{spe_rds.resolve()}") + + results <- find_colocalized_genes( + spe = spe, + colGraphName = "{col_graph_name}", + sample_id = "{sample_id}", + gene_names = {r_gene_vector}, + p_adj_method = "{p_adj_method}", + p_adj_threshold = {p_adj_threshold}, + min_sub_spots = {min_sub_spots}, + min_gene_spots = {min_gene_spots}, + min_jaccard = {min_jaccard}, + return_details = {'TRUE' if return_details else 'FALSE'} + ) + + if ({'TRUE' if return_details else 'FALSE'}) {{ + write.csv(results$summary, file = "{output_summary_csv.resolve()}", row.names = FALSE) + write.csv(results$details, file = "{str(output_details_csv.resolve())}", row.names = FALSE) + }} else {{ + write.csv(results, file = "{output_summary_csv.resolve()}", row.names = FALSE) + }} + + cat("Analysis complete. Results saved.\\n") + """ + + exec_result = _run_r_script(r_script, output_dir) + + output_files = {"summary_csv": str(output_summary_csv.resolve())} + if return_details and output_details_csv: + output_files["details_csv"] = str(output_details_csv.resolve()) + + return { + "command_executed": exec_result["command_executed"], + "stdout": exec_result["stdout"], + "stderr": exec_result["stderr"], + "output_files": output_files, + } + + +@mcp.tool +def stjoincount_moran_mc( + input_file: Path, + coords_cols: str, + variable_col: str, + output_csv: Path, + graph_method: Literal["knn", "distance"], + graph_param_k: Optional[int] = None, + graph_param_dist: Optional[float] = None, + nsim: int = 499, + alternative: Literal["greater", "less", "two.sided"] = "greater", +): + """ + Performs Moran's I test for spatial autocorrelation. + + This tool wraps the moran.mc function from the R/spdep package. It assesses + whether the pattern of a continuous variable is clustered, dispersed, or random. + + Requires an R installation with the 'spdep' and 'readr' packages installed. + """ + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if nsim <= 0: + raise ValueError("nsim must be a positive integer.") + + coord_names = [c.strip() for c in coords_cols.split(',')] + if len(coord_names) != 2: + raise ValueError("coords_cols must be a comma-separated string of two column names.") + + if graph_method == "knn": + if graph_param_k is None or graph_param_k <= 0: + raise ValueError("graph_param_k must be a positive integer for knn method.") + elif graph_method == "distance": + if graph_param_dist is None or graph_param_dist <= 0: + raise ValueError("graph_param_dist must be a positive float for distance method.") + else: + raise ValueError(f"Unknown graph_method: {graph_method}") + + output_dir = output_csv.parent + output_dir.mkdir(parents=True, exist_ok=True) + + r_script = f""" + options(warn = -1) + if (!requireNamespace("spdep", quietly = TRUE)) {{ + stop("Package 'spdep' is not installed.") + }} + if (!requireNamespace("readr", quietly = TRUE)) {{ + stop("Package 'readr' is not installed.") + }} + library(spdep) + library(readr) + + data <- read_csv("{input_file.resolve()}", show_col_types = FALSE) + + required_cols <- c("{coord_names[0]}", "{coord_names[1]}", "{variable_col}") + if (!all(required_cols %in% colnames(data))) {{ + stop("One or more required columns not found in the input file.") + }} + + coords <- as.matrix(data[, c("{coord_names[0]}", "{coord_names[1]}")]) + x <- data[["{variable_col}"]] + + if ("{graph_method}" == "knn") {{ + nb <- knn2nb(knearneigh(coords, k = {graph_param_k})) + }} else if ("{graph_method}" == "distance") {{ + nb <- dnearneigh(coords, d1 = 0, d2 = {graph_param_dist}) + }} + + lw <- nb2listw(nb, style = "W", zero.policy = TRUE) + + set.seed(123) + result <- moran.mc( + x = x, listw = lw, nsim = {nsim}, alternative = "{alternative}", zero.policy = TRUE + ) + + result_df <- data.frame( + statistic = result$statistic, p.value = result$p.value, + method = result$method, alternative = result$alternative, nsim = {nsim} + ) + write.csv(result_df, file = "{output_csv.resolve()}", row.names = FALSE) + + cat("Moran's I test complete. Results saved.\\n") + """ + + exec_result = _run_r_script(r_script, output_dir) + + return { + "command_executed": exec_result["command_executed"], + "stdout": exec_result["stdout"], + "stderr": exec_result["stderr"], + "output_files": {"results_csv": str(output_csv.resolve())}, + } + + +@mcp.tool +def stjoincount_joincount_mc( + input_file: Path, + coords_cols: str, + variable_col: str, + output_csv: Path, + graph_method: Literal["knn", "distance"], + binarize_threshold: float, + graph_param_k: Optional[int] = None, + graph_param_dist: Optional[float] = None, + nsim: int = 499, + alternative: Literal["greater", "less", "two.sided"] = "greater", +): + """ + Performs a global join count test for spatial autocorrelation for binary data. + + This tool wraps the joincount.mc function from the R/spdep package. It tests + if adjacent locations have the same binary value more than expected by chance. + + Requires an R installation with the 'spdep' and 'readr' packages installed. + """ + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if nsim <= 0: + raise ValueError("nsim must be a positive integer.") + + coord_names = [c.strip() for c in coords_cols.split(',')] + if len(coord_names) != 2: + raise ValueError("coords_cols must be a comma-separated string of two column names.") + + if graph_method == "knn": + if graph_param_k is None or graph_param_k <= 0: + raise ValueError("graph_param_k must be a positive integer for knn method.") + elif graph_method == "distance": + if graph_param_dist is None or graph_param_dist <= 0: + raise ValueError("graph_param_dist must be a positive float for distance method.") + else: + raise ValueError(f"Unknown graph_method: {graph_method}") + + output_dir = output_csv.parent + output_dir.mkdir(parents=True, exist_ok=True) + + r_script = f""" + options(warn = -1) + if (!requireNamespace("spdep", quietly = TRUE)) {{ + stop("Package 'spdep' is not installed.") + }} + if (!requireNamespace("readr", quietly = TRUE)) {{ + stop("Package 'readr' is not installed.") + }} + library(spdep) + library(readr) + + data <- read_csv("{input_file.resolve()}", show_col_types = FALSE) + + required_cols <- c("{coord_names[0]}", "{coord_names[1]}", "{variable_col}") + if (!all(required_cols %in% colnames(data))) {{ + stop("One or more required columns not found in the input file.") + }} + + coords <- as.matrix(data[, c("{coord_names[0]}", "{coord_names[1]}")]) + x_binary <- as.factor(ifelse(data[["{variable_col}"]] > {binarize_threshold}, 1, 0)) + + if ("{graph_method}" == "knn") {{ + nb <- knn2nb(knearneigh(coords, k = {graph_param_k})) + }} else if ("{graph_method}" == "distance") {{ + nb <- dnearneigh(coords, d1 = 0, d2 = {graph_param_dist}) + }} + + lw <- nb2listw(nb, style = "B", zero.policy = TRUE) + + set.seed(123) + result <- joincount.mc( + fx = x_binary, listw = lw, nsim = {nsim}, alternative = "{alternative}", zero.policy = TRUE + ) + + result_1 <- result[[2]] + result_df <- data.frame( + statistic = result_1$statistic, p.value = result_1$p.value, + method = result_1$method, alternative = result_1$alternative, nsim = {nsim} + ) + write.csv(result_df, file = "{output_csv.resolve()}", row.names = FALSE) + + cat("Join Count test complete. Results saved.\\n") + """ + + exec_result = _run_r_script(r_script, output_dir) + + return { + "command_executed": exec_result["command_executed"], + "stdout": exec_result["stdout"], + "stderr": exec_result["stderr"], + "output_files": {"results_csv": str(output_csv.resolve())}, + } + + +@mcp.tool +def stjoincount_joincount_lisa( + input_file: Path, + coords_cols: str, + variable_col: str, + output_csv: Path, + graph_method: Literal["knn", "distance"], + binarize_threshold: float, + graph_param_k: Optional[int] = None, + graph_param_dist: Optional[float] = None, + nsim: int = 499, + alternative: Literal["greater", "less", "two.sided"] = "greater", + p_adjust_method: Literal[ + "holm", "hochberg", "hommel", "bonferroni", "BH", "BY", "fdr", "none" + ] = "none", +): + """ + Performs a local join count test for spatial clusters (LISA). + + This tool wraps the joincount.lisa function from R/spdep. It identifies + individual locations that are part of spatial clusters of similar binary values. + + Requires an R installation with the 'spdep' and 'readr' packages installed. + """ + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if nsim <= 0: + raise ValueError("nsim must be a positive integer.") + + coord_names = [c.strip() for c in coords_cols.split(',')] + if len(coord_names) != 2: + raise ValueError("coords_cols must be a comma-separated string of two column names.") + + if graph_method == "knn": + if graph_param_k is None or graph_param_k <= 0: + raise ValueError("graph_param_k must be a positive integer for knn method.") + elif graph_method == "distance": + if graph_param_dist is None or graph_param_dist <= 0: + raise ValueError("graph_param_dist must be a positive float for distance method.") + else: + raise ValueError(f"Unknown graph_method: {graph_method}") + + output_dir = output_csv.parent + output_dir.mkdir(parents=True, exist_ok=True) + + r_script = f""" + options(warn = -1) + if (!requireNamespace("spdep", quietly = TRUE)) {{ + stop("Package 'spdep' is not installed.") + }} + if (!requireNamespace("readr", quietly = TRUE)) {{ + stop("Package 'readr' is not installed.") + }} + library(spdep) + library(readr) + + data <- read_csv("{input_file.resolve()}", show_col_types = FALSE) + + required_cols <- c("{coord_names[0]}", "{coord_names[1]}", "{variable_col}") + if (!all(required_cols %in% colnames(data))) {{ + stop("One or more required columns not found in the input file.") + }} + + coords <- as.matrix(data[, c("{coord_names[0]}", "{coord_names[1]}")]) + x_binary <- as.factor(ifelse(data[["{variable_col}"]] > {binarize_threshold}, 1, 0)) + + if ("{graph_method}" == "knn") {{ + nb <- knn2nb(knearneigh(coords, k = {graph_param_k})) + }} else if ("{graph_method}" == "distance") {{ + nb <- dnearneigh(coords, d1 = 0, d2 = {graph_param_dist}) + }} + + lw <- nb2listw(nb, style = "B", zero.policy = TRUE) + + set.seed(123) + result <- joincount.lisa( + fx = x_binary, listw = lw, nsim = {nsim}, alternative = "{alternative}", + p.adjust.method = "{p_adjust_method}", zero.policy = TRUE + ) + + output_data <- cbind(data, as.data.frame(result)) + write.csv(output_data, file = "{output_csv.resolve()}", row.names = FALSE) + + cat("Local Join Count test complete. Results saved.\\n") + """ + + exec_result = _run_r_script(r_script, output_dir) + + return { + "command_executed": exec_result["command_executed"], + "stdout": exec_result["stdout"], + "stderr": exec_result["stderr"], + "output_files": {"results_csv": str(output_csv.resolve())}, + } \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-stjoincount/app/bioconductor-stjoincount_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-stjoincount/app/bioconductor-stjoincount_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ca5a1d12c04ccff626f7b306f118ed54685370bf --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-stjoincount/app/bioconductor-stjoincount_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-stjoincount/app/bioconductor-stjoincount_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_stjoincount' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-stjoincount/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-stjoincount/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-stjoincount/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-stjoincount/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-stjoincount/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..5d4ca0c86f4cd30d0e72b88a1b54f83e2ab8c0d4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-stjoincount/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-stjoincount: + build: . + image: mcp-bioconductor-stjoincount:latest + container_name: mcp-bioconductor-stjoincount + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-stjoincount + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-stjoincount/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-stjoincount/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..309317041ceeb2c4c4979c662745587202354f24 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-stjoincount/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-stjoincount + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-stjoincount/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-stjoincount/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-stjoincount/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-tidyomics/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-tidyomics/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cfc7b71104b7e0cc293eaaa48fbbae7a56c0d742 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-tidyomics/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-tidyomics via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-tidyomics -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-tidyomics_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-tidyomics_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-tidyomics_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-tidyomics/app/__pycache__/bioconductor-tidyomics_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-tidyomics/app/__pycache__/bioconductor-tidyomics_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2be09d4f599578b8edfa1a6c788f6561d0482b50 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-tidyomics/app/__pycache__/bioconductor-tidyomics_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-tidyomics/app/bioconductor-tidyomics_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-tidyomics/app/bioconductor-tidyomics_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e5cb8cd750ac31dbfdc9a64da3ba06731aef7c9b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-tidyomics/app/bioconductor-tidyomics_server.py @@ -0,0 +1,194 @@ +import subprocess +import tempfile +from pathlib import Path +import logging +from typing import List, Optional + +# Configure logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# Mock MCP decorator for standalone execution +class mcp: + @staticmethod + def tool(func): + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + # In a real MCP environment, this would register the function. + # For this script, we just return the original function. + return wrapper + +@mcp.tool +def tidyomics_list_packages() -> dict: + """ + Lists the core packages included in the tidyomics ecosystem. + + This function executes an R script that calls `tidyomics::tidyomics_packages()` + to retrieve and print the names of the core tidyomics packages. + + Returns: + dict: A dictionary containing the command executed, stdout, stderr, + and a list of the tidyomics packages. + """ + r_script_content = """ + tryCatch({ + suppressPackageStartupMessages(library(tidyomics)) + packages <- tidyomics::tidyomics_packages() + cat(packages, sep = "\\n") + }, error = function(e) { + message("Error: ", e$message) + quit(status = 1) + }) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = Path(r_script_file.name) + + command = ["Rscript", str(r_script_path)] + command_executed = " ".join(command) + logger.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + + stdout_lines = result.stdout.strip().split('\n') + packages = [line for line in stdout_lines if line] + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "packages": packages + } + except subprocess.CalledProcessError as e: + logger.error(f"Error executing tidyomics_list_packages: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed." + } + finally: + r_script_path.unlink() + +@mcp.tool +def tidyomics_attach_packages(quietly: bool = False) -> dict: + """ + Loads the tidyomics meta-package and captures the attachment messages. + + This function simulates the primary use of the package, which is to load + the entire tidyomics ecosystem into an R session. The startup messages, + which show attached packages and version info, are captured from stderr. + + Args: + quietly (bool): If True, suppresses startup messages. Defaults to False. + + Returns: + dict: A dictionary containing the command executed, stdout, and stderr + (which contains the attachment log). + """ + # R's boolean literals are uppercase + quietly_r = "TRUE" if quietly else "FALSE" + + r_script_content = f""" + tryCatch({{ + library(tidyomics, quietly = {quietly_r}) + }}, error = function(e) {{ + message("Error: ", e$message) + quit(status = 1) + }}) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = Path(r_script_file.name) + + command = ["Rscript", str(r_script_path)] + command_executed = " ".join(command) + logger.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + } + except subprocess.CalledProcessError as e: + logger.error(f"Error executing tidyomics_attach_packages: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed." + } + finally: + r_script_path.unlink() + +@mcp.tool +def tidyomics_check_conflicts() -> dict: + """ + Reports on namespace conflicts between tidyomics packages and other loaded packages. + + This function executes `tidyomics::tidyomics_conflicts()` to identify functions + that are masked by others, which is a common issue when loading multiple + packages with overlapping function names. + + Returns: + dict: A dictionary containing the command executed, stdout (which contains + the conflict report), and stderr. + """ + r_script_content = """ + tryCatch({ + suppressPackageStartupMessages(library(tidyomics)) + conflicts <- tidyomics::tidyomics_conflicts() + print(conflicts) + }, error = function(e) { + message("Error: ", e$message) + quit(status = 1) + }) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = Path(r_script_file.name) + + command = ["Rscript", str(r_script_path)] + command_executed = " ".join(command) + logger.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + } + except subprocess.CalledProcessError as e: + logger.error(f"Error executing tidyomics_check_conflicts: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed." + } + finally: + r_script_path.unlink() \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-tidyomics/app/bioconductor-tidyomics_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-tidyomics/app/bioconductor-tidyomics_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4e19c1a9161364d640c9365da7ac7f8a9585260b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-tidyomics/app/bioconductor-tidyomics_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-tidyomics/app/bioconductor-tidyomics_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_tidyomics' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-tidyomics/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-tidyomics/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-tidyomics/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-tidyomics/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-tidyomics/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..9b52cded7a055fcee257fccf09f8018d2e24a424 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-tidyomics/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-tidyomics: + build: . + image: mcp-bioconductor-tidyomics:latest + container_name: mcp-bioconductor-tidyomics + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-tidyomics + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-tidyomics/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-tidyomics/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..204ac4df1f6f51224574fd73d04681c9d3c2e6df --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-tidyomics/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-tidyomics + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-tidyomics/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-tidyomics/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-tidyomics/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-weberdivechalcdata/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-weberdivechalcdata/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..34f22cb21219fcac9d2d1c71f5bd8bd7fb42cd51 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-weberdivechalcdata/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-weberdivechalcdata via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-weberdivechalcdata -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-weberdivechalcdata_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-weberdivechalcdata_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-weberdivechalcdata_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-weberdivechalcdata/app/__pycache__/bioconductor-weberdivechalcdata_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-weberdivechalcdata/app/__pycache__/bioconductor-weberdivechalcdata_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c4563afd918a4aefdfef474e2ac811e0f546bd0c Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-weberdivechalcdata/app/__pycache__/bioconductor-weberdivechalcdata_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-weberdivechalcdata/app/bioconductor-weberdivechalcdata_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-weberdivechalcdata/app/bioconductor-weberdivechalcdata_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7cee82c09019f534f632d256236626903ebbaae7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-weberdivechalcdata/app/bioconductor-weberdivechalcdata_server.py @@ -0,0 +1,112 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Literal, Dict, List + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided by the MCP framework. +def mcp_tool_placeholder(*args, **kwargs): + def decorator(func): + return func + return decorator + +mcp = type("MCP", (), {"tool": mcp_tool_placeholder}) + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_bioconductor_weberdivechalcdata' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def load_weberdivechalc_data( + dataset: Literal["sce", "spe"], + output_rds: Path, +) -> Dict[str, any]: + """ + Loads a specified dataset from the WeberDivechaLCdata Bioconductor package and saves it as an RDS file. + + The WeberDivechaLCdata package provides spatially-resolved transcriptomics (SRT) and + single-nucleus RNA-sequencing (snRNA-seq) data from the locus coeruleus (LC) in + postmortem human brain samples. + + Args: + dataset: The dataset to load. + 'sce': Loads the SingleCellExperiment object with snRNA-seq data. + 'spe': Loads the SpatialExperiment object with Visium SRT data. + output_rds: The path to save the output data object as an .rds file. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # Input validation + if dataset not in ["sce", "spe"]: + raise ValueError("The 'dataset' parameter must be either 'sce' or 'spe'.") + + if not output_rds.parent.exists(): + output_rds.parent.mkdir(parents=True, exist_ok=True) + + r_script_content = f""" + # Ensure ExperimentHub can write to a user-accessible directory + # This is important for environments where the default cache is not writable + eh_cache_dir <- rappdirs::user_cache_dir(appname="ExperimentHub") + if (!dir.exists(eh_cache_dir)) {{ + dir.create(eh_cache_dir, recursive = TRUE) + }} + setExperimentHubOption("CACHE", eh_cache_dir) + + # Load the necessary library + library(WeberDivechaLCdata) + + # Load the specified dataset + cat("Loading dataset: {dataset}...\\n") + data_object <- WeberDivechaLCdata(dataset = "{dataset}") + + # Save the data object to the specified RDS file + cat("Saving data object to {str(output_rds)}\\n") + saveRDS(data_object, file = "{str(output_rds)}") + + cat("Process complete.\\n") + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_r_script: + tmp_r_script.write(r_script_content) + r_script_path = tmp_r_script.name + + command = ["Rscript", r_script_path] + command_executed = " ".join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + + # Clean up the temporary R script file + Path(r_script_path).unlink() + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": { + "data_object_rds": str(output_rds) + } + } + except subprocess.CalledProcessError as e: + # Clean up the temporary R script file even on error + Path(r_script_path).unlink() + + error_message = ( + 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}" + ) + raise RuntimeError(error_message) from e + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-weberdivechalcdata/app/bioconductor-weberdivechalcdata_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-weberdivechalcdata/app/bioconductor-weberdivechalcdata_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..850166979feb244c56eb16d142700f378ed71432 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-weberdivechalcdata/app/bioconductor-weberdivechalcdata_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-weberdivechalcdata/app/bioconductor-weberdivechalcdata_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_bioconductor_weberdivechalcdata' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-weberdivechalcdata/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-weberdivechalcdata/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-weberdivechalcdata/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-weberdivechalcdata/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-weberdivechalcdata/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-weberdivechalcdata/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_celltypist/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_celltypist/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7aef2682e4708f4951775888341113d6336c96e9 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_celltypist/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install celltypist via conda (e.g., from bioconda) +RUN conda install -c bioconda celltypist -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY celltypist_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/celltypist_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/celltypist_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_celltypist/app/__pycache__/celltypist_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_celltypist/app/__pycache__/celltypist_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4c86c58a5cff7efab81823314bc577b51f0e6077 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_celltypist/app/__pycache__/celltypist_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_celltypist/app/celltypist_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_celltypist/app/celltypist_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fc666a1fab7c98d95c79b2e180050c74b6662ff4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_celltypist/app/celltypist_server.py @@ -0,0 +1,205 @@ +from __future__ import annotations + +import subprocess +import tempfile +from pathlib import Path +from typing import List, Literal, Optional + +# MCP decorator is not imported as per instructions. +# It is assumed to be available in the execution environment. + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_celltypist' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def celltypist_predict( + indata: Path, + model: Optional[str] = None, + transpose_input: bool = False, + gene_file: Optional[Path] = None, + cell_file: Optional[Path] = None, + mode: Literal["best_match", "prob_match"] = "best_match", + p_thres: float = 0.5, + majority_voting: bool = False, + over_clustering: str = "auto", + use_gpu: bool = False, + min_prop: float = 0.0, + outdir: Optional[Path] = None, + prefix: Optional[str] = None, + xlsx: bool = False, + plot_results: bool = False, + quiet: bool = False, +) -> dict: + """ + Run Celltypist for semi-automatic cell type annotation on a given count matrix. + + Args: + indata: Path to the input count matrix (.csv/txt/tsv/tab/mtx) or AnnData (.h5ad). + model: Model used for predictions. Defaults to 'Immune_All_Low.pkl'. + transpose_input: Transpose the input matrix if it is in gene-by-cell format. + gene_file: Path to a file with one gene per line for mtx input. + cell_file: Path to a file with one cell per line for mtx input. + mode: Prediction mode, 'best_match' or 'prob_match'. + p_thres: Probability threshold for 'prob_match' mode. + majority_voting: Refine predicted labels by majority voting after over-clustering. + over_clustering: Input for over-clustering. Can be a file path or a string key. + use_gpu: Use GPU for over-clustering. Requires rapids-singlecell. + min_prop: Minimum proportion of cells for naming a subcluster in majority voting. + outdir: Directory to store output files. A temporary directory is used if not provided. + prefix: Prefix for output files. + xlsx: Merge output tables into a single Excel (.xlsx) file. + plot_results: Generate plots for the prediction results. + quiet: Hide banner and configuration information during the run. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # 1. Input validation + if not indata.is_file(): + raise FileNotFoundError(f"Input data file not found: {indata}") + if gene_file and not gene_file.is_file(): + raise FileNotFoundError(f"Gene file not found: {gene_file}") + if cell_file and not cell_file.is_file(): + raise FileNotFoundError(f"Cell file not found: {cell_file}") + if not (0.0 <= p_thres <= 1.0): + raise ValueError(f"p_thres must be between 0.0 and 1.0, but got {p_thres}") + if not (0.0 <= min_prop <= 1.0): + raise ValueError(f"min_prop must be between 0.0 and 1.0, but got {min_prop}") + + # 2. Command construction and output directory handling + with tempfile.TemporaryDirectory() as temp_dir: + if outdir is None: + run_outdir = Path(temp_dir) + else: + run_outdir = outdir + run_outdir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "celltypist", + "--indata", str(indata), + "--outdir", str(run_outdir), + ] + + if model: + cmd.extend(["--model", model]) + if transpose_input: + cmd.append("--transpose-input") + if gene_file: + cmd.extend(["--gene-file", str(gene_file)]) + if cell_file: + cmd.extend(["--cell-file", str(cell_file)]) + + cmd.extend(["--mode", mode]) + if mode == "prob_match": + cmd.extend(["--p-thres", str(p_thres)]) + + if majority_voting: + cmd.append("--majority-voting") + cmd.extend(["--over-clustering", over_clustering]) + if use_gpu: + cmd.append("--use-GPU") + cmd.extend(["--min-prop", str(min_prop)]) + + if prefix: + cmd.extend(["--prefix", prefix]) + if xlsx: + cmd.append("--xlsx") + if plot_results: + cmd.append("--plot-results") + if quiet: + cmd.append("--quiet") + + # 3. Subprocess execution and error handling + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + encoding='utf-8' + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(map(str, cmd)), + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + "output_files": [] + } + + # 4. Collect and return structured output + output_files = [str(f) for f in run_outdir.glob("**/*") if f.is_file()] + + return { + "command_executed": " ".join(map(str, cmd)), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files + } + +@mcp.tool() +def celltypist_show_models() -> dict: + """ + Show all available Celltypist models and their descriptions. + + Returns: + A dictionary containing the executed command, stdout, and stderr. + """ + cmd = ["celltypist", "--show-models"] + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + encoding='utf-8' + ) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + } + +@mcp.tool() +def celltypist_update_models() -> dict: + """ + Download the latest Celltypist models from the remote server. + + Returns: + A dictionary containing the executed command, stdout, and stderr. + """ + cmd = ["celltypist", "--update-models"] + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + encoding='utf-8' + ) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_celltypist/app/celltypist_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_celltypist/app/celltypist_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a329ec100f622da500a5a734f31b8d6d95af228c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_celltypist/app/celltypist_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_celltypist/app/celltypist_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_celltypist' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_celltypist/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_celltypist/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f53b5ace39885ced50106457777cf126f3ad6e2a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_celltypist/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-celltypist: + build: . + image: mcp-celltypist:latest + container_name: mcp-celltypist + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=celltypist + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_celltypist/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_celltypist/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..76e5dc75e1be1d91d909773c3edf8379d5a6bebb --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_celltypist/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - celltypist + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_celltypist/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_celltypist/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_celltypist/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cosg/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cosg/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..84e704695e77c7a78067ebd5fc584563fbf701c3 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cosg/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install cosg via conda (e.g., from bioconda) +RUN conda install -c bioconda cosg -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY cosg_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/cosg_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/cosg_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cosg/app/__pycache__/cosg_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cosg/app/__pycache__/cosg_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1826bbfaa47378a094b76ddd5e6fda3f8a6f20f9 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cosg/app/__pycache__/cosg_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cosg/app/cosg_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cosg/app/cosg_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3becb25401e2fb14f5395281845ab4e31aaed212 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cosg/app/cosg_server.py @@ -0,0 +1,132 @@ +import subprocess +from pathlib import Path +from typing import Optional +import logging + +# Set up logging +logging.basicConfig(level=logging.INFO) +log = logging.getLogger(__name__) + +# Assuming mcp.tool is available in the execution environment. +# This is a placeholder for the actual decorator. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_cosg' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def cosg( + input_file: Path, + output_file: Path, + group_by: Optional[str] = None, + use_raw: bool = False, + mu: float = 1.0, + n_genes_user: int = 100, + remove_low_umi_genes: bool = False, + low_umi_cutoff: Optional[float] = None, +) -> dict: + """ + Identifies marker genes for single-cell sequencing data using the COSG method. + + This tool wraps the command-line version of COSG, which performs robust marker + gene selection from single-cell transcriptomics data. + + Args: + input_file: Path to the input AnnData object file (.h5ad). + output_file: Path to the output file for marker genes (.csv, .tsv, .txt). + group_by: The column name in the .obs attribute of the AnnData object to group cells by. + use_raw: If True, use the raw counts for marker gene identification. + mu: The penalty parameter for gene weights. Must be a positive value. + n_genes_user: The number of marker genes to identify for each cluster. Must be a positive integer. + remove_low_umi_genes: If True, remove genes with low UMI counts before analysis. + low_umi_cutoff: The UMI count cutoff for removing low-expressed genes. Only used if remove_low_umi_genes is True. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a dictionary of output files. + """ + # --- Input Validation --- + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found at: {input_file}") + + if not output_file.parent.is_dir(): + raise NotADirectoryError(f"Output directory does not exist: {output_file.parent}") + + if mu <= 0: + raise ValueError("The 'mu' parameter must be a positive number.") + + if n_genes_user <= 0: + raise ValueError("The 'n_genes_user' parameter must be a positive integer.") + + if low_umi_cutoff is not None and low_umi_cutoff < 0: + raise ValueError("The 'low_umi_cutoff' parameter cannot be negative.") + + # --- Command Construction --- + cmd = [ + "cosg", + "--input", str(input_file), + "--output", str(output_file), + "--mu", str(mu), + "--n-genes-user", str(n_genes_user), + ] + + if group_by: + cmd.extend(["--group-by", group_by]) + + # Boolean flags are added only if they are True, as is standard for CLI tools. + if use_raw: + cmd.append("--use-raw") + + if remove_low_umi_genes: + cmd.append("--remove-low-umi-genes") + if low_umi_cutoff is not None: + cmd.extend(["--low-umi-cutoff", str(low_umi_cutoff)]) + + command_executed = " ".join(cmd) + log.info(f"Executing command: {command_executed}") + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + stdout = result.stdout + stderr = result.stderr + + # --- Structured Result Return --- + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": { + "marker_genes": str(output_file) + } + } + except FileNotFoundError: + log.error("The 'cosg' command was not found.") + raise RuntimeError( + "The 'cosg' executable is not in the system's PATH. Please ensure it is installed and accessible." + ) + except subprocess.CalledProcessError as e: + log.error(f"COSG execution failed with return code {e.returncode}") + log.error(f"Stdout: {e.stdout}") + log.error(f"Stderr: {e.stderr}") + raise RuntimeError( + f"COSG command failed.\n" + f"Command: {command_executed}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) from e + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cosg/app/cosg_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cosg/app/cosg_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3f3350f5095b32c5dd55bac9932caece7593b9bb --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cosg/app/cosg_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_cosg/app/cosg_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_cosg' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cosg/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cosg/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..119490df670800288ffa5d8cd6ad784fdcc576f1 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cosg/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-cosg: + build: . + image: mcp-cosg:latest + container_name: mcp-cosg + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=cosg + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cosg/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cosg/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8414534359b03445a0a6b3dc283d73d6d4762b7f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cosg/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - cosg + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cosg/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cosg/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cosg/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cutadapt/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cutadapt/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a29aab2da7b5bc93084b8628501e2937826fb8e7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cutadapt/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install cutadapt via conda (e.g., from bioconda) +RUN conda install -c bioconda cutadapt -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/cutadapt_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/cutadapt_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/cutadapt_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cutadapt/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cutadapt/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..252864446952d8c6b46b41cadd609f9fd0fc8195 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cutadapt/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-cutadapt: + build: . + image: mcp-cutadapt:latest + container_name: mcp-cutadapt + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=cutadapt + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cutadapt/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cutadapt/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e658fc31395bdbc155097b1965ea85c31adf7977 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cutadapt/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - cutadapt + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cutadapt/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cutadapt/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_cutadapt/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptoolsintervals/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptoolsintervals/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f40acac57dcd1dd7f25a06c2964a112577b7990e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptoolsintervals/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install deeptoolsintervals via conda (e.g., from bioconda) +RUN conda install -c bioconda deeptoolsintervals -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/deeptoolsintervals_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/deeptoolsintervals_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/deeptoolsintervals_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptoolsintervals/app/__pycache__/deeptoolsintervals_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptoolsintervals/app/__pycache__/deeptoolsintervals_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..22093b4d4ff12a7a4b2746410d7ff5bed300181f Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptoolsintervals/app/__pycache__/deeptoolsintervals_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptoolsintervals/app/deeptoolsintervals_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptoolsintervals/app/deeptoolsintervals_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3392e1d0235d71a4f8e14a3b799439f5920153e0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptoolsintervals/app/deeptoolsintervals_server.py @@ -0,0 +1,121 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +# The mcp.tool decorator is expected to be provided by the Model Context Protocol server environment. +# It is not defined here. + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_deeptoolsintervals' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def deeptoolsintervals( + bed: Path, + dist: int = 0, + merge: bool = False, + output_file: Optional[Path] = None +) -> Dict[str, Any]: + """ + Processes a BED file to merge overlapping regions or compute distances between features. + + This tool is an internal utility from the deepTools suite. Its default behavior + is to merge overlapping regions in the input BED file. Alternatively, it can + compute the distance between consecutive genomic features. The output is written + to standard output. + + Args: + bed (Path): Input BED file to be processed. + dist (int): If greater than 0, compute the distance between consecutive entries + instead of merging. A value of 1 means distance between consecutive + entries (1st and 2nd, 2nd and 3rd, etc.). A value of 2 means + distance between entry 1 and 3, 2 and 4, etc. A value of 0 + (default) disables distance computation and enables merging. + merge (bool): Explicitly request merging of overlapping regions. This is the + default behavior when `dist` is 0. Using `merge=True` with `dist > 0` + is not allowed as they are mutually exclusive operations. + output_file (Optional[Path]): Path to save the output. If not provided, + the output is captured and returned in `stdout`. + + Returns: + Dict[str, Any]: A dictionary containing the execution details: + - command_executed (str): The command line string executed. + - stdout (str): The standard output from the tool, or a message indicating file output. + - stderr (str): The standard error from the tool. + - output_files (List[str]): A list of paths to generated output files. + """ + # 1. Input Validation + if not bed.is_file(): + raise FileNotFoundError(f"Input BED file not found at {bed}") + if dist < 0: + raise ValueError("The 'dist' parameter must be a non-negative integer.") + if dist > 0 and merge: + raise ValueError("The 'dist' and 'merge' parameters are mutually exclusive. Use 'dist' for distance calculation or 'merge' for merging regions.") + + # 2. Command Construction + cmd = ["deeptoolsintervals", "--bed", str(bed)] + + # The tool's logic is that if dist > 0, it calculates distance. + # If dist == 0, it merges. The --merge flag is for explicit declaration. + if dist > 0: + cmd.extend(["--dist", str(dist)]) + elif merge: + # This is only added if the user explicitly sets merge=True. + # The tool's default action is to merge when dist=0 anyway. + cmd.append("--merge") + + command_executed = " ".join(cmd) + output_files: List[str] = [] + + # 3. Subprocess Execution + try: + if output_file: + # Ensure parent directory exists for the output file + output_file.parent.mkdir(parents=True, exist_ok=True) + with open(output_file, "w") as f_out: + result = subprocess.run( + cmd, + text=True, + check=True, + stdout=f_out, + stderr=subprocess.PIPE + ) + stdout_content = f"Output successfully written to {output_file}" + stderr_content = result.stderr + output_files.append(str(output_file)) + else: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + stdout_content = result.stdout + stderr_content = result.stderr + + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'deeptoolsintervals' command not found. Please ensure deepTools 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": output_files + } + + # 4. Structured Result Return + return { + "command_executed": command_executed, + "stdout": stdout_content, + "stderr": stderr_content, + "output_files": output_files + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptoolsintervals/app/deeptoolsintervals_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptoolsintervals/app/deeptoolsintervals_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..04e9c4ae01130fe125af6b5396da52b50a50960d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptoolsintervals/app/deeptoolsintervals_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_deeptoolsintervals/app/deeptoolsintervals_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_deeptoolsintervals' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptoolsintervals/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptoolsintervals/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptoolsintervals/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptoolsintervals/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptoolsintervals/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..4eae2e5018342a973fcbfc756298e0cb10192a82 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptoolsintervals/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-deeptoolsintervals: + build: . + image: mcp-deeptoolsintervals:latest + container_name: mcp-deeptoolsintervals + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=deeptoolsintervals + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptoolsintervals/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptoolsintervals/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..16314b05f46b134673b40a3d7202b99740c15635 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptoolsintervals/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - deeptoolsintervals + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptoolsintervals/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptoolsintervals/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_deeptoolsintervals/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_dropkick/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_dropkick/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fe99026d68d574e29eaf2ce234ecd03abfad3f1e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_dropkick/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install dropkick via conda (e.g., from bioconda) +RUN conda install -c bioconda dropkick -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/dropkick_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/dropkick_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/dropkick_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_dropkick/app/__pycache__/dropkick_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_dropkick/app/__pycache__/dropkick_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9fa94909d3623534ceba15a85f8a31297aa0ad52 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_dropkick/app/__pycache__/dropkick_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_dropkick/app/dropkick_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_dropkick/app/dropkick_server.py new file mode 100644 index 0000000000000000000000000000000000000000..40b99c21c6002ebdf26e7700a060458473a9db61 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_dropkick/app/dropkick_server.py @@ -0,0 +1,201 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# MCP decorator is not imported as per instructions, +# but it is assumed to be available in the execution environment. +# from mcp import tool as mcp_tool +# +# def mcp_tool(): +# def decorator(f): +# return f +# return decorator +# +# mcp = type("mcp", (), {"tool": mcp_tool}) + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_dropkick' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def dropkick_run( + counts_file: Path, + output_dir: Optional[Path] = None, + method: str = "subtraction", + thresh: Optional[float] = None, + genes: int = 100, + n_jobs: int = 1, +): + """ + Runs the main dropkick filtering pipeline on single-cell RNA sequencing data. + + This tool filters cells from raw count matrices, identifies high-quality cells, + and saves the results, including cell probability scores and labels, + in a new .h5ad file. + + Args: + counts_file: Path to the input counts file (.h5ad, .csv, or .tsv). + output_dir: Output directory. Defaults to the input file's directory. + method: Ambient background correction method. One of ['subtraction', 'multiplication']. + thresh: Override automatic empty droplet threshold. Must be a float between 0 and 1. + genes: Number of ambient genes to use. + n_jobs: Number of CPU cores to use. + + Returns: + A dictionary containing the executed command, stdout, stderr, and the path to the output .h5ad file. + """ + # --- Input Validation --- + if not counts_file.is_file(): + raise FileNotFoundError(f"Input file not found: {counts_file}") + + if method not in ["subtraction", "multiplication"]: + raise ValueError(f"Invalid method '{method}'. Must be 'subtraction' or 'multiplication'.") + + if thresh is not None and not (0.0 <= thresh <= 1.0): + raise ValueError(f"Threshold 'thresh' must be between 0.0 and 1.0, but got {thresh}.") + + if genes <= 0: + raise ValueError(f"Number of genes must be a positive integer, but got {genes}.") + + if n_jobs <= 0: + raise ValueError(f"Number of jobs 'n_jobs' must be a positive integer, but got {n_jobs}.") + + # --- Command Construction --- + cmd = ["dropkick", "run", str(counts_file)] + + if output_dir: + output_dir.mkdir(parents=True, exist_ok=True) + cmd.extend(["--out", str(output_dir)]) + out_path = output_dir + else: + out_path = counts_file.parent + + if method != "subtraction": + cmd.extend(["--method", method]) + + if thresh is not None: + cmd.extend(["--thresh", str(thresh)]) + + if genes != 100: + cmd.extend(["--genes", str(genes)]) + + if n_jobs != 1: + cmd.extend(["--n_jobs", str(n_jobs)]) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except FileNotFoundError: + raise RuntimeError("dropkick executable not found. Please ensure it is installed and in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"dropkick run failed with exit code {e.returncode}", + "output_files": [] + } + + # --- Output Handling --- + # dropkick creates an output file named _dropkick.h5ad + input_basename = counts_file.stem + output_h5ad = out_path / f"{input_basename}_dropkick.h5ad" + + output_files = [] + if output_h5ad.exists(): + output_files.append(str(output_h5ad)) + else: + # Log a warning if the expected output is not found + result.stderr += f"\nWARNING: Expected output file not found at {output_h5ad}" + + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + + +@mcp.tool() +def dropkick_qc( + counts_file: Path, + output_dir: Optional[Path] = None, +): + """ + Runs a quick quality control check on scRNA-seq data. + + This tool generates a plot of the total UMI distribution and ambient genes, + which is saved as a PNG image file. + + Args: + counts_file: Path to the input counts file (.h5ad, .csv, or .tsv). + output_dir: Output directory. Defaults to the input file's directory. + + Returns: + A dictionary containing the executed command, stdout, stderr, and the path to the output QC plot. + """ + # --- Input Validation --- + if not counts_file.is_file(): + raise FileNotFoundError(f"Input file not found: {counts_file}") + + # --- Command Construction --- + cmd = ["dropkick", "qc", str(counts_file)] + + if output_dir: + output_dir.mkdir(parents=True, exist_ok=True) + cmd.extend(["--out", str(output_dir)]) + out_path = output_dir + else: + out_path = counts_file.parent + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except FileNotFoundError: + raise RuntimeError("dropkick executable not found. Please ensure it is installed and in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"dropkick qc failed with exit code {e.returncode}", + "output_files": [] + } + + # --- Output Handling --- + # dropkick qc creates an output file named _qc.png + input_basename = counts_file.stem + output_png = out_path / f"{input_basename}_qc.png" + + output_files = [] + if output_png.exists(): + output_files.append(str(output_png)) + else: + # Log a warning if the expected output is not found + result.stderr += f"\nWARNING: Expected output file not found at {output_png}" + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_dropkick/app/dropkick_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_dropkick/app/dropkick_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d816126774d1e1f85c50c298bae36a0a3dc7aca3 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_dropkick/app/dropkick_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_dropkick/app/dropkick_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_dropkick' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_dropkick/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_dropkick/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_dropkick/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_dropkick/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_dropkick/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..fedcde33ee80da29a12ca9733d05204565e3cfe8 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_dropkick/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-dropkick: + build: . + image: mcp-dropkick:latest + container_name: mcp-dropkick + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=dropkick + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_dropkick/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_dropkick/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..dad3f0acf4878ef9f80138f938642ec863c13cb8 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_dropkick/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - dropkick + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_dropkick/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_dropkick/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_dropkick/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ena-webin-cli/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ena-webin-cli/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..27c43fccf2a9dc81337c1024b8d3cf97ffcb6548 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ena-webin-cli/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install ena-webin-cli via conda (e.g., from bioconda) +RUN conda install -c bioconda ena-webin-cli -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/ena-webin-cli_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/ena-webin-cli_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/ena-webin-cli_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ena-webin-cli/app/__pycache__/ena-webin-cli_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ena-webin-cli/app/__pycache__/ena-webin-cli_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..035996410c0bdbe7f1362859704719f4ccd85669 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ena-webin-cli/app/__pycache__/ena-webin-cli_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ena-webin-cli/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ena-webin-cli/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f0131324c4b94726e90532dc7f6b762fcd5639c8 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ena-webin-cli/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-ena-webin-cli: + build: . + image: mcp-ena-webin-cli:latest + container_name: mcp-ena-webin-cli + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=ena-webin-cli + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ena-webin-cli/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ena-webin-cli/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3dd0702e48d49582bd2add0c90f4b46fe1e2a6d1 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ena-webin-cli/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - ena-webin-cli + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ena-webin-cli/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ena-webin-cli/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ena-webin-cli/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fastdtw/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fastdtw/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a8f7c742b54006a1241d90dbc02cbfbaad1ba53d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fastdtw/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install fastdtw via conda (e.g., from bioconda) +RUN conda install -c bioconda fastdtw -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/fastdtw_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/fastdtw_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/fastdtw_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fastdtw/app/__pycache__/fastdtw_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fastdtw/app/__pycache__/fastdtw_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14a09b1af8f6607eee460a8b8256c29d98b86197 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fastdtw/app/__pycache__/fastdtw_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fastdtw/app/fastdtw_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fastdtw/app/fastdtw_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a8bea63fe8e4baed58b7b6b1e362023886224340 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fastdtw/app/fastdtw_server.py @@ -0,0 +1,110 @@ +from pathlib import Path +import subprocess +from typing import Optional, Dict, Any, List + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_fastdtw' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def fastdtw_compute( + series_1_path: str, + series_2_path: str, + radius: int = 1, + distance_metric: str = "euclidean", +) -> Dict[str, Any]: + """ + Compute the Fast Dynamic Time Warping (FastDTW) distance between two time-series files. + FastDTW is an approximate DTW algorithm that provides optimal or near-optimal alignments + with an O(N) time and memory complexity. + + Args: + series_1_path: Path to the first time-series data file (e.g., CSV, TSV, or text). + series_2_path: Path to the second time-series data file (e.g., CSV, TSV, or text). + radius: The search radius for the approximation. A larger radius increases accuracy but increases computation time. Default is 1. + distance_metric: The distance metric to use. Common options include 'euclidean', 'manhattan', 'chebyshev', etc. Default is 'euclidean'. + """ + + # Input validation + path1 = Path(series_1_path) + path2 = Path(series_2_path) + + if not path1.exists(): + return {"error": f"Input file 1 not found: {series_1_path}"} + if not path2.exists(): + return {"error": f"Input file 2 not found: {series_2_path}"} + + if radius < 1: + return {"error": "Radius must be an integer greater than or equal to 1."} + + # Construct the command + # Based on standard python -m fastdtw CLI patterns + cmd = [ + "python", "-m", "fastdtw", + str(path1), + str(path2), + "--radius", str(radius), + "--dist", distance_metric + ] + + try: + # Execute the tool + 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": f"FastDTW execution failed with return code {e.returncode}", + "status": "error" + } + except Exception as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "status": "error" + } + +@mcp.tool() +def fastdtw_help() -> Dict[str, Any]: + """ + Retrieve the help documentation and version information for the fastdtw CLI tool. + """ + cmd = ["python", "-m", "fastdtw", "--help"] + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to retrieve help documentation." + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fastdtw/app/fastdtw_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fastdtw/app/fastdtw_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a7d1b7185c9fd19b2254450f472aca0ccef85c8e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fastdtw/app/fastdtw_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_fastdtw/app/fastdtw_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_fastdtw' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fastdtw/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fastdtw/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fastdtw/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fastdtw/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fastdtw/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..bff043cc7a4e3531b5906f10ebed09c08bcf3115 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fastdtw/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-fastdtw: + build: . + image: mcp-fastdtw:latest + container_name: mcp-fastdtw + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=fastdtw + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fastdtw/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fastdtw/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..91d80641f507ab9f7af361b27aae074e7c1f5c07 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fastdtw/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - fastdtw + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fastdtw/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fastdtw/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fastdtw/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fasttree/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fasttree/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ad5b64c271d3c8d2a352ffc42c8040aacd559220 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fasttree/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install fasttree via conda (e.g., from bioconda) +RUN conda install -c bioconda fasttree -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/fasttree_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/fasttree_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/fasttree_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fasttree/app/__pycache__/fasttree_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fasttree/app/__pycache__/fasttree_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16d0ae8d668032a156c8447ef8be36755726196f Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fasttree/app/__pycache__/fasttree_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fasttree/app/fasttree_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fasttree/app/fasttree_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e5f0a72a894387ddf3c58aa6345917bbab8d61f4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fasttree/app/fasttree_server.py @@ -0,0 +1,223 @@ +import logging +import subprocess +from pathlib import Path +from typing import Dict, List, Optional, Union +import tempfile + +# Dummy decorator to allow the code to be syntactically correct without the MCP framework. +# In a real MCP environment, this would be provided by the framework. +class mcp: + def tool(func): + return func + +@mcp.tool +def fasttree( + alignment_file: Path, + output_tree_file: Optional[Path] = None, + log_file: Optional[Path] = None, + nucleotide: bool = False, + model: Optional[str] = None, + gamma: bool = False, + search_thoroughness: str = "normal", + no_ml: bool = False, + no_me: bool = False, + initial_tree: Optional[Path] = None, + initial_tree_round1: Optional[Path] = None, + bootstraps: Optional[int] = None, + sh_test: bool = False, + no_support: bool = False, + no_cat: bool = False, + categories: int = 20, + pseudocounts: bool = False, + bionj: bool = False, + nj: bool = False, + matrix_file: Optional[Path] = None, + constraints_file: Optional[Path] = None, + constraint_weight: Optional[float] = None, + seed: Optional[int] = None, + min_evolution_rounds: Optional[int] = None, + quiet: bool = False, + executable_name: str = "FastTree", +) -> Dict[str, Union[str, List[str], Dict[str, str]]]: + """ + Run FastTree to infer an approximately-maximum-likelihood phylogenetic tree. + + FastTree infers approximately-maximum-likelihood phylogenetic trees from alignments of + nucleotide or protein sequences. It is designed for large alignments. + + Args: + alignment_file: Path to the input alignment file in FASTA or Phylip format. + output_tree_file: Path to save the output tree file in Newick format. + If not provided, the tree is written to a temporary file. + log_file: Path to save the log file with progress and model parameters. + nucleotide: Assume nucleotide alignment (-nt). Default is protein. + model: Specify the substitution model. For nucleotides, 'gtr' is the only valid option. + For proteins, choices are 'wag' (default) or 'jtt' ('jones'). + gamma: Re-optimize the gamma20 likelihood model parameters after each round of topology optimization. + search_thoroughness: Control the search thoroughness. + Choices: 'normal', 'fastest', 'slow', 'slowest'. + no_ml: Do not perform maximum-likelihood steps (-noml). + no_me: Do not perform minimum-evolution steps (-nome). + initial_tree: Path to a starting tree file (-intree). + initial_tree_round1: Path to a starting tree for the first round only (-intree1). + bootstraps: Number of bootstrap replicates for branch support (-boot). + sh_test: Compute local support values with the Shimodaira-Hasegawa test (-sh). + no_support: Do not compute any support values (-nosupport). + no_cat: Do not use the CAT approximation of rate heterogeneity (-nocat). + categories: Number of rate categories for the CAT approximation (-cat). + pseudocounts: Use pseudocounts to handle gaps in protein alignments (-pseudo). + bionj: Use BIONJ for the initial tree (-bionj). Mutually exclusive with 'nj'. + nj: Use Neighbor-Joining for the initial tree (-nj). Mutually exclusive with 'bionj'. + matrix_file: Path to a user-provided substitution matrix file (-matrix). + constraints_file: Path to a file with topological constraints (-constraints). + constraint_weight: Weight for the topological constraints (-constraintWeight). + seed: Specify a random seed for bootstrapping (-seed). + min_evolution_rounds: Number of rounds of minimum-evolution-based topology improvement (-n). + quiet: Suppress progress indicators (-quiet or -nopr). + executable_name: The name of the FastTree executable (e.g., 'FastTree', 'FastTreeMP'). + + Returns: + A dictionary containing the executed command, stdout, stderr, and a dict of output file paths. + """ + # 1. Input Validation + if not alignment_file.is_file(): + raise FileNotFoundError(f"Alignment file not found: {alignment_file}") + + for file_path in [initial_tree, initial_tree_round1, matrix_file, constraints_file]: + if file_path and not file_path.is_file(): + raise FileNotFoundError(f"Input file not found: {file_path}") + + if nucleotide: + if model and model.lower() != 'gtr': + raise ValueError("For nucleotide data (-nt), the only valid model is 'gtr'.") + else: + if model and model.lower() not in ['wag', 'jtt', 'jones']: + raise ValueError("For protein data, valid models are 'wag' or 'jtt' ('jones').") + + allowed_search = ["normal", "fastest", "slow", "slowest"] + if search_thoroughness not in allowed_search: + raise ValueError(f"search_thoroughness must be one of {allowed_search}") + + if bionj and nj: + raise ValueError("Cannot specify both -bionj and -nj simultaneously.") + + if bootstraps is not None and bootstraps <= 0: + raise ValueError("Number of bootstraps must be a positive integer.") + + if categories <= 0: + raise ValueError("Number of categories must be a positive integer.") + + # 2. Command Construction + cmd = [executable_name] + + if nucleotide: + cmd.append("-nt") + if model: + if model.lower() == 'gtr': + cmd.append("-gtr") + elif model.lower() == 'wag': + cmd.append("-wag") + elif model.lower() in ['jtt', 'jones']: + cmd.append("-jones") + + if gamma: + cmd.append("-gamma") + + if search_thoroughness != "normal": + cmd.append(f"-{search_thoroughness}") + + if no_ml: + cmd.append("-noml") + if no_me: + cmd.append("-nome") + if no_support: + cmd.append("-nosupport") + if sh_test: + cmd.append("-sh") + if no_cat: + cmd.append("-nocat") + if pseudocounts: + cmd.append("-pseudo") + if bionj: + cmd.append("-bionj") + if nj: + cmd.append("-nj") + if quiet: + cmd.append("-quiet") + + if bootstraps is not None: + cmd.extend(["-boot", str(bootstraps)]) + if categories != 20: + cmd.extend(["-cat", str(categories)]) + if min_evolution_rounds is not None: + cmd.extend(["-n", str(min_evolution_rounds)]) + if seed is not None: + cmd.extend(["-seed", str(seed)]) + if constraint_weight is not None: + cmd.extend(["-constraintWeight", str(constraint_weight)]) + + if initial_tree: + cmd.extend(["-intree", str(initial_tree)]) + if initial_tree_round1: + cmd.extend(["-intree1", str(initial_tree_round1)]) + if matrix_file: + cmd.extend(["-matrix", str(matrix_file)]) + if constraints_file: + cmd.extend(["-constraints", str(constraints_file)]) + if log_file: + cmd.extend(["-log", str(log_file)]) + + output_files = {} + tree_output_path = output_tree_file + if output_tree_file: + cmd.extend(["-out", str(output_tree_file)]) + + # Positional argument for alignment file must be last + cmd.append(str(alignment_file)) + + # 3. Subprocess Execution + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + except FileNotFoundError: + raise RuntimeError(f"Executable '{executable_name}' not found. Please ensure FastTree is installed and in your PATH.") + except subprocess.CalledProcessError as e: + logging.error(f"FastTree failed with exit code {e.returncode}") + logging.error(f"Stdout: {e.stdout}") + logging.error(f"Stderr: {e.stderr}") + # Return structured error information + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": {}, + "error": "FastTree execution failed." + } + + # 4. Structured Result Return + if not tree_output_path: + # If no output file was specified, FastTree writes the tree to stdout. + # We capture it and save it to a temporary file for a consistent output format. + with tempfile.NamedTemporaryFile(delete=False, mode='w', suffix=".tre", prefix="fasttree_") as tmp_out: + tmp_out.write(result.stdout) + tree_output_path = Path(tmp_out.name) + output_files["tree_file"] = str(tree_output_path) + else: + output_files["tree_file"] = str(tree_output_path) + + if log_file: + output_files["log_file"] = str(log_file) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fasttree/app/fasttree_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fasttree/app/fasttree_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5382035454556214f302592ff104eee26aa54add --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fasttree/app/fasttree_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_fasttree/app/fasttree_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_fasttree' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fasttree/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fasttree/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fasttree/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fasttree/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fasttree/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f0f9219f1259b7fafa6a7222308882eba4466f6d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fasttree/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-fasttree: + build: . + image: mcp-fasttree:latest + container_name: mcp-fasttree + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=fasttree + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fasttree/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fasttree/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..21d1a55034d86ae50f9df94ad50b2d935d527fa0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fasttree/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - fasttree + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fasttree/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fasttree/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fasttree/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fgbio/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fgbio/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0fba7c013d69f5087a707d9ce0a234c4f581f523 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fgbio/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install fgbio via conda (e.g., from bioconda) +RUN conda install -c bioconda fgbio -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/fgbio_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/fgbio_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/fgbio_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fgbio/app/__pycache__/fgbio_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fgbio/app/__pycache__/fgbio_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0750a88586f385b9fc10c3036538ae630ca0a50a Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fgbio/app/__pycache__/fgbio_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fgbio/app/fgbio_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fgbio/app/fgbio_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0cc4fd3313a203cbd4266384ee9e3c966d6094e6 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fgbio/app/fgbio_server.py @@ -0,0 +1,380 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union +import os + +def run_fgbio_command(command: List[str]): + """Helper to execute fgbio commands and handle errors.""" + try: + # Ensure fgbio is in the path or use a specific path if needed + result = subprocess.run( + command, + capture_output=True, + text=True, + check=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", + "error_message": str(e) + } + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_fgbio' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def fastq_to_bam( + input_fastqs: List[str], + output: str, + sample: str, + library: str, + platform: str = "ILLUMINA", + read_group_id: str = "1", + sort_order: str = "queryname", + predicted_insert_size: Optional[int] = None, + description: Optional[str] = None, + comment: Optional[List[str]] = None, +): + """ + Converts FASTQ files to an unmapped BAM file. + + Args: + input_fastqs: One or two FASTQ files (for single-end or paired-end). + output: The output BAM file. + sample: The sample name. + library: The library name. + platform: The platform (e.g., ILLUMINA). + read_group_id: The read group ID. + sort_order: The sort order for the output BAM. + predicted_insert_size: Predicted average insert size. + description: Read group description. + comment: Comments to add to the BAM header. + """ + for f in input_fastqs: + if not Path(f).exists(): + return {"error": f"Input FASTQ file not found: {f}"} + + cmd = ["fgbio", "FastqToBam", "--input"] + input_fastqs + cmd += ["--output", output, "--sample", sample, "--library", library] + cmd += ["--platform", platform, "--read-group-id", read_group_id, "--sort-order", sort_order] + + if predicted_insert_size is not None: + cmd += ["--predicted-insert-size", str(predicted_insert_size)] + if description: + cmd += ["--description", description] + if comment: + for c in comment: + cmd += ["--comment", c] + + return run_fgbio_command(cmd) + +@mcp.tool() +def extract_umis_from_bam( + input_bam: str, + output: str, + read_structure: List[str], + molecular_index_tags: List[str] = ["RX"], + single_tag: Optional[str] = None, + annotate_unknown_tags: bool = False, +): + """ + Extracts UMIs from reads in a BAM file and stores them in tags. + + Args: + input_bam: The input BAM file. + output: The output BAM file. + read_structure: The read structures (one per read in the template). e.g. ["5M2S+T", "7M1S+T"] + molecular_index_tags: The tag(s) to store the molecular indexes in. + single_tag: If provided, all UMIs are concatenated into this single tag. + annotate_unknown_tags: If true, annotate tags even if they are not molecular indexes. + """ + if not Path(input_bam).exists(): + return {"error": f"Input BAM file not found: {input_bam}"} + + cmd = ["fgbio", "ExtractUmisFromBam", "--input", input_bam, "--output", output] + cmd += ["--read-structure"] + read_structure + cmd += ["--molecular-index-tags"] + molecular_index_tags + + if single_tag: + cmd += ["--single-tag", single_tag] + if annotate_unknown_tags: + cmd += ["--annotate-unknown-tags", "true"] + + return run_fgbio_command(cmd) + +@mcp.tool() +def group_reads_by_umi( + input_bam: str, + output: str, + strategy: str = "adjacency", + edits: int = 1, + min_map_q: int = 1, + family_size_histogram: Optional[str] = None, + assign_tag: str = "MI", +): + """ + Groups reads together that appear to have come from the same original molecule. + + Args: + input_bam: The input BAM file (must be sorted by template or coordinate). + output: The output BAM file. + strategy: The UMI grouping strategy (identity, edit, adjacency). + edits: The number of edits allowed between UMIs. + min_map_q: The minimum mapping quality for a read to be used. + family_size_histogram: Optional file to write family size histogram. + assign_tag: The tag to store the molecular identifier (family ID). + """ + if not Path(input_bam).exists(): + return {"error": f"Input BAM file not found: {input_bam}"} + + cmd = ["fgbio", "GroupReadsByUmi", "--input", input_bam, "--output", output] + cmd += ["--strategy", strategy, "--edits", str(edits), "--min-map-q", str(min_map_q)] + cmd += ["--assign-tag", assign_tag] + + if family_size_histogram: + cmd += ["--family-size-histogram", family_size_histogram] + + return run_fgbio_command(cmd) + +@mcp.tool() +def call_molecular_consensus_reads( + input_bam: str, + output: str, + min_reads: int = 1, + min_input_base_quality: int = 10, + max_reads_per_family: int = 100, + tag: str = "MI", + read_group_id: Optional[str] = None, + sort_order: str = "queryname", +): + """ + Calls consensus sequences from reads grouped by UMI. + + Args: + input_bam: The input BAM file grouped by UMI. + output: The output BAM file of consensus reads. + min_reads: The minimum number of reads to generate a consensus. + min_input_base_quality: The minimum base quality to include a base in consensus calling. + max_reads_per_family: The maximum number of reads to use from any one family. + tag: The tag containing the molecular identifier. + read_group_id: The read group ID to use for the consensus reads. + sort_order: The sort order of the output BAM. + """ + if not Path(input_bam).exists(): + return {"error": f"Input BAM file not found: {input_bam}"} + + cmd = ["fgbio", "CallMolecularConsensusReads", "--input", input_bam, "--output", output] + cmd += ["--min-reads", str(min_reads), "--min-input-base-quality", str(min_input_base_quality)] + cmd += ["--max-reads-per-family", str(max_reads_per_family), "--tag", tag, "--sort-order", sort_order] + + if read_group_id: + cmd += ["--read-group-id", read_group_id] + + return run_fgbio_command(cmd) + +@mcp.tool() +def filter_consensus_reads( + input_bam: str, + output: str, + ref: str, + min_reads: List[int] = [1], + min_base_quality: int = 20, + max_read_error_rate: float = 0.05, + max_base_error_rate: float = 0.1, + max_no_call_fraction: float = 0.2, +): + """ + Filters consensus reads generated by CallMolecularConsensusReads. + + Args: + input_bam: The input BAM file of consensus reads. + output: The output filtered BAM file. + ref: The reference FASTA file. + min_reads: The minimum number of reads supporting the consensus (can be multiple values). + min_base_quality: The minimum base quality for a consensus base. + max_read_error_rate: The maximum error rate for a read to be kept. + max_base_error_rate: The maximum error rate for a single base. + max_no_call_fraction: The maximum fraction of no-calls (N) in a read. + """ + if not Path(input_bam).exists(): + return {"error": f"Input BAM file not found: {input_bam}"} + if not Path(ref).exists(): + return {"error": f"Reference file not found: {ref}"} + + cmd = ["fgbio", "FilterConsensusReads", "--input", input_bam, "--output", output, "--ref", ref] + cmd += ["--min-reads"] + [str(m) for m in min_reads] + cmd += ["--min-base-quality", str(min_base_quality)] + cmd += ["--max-read-error-rate", str(max_read_error_rate)] + cmd += ["--max-base-error-rate", str(max_base_error_rate)] + cmd += ["--max-no-call-fraction", str(max_no_call_fraction)] + + return run_fgbio_command(cmd) + +@mcp.tool() +def clip_bam( + input_bam: str, + output: str, + ref: str, + soft_clip: bool = False, + clip_overlapping_reads: bool = True, + upgrade_clipping: bool = False, + read_structure: Optional[List[str]] = None, +): + """ + Clips reads in a BAM file to remove adapter sequences or overlapping segments. + + Args: + input_bam: The input BAM file. + output: The output BAM file. + ref: The reference FASTA file. + soft_clip: If true, use soft clipping instead of hard clipping. + clip_overlapping_reads: If true, clip overlapping segments of paired-end reads. + upgrade_clipping: If true, upgrade existing clipping. + read_structure: Optional read structures to identify segments to clip. + """ + if not Path(input_bam).exists(): + return {"error": f"Input BAM file not found: {input_bam}"} + if not Path(ref).exists(): + return {"error": f"Reference file not found: {ref}"} + + cmd = ["fgbio", "ClipBam", "--input", input_bam, "--output", output, "--ref", ref] + cmd += ["--soft-clip", str(soft_clip).lower()] + cmd += ["--clip-overlapping-reads", str(clip_overlapping_reads).lower()] + cmd += ["--upgrade-clipping", str(upgrade_clipping).lower()] + + if read_structure: + cmd += ["--read-structure"] + read_structure + + return run_fgbio_command(cmd) + +@mcp.tool() +def sort_bam( + input_bam: str, + output: str, + sort_order: str = "coordinate", + max_records_in_ram: int = 500000, + tmp_dir: Optional[str] = None, +): + """ + Sorts a BAM file. + + Args: + input_bam: The input BAM file. + output: The output sorted BAM file. + sort_order: The order to sort the BAM (coordinate, queryname, random, etc.). + max_records_in_ram: The maximum number of records to keep in RAM. + tmp_dir: Directory for temporary files. + """ + if not Path(input_bam).exists(): + return {"error": f"Input BAM file not found: {input_bam}"} + + cmd = ["fgbio", "SortBam", "--input", input_bam, "--output", output, "--sort-order", sort_order] + cmd += ["--max-records-in-ram", str(max_records_in_ram)] + + if tmp_dir: + cmd += ["--tmp-dir", tmp_dir] + + return run_fgbio_command(cmd) + +@mcp.tool() +def collect_duplication_metrics( + input_bam: str, + output: str, + description: Optional[str] = None, +): + """ + Collects metrics about duplicate reads in a BAM file. + + Args: + input_bam: The input BAM file. + output: The output metrics file. + description: Description of the library/run. + """ + if not Path(input_bam).exists(): + return {"error": f"Input BAM file not found: {input_bam}"} + + cmd = ["fgbio", "CollectDuplicationMetrics", "--input", input_bam, "--output", output] + + if description: + cmd += ["--description", description] + + return run_fgbio_command(cmd) + +@mcp.tool() +def sam_to_fastq( + input_bam: str, + fastq1: str, + fastq2: Optional[str] = None, + interleave: bool = False, + include_non_primary_alignments: bool = False, +): + """ + Converts a BAM/SAM file to FASTQ. + + Args: + input_bam: The input BAM/SAM file. + fastq1: The output FASTQ file for read 1. + fastq2: The output FASTQ file for read 2 (optional). + interleave: If true, interleave R1 and R2 in a single FASTQ file. + include_non_primary_alignments: If true, include non-primary alignments. + """ + if not Path(input_bam).exists(): + return {"error": f"Input BAM file not found: {input_bam}"} + + cmd = ["fgbio", "SamToFastq", "--input", input_bam, "--fastq", fastq1] + + if fastq2: + cmd += ["--fastq2", fastq2] + if interleave: + cmd += ["--interleave", "true"] + if include_non_primary_alignments: + cmd += ["--include-non-primary-alignments", "true"] + + return run_fgbio_command(cmd) + +@mcp.tool() +def zipper_bams( + unmapped_bam: str, + mapped_bam: str, + output: str, + ref: str, + tags_to_reverse: List[str] = ["RX", "OX", "BZ"], + tags_to_revcomp: List[str] = ["RX", "OX", "BZ"], +): + """ + Zips together an unmapped BAM and a mapped BAM to produce a mapped BAM with all tags. + + Args: + unmapped_bam: The unmapped BAM file. + mapped_bam: The mapped BAM file. + output: The output mapped BAM file. + ref: The reference FASTA file. + tags_to_reverse: Tags to reverse when the read is mapped to the negative strand. + tags_to_revcomp: Tags to reverse-complement when the read is mapped to the negative strand. + """ + if not Path(unmapped_bam).exists(): + return {"error": f"Unmapped BAM file not found: {unmapped_bam}"} + if not Path(mapped_bam).exists(): + return {"error": f"Mapped BAM file not found: {mapped_bam}"} + if not Path(ref).exists(): + return {"error": f"Reference file not found: {ref}"} + + cmd = ["fgbio", "ZipperBams", "--unmapped", unmapped_bam, "--mapped", mapped_bam, "--output", output, "--ref", ref] + cmd += ["--tags-to-reverse"] + tags_to_reverse + cmd += ["--tags-to-revcomp"] + tags_to_revcomp + + return run_fgbio_command(cmd) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fgbio/app/fgbio_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fgbio/app/fgbio_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9dd2b20a11dcdacf5968179293e9ef520f181ede --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fgbio/app/fgbio_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_fgbio/app/fgbio_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_fgbio' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fgbio/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fgbio/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fgbio/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fgbio/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fgbio/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7487134571869fa24811a5d1a88a41383b58b844 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fgbio/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-fgbio: + build: . + image: mcp-fgbio:latest + container_name: mcp-fgbio + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=fgbio + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fgbio/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fgbio/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e88743b4cc21e314b6e4f5bd22a99f0aa605b896 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fgbio/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - fgbio + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fgbio/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fgbio/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_fgbio/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_filechunkio/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_filechunkio/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..218ba073ed52e41b06724a0b5cbe6e2989298445 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_filechunkio/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install filechunkio via conda (e.g., from bioconda) +RUN conda install -c bioconda filechunkio -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/filechunkio_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/filechunkio_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/filechunkio_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_filechunkio/app/__pycache__/filechunkio_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_filechunkio/app/__pycache__/filechunkio_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5221b6ef35700c9b4a920b4699bbc15201024b6f Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_filechunkio/app/__pycache__/filechunkio_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_filechunkio/app/filechunkio_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_filechunkio/app/filechunkio_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ee4d203d006289dfa055fcf0a6ef4d75a86137dc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_filechunkio/app/filechunkio_server.py @@ -0,0 +1,169 @@ +import math +import os +import subprocess +import tempfile +from pathlib import Path +from typing import List + +# @mcp.tool is a placeholder for the actual decorator. +# The user specified "NO NEED to import mcp". + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_filechunkio' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def create_chunks( + input_file: Path, + output_dir: Path, + chunk_size_mb: int = 10, + prefix: str = "chunk_" +): + """ + Splits a large file into smaller, fixed-size chunks. + + This tool provides a command-line-like interface for the 'filechunkio' library, + which itself does not have a CLI. It is useful for preparing large files for + multipart uploads or parallel processing. The execution requires a Python + environment with the 'filechunkio' library installed. + + Args: + input_file: Path to the large file to be split. + output_dir: Directory to save the output chunk files. It will be created if it doesn't exist. + chunk_size_mb: The size of each chunk in megabytes (MB). Must be a positive integer. + prefix: A string to prefix each output chunk file name. + """ + # --- Input Validation --- + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found or is not a regular file: {input_file}") + + if chunk_size_mb <= 0: + raise ValueError("chunk_size_mb must be a positive integer.") + + # --- File Path Handling --- + # The output directory is created within the executed script to ensure it's handled + # by the execution environment, but we can also create it here for early validation. + output_dir.mkdir(parents=True, exist_ok=True) + + # --- Dynamic Script Generation --- + # This approach adheres to the MCP pattern of using subprocess.run by creating a + # temporary script that utilizes the filechunkio library. + script_content = f""" +import math +import os +import sys +from pathlib import Path + +try: + from filechunkio import FileChunkIO +except ImportError: + sys.stderr.write("Error: The 'filechunkio' library is not installed in the Python environment.\\n") + sys.exit(1) + +def main(): + input_file = Path('{input_file.resolve()}') + output_dir = Path('{output_dir.resolve()}') + chunk_size_mb = {chunk_size_mb} + prefix = '{prefix}' + + output_dir.mkdir(parents=True, exist_ok=True) + + chunk_size_bytes = chunk_size_mb * 1024 * 1024 + file_size = os.path.getsize(input_file) + + if file_size == 0: + print("Input file is empty. No chunks will be created.") + print("---OUTPUT FILES---") + return + + num_chunks = int(math.ceil(file_size / float(chunk_size_bytes))) + + output_files = [] + print(f"Splitting file '{{input_file.name}}' ({{file_size}} bytes) into {{num_chunks}} chunks of ~{{chunk_size_mb}} MB.") + + for i in range(num_chunks): + offset = chunk_size_bytes * i + bytes_to_read = min(chunk_size_bytes, file_size - offset) + + output_chunk_path = output_dir / f"{{prefix}}{{i:04d}}.part" + + try: + with FileChunkIO(str(input_file), 'r', offset=offset, bytes=bytes_to_read) as chunk: + with open(output_chunk_path, 'wb') as chunk_out: + # Read in smaller blocks to handle memory efficiently for large chunks + buffer_size = 1024 * 1024 # 1MB buffer + while True: + data = chunk.read(buffer_size) + if not data: + break + chunk_out.write(data) + + output_files.append(str(output_chunk_path)) + print(f"Successfully created chunk: {{output_chunk_path}}") + except Exception as e: + sys.stderr.write(f"Failed to create chunk {{i}}: {{e}}\\n") + sys.exit(1) + + # Print a separator and then the list of output files for easy parsing + print("---OUTPUT FILES---") + for f in output_files: + print(f) + +if __name__ == "__main__": + main() +""" + + script_path = None + command = [] + try: + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".py") as tmp_script: + tmp_script.write(script_content) + script_path = Path(tmp_script.name) + + # --- Subprocess Execution --- + command = ["python", str(script_path)] + + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + + stdout = process.stdout + stderr = process.stderr + + # --- Structured Result Return --- + # Parse stdout to find the list of output files + output_files_list = [] + if "---OUTPUT FILES---" in stdout: + _, file_list_str = stdout.split("---OUTPUT FILES---", 1) + for line in file_list_str.strip().splitlines(): + if line.strip(): + p = Path(line.strip()) + if p.exists(): + output_files_list.append(str(p)) + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files_list + } + + except subprocess.CalledProcessError as e: + # Capture output even on failure and return a structured error + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + finally: + # Clean up the temporary script + if script_path and script_path.exists(): + script_path.unlink() + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_filechunkio/app/filechunkio_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_filechunkio/app/filechunkio_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..57911c2567b81244f307a2add4940af38b1b8d73 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_filechunkio/app/filechunkio_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_filechunkio/app/filechunkio_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_filechunkio' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_filechunkio/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_filechunkio/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_filechunkio/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_filechunkio/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_filechunkio/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..329e95f2fbfa7ff6fddaf3de13cbf6c0a94d967a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_filechunkio/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-filechunkio: + build: . + image: mcp-filechunkio:latest + container_name: mcp-filechunkio + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=filechunkio + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_filechunkio/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_filechunkio/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a0fcde106db38d79d05eeacc6031896f25a0e022 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_filechunkio/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - filechunkio + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_filechunkio/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_filechunkio/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_filechunkio/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_flye/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_flye/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a1e9da8ed252396478d9cfa3426d092388070c5a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_flye/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install flye via conda (e.g., from bioconda) +RUN conda install -c bioconda flye -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/flye_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/flye_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/flye_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_flye/app/__pycache__/flye_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_flye/app/__pycache__/flye_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..03dd24d1c9e9f08521e328103723bc86099ef5ac Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_flye/app/__pycache__/flye_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_flye/app/flye_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_flye/app/flye_server.py new file mode 100644 index 0000000000000000000000000000000000000000..843e9cebd630a3b0a648fc5c97f3665cfea606db --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_flye/app/flye_server.py @@ -0,0 +1,193 @@ +import subprocess +import logging +import shutil +from pathlib import Path +from typing import List, Optional, Literal + +# In a real MCP environment, the mcp package would be available. +# For this standalone script, we define a placeholder decorator. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_flye' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def flye_assemble( + reads: List[Path], + out_dir: Path, + read_type: Literal["pacbio-raw", "pacbio-corr", "pacbio-hifi", "nano-raw", "nano-corr", "nano-hq"], + genome_size: Optional[str] = None, + threads: int = 1, + iterations: int = 1, + meta: bool = False, + polish_target: Optional[Path] = None, + min_overlap: Optional[int] = None, + keep_haplotypes: bool = False, + debug: bool = False, + scaffold: bool = False, + resume: bool = False, + resume_from: Optional[str] = None, + stop_after: Optional[str] = None, + read_error: Optional[float] = None, + extra_params: Optional[str] = None, +): + """ + Runs the Flye assembler for long-read sequencing data. + + Flye is a de novo assembler for single-molecule sequencing reads, such as those + produced by PacBio and Oxford Nanopore Technologies. It can handle various + input read types and is suitable for assembling genomes of varying complexity, + including metagenomes. + + Args: + reads: A list of input read files (FASTA/FASTQ, can be gzipped). + out_dir: The path to the output directory where results will be stored. + read_type: The type of input reads. + genome_size: Estimated genome size (e.g., '5m', '2.6g'). + threads: Number of threads to use for the assembly. + iterations: Number of polishing iterations to perform. + meta: Enables metagenome assembly mode. + polish_target: Path to reads for polishing (optional, uses input reads if not set). + min_overlap: Minimum overlap length for contig assembly (default: auto). + keep_haplotypes: Do not collapse alternative haplotypes. + debug: Enable debug output for troubleshooting. + scaffold: Scaffold assembly using the assembly graph. + resume: Resume a previously failed or stopped assembly. + resume_from: Resume from a specific stage of the assembly. + stop_after: Stop the assembly after a specific stage. + read_error: Override the estimated read error rate (e.g., 0.03). + extra_params: Extra configuration parameters to pass to Flye. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of + paths to the primary output files. + """ + # 1. Input validation + if not shutil.which("flye"): + raise RuntimeError("Flye executable not found in PATH.") + + if not reads: + raise ValueError("At least one input read file must be provided.") + + for read_file in reads: + if not read_file.is_file(): + raise FileNotFoundError(f"Input read file not found: {read_file}") + + if polish_target and not polish_target.is_file(): + raise FileNotFoundError(f"Polish target file not found: {polish_target}") + + if threads <= 0: + raise ValueError("Number of threads must be a positive integer.") + + if iterations < 0: + raise ValueError("Number of iterations cannot be negative.") + + # 2. Command construction + cmd = ["flye"] + + # Add read type and files + cmd.append(f"--{read_type}") + cmd.extend([str(p) for p in reads]) + + # Add required output directory + cmd.extend(["--out-dir", str(out_dir)]) + + # Add optional arguments + if genome_size: + cmd.extend(["--genome-size", genome_size]) + + cmd.extend(["--threads", str(threads)]) + cmd.extend(["--iterations", str(iterations)]) + + if meta: + cmd.append("--meta") + + if polish_target: + cmd.extend(["--polish-target", str(polish_target)]) + + if min_overlap is not None: + if min_overlap <= 0: + raise ValueError("min_overlap must be a positive integer.") + cmd.extend(["--min-overlap", str(min_overlap)]) + + if keep_haplotypes: + cmd.append("--keep-haplotypes") + + if debug: + cmd.append("--debug") + + if scaffold: + cmd.append("--scaffold") + + if resume: + cmd.append("--resume") + + if resume_from: + cmd.extend(["--resume-from", resume_from]) + + if stop_after: + cmd.extend(["--stop-after", stop_after]) + + if read_error is not None: + if not (0 < read_error < 1): + raise ValueError("read_error must be a float between 0 and 1.") + cmd.extend(["--read-error", str(read_error)]) + + if extra_params: + # Flye expects extra params as a single string, so we don't split it. + cmd.extend(["--extra-params", extra_params]) + + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + # 3. Subprocess execution and error handling + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + except subprocess.CalledProcessError as e: + logging.error(f"Flye execution failed with exit code {e.returncode}") + logging.error(f"Stderr: {e.stderr}") + logging.error(f"Stdout: {e.stdout}") + # Return structured error information + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Flye failed with exit code {e.returncode}", + "output_files": [] + } + + # 4. Structured result return + output_files = [] + expected_outputs = [ + "assembly.fasta", + "assembly_graph.gfa", + "assembly_info.txt", + "flye.log", + "params.json" + ] + for f in expected_outputs: + output_path = out_dir / f + if output_path.exists(): + output_files.append(str(output_path)) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_flye/app/flye_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_flye/app/flye_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..20d946f84dfc28d773e5625f3c23b001542a81f8 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_flye/app/flye_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_flye/app/flye_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_flye' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_flye/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_flye/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_flye/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_flye/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_flye/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b9da3a732c61cb3c8fd57969897cad39e5e8e0f6 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_flye/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - flye + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_flye/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_flye/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_flye/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_foldseek/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_foldseek/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_foldseek/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4-spark/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4-spark/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c4249400724afc32e3e4276ec8689774d63f11a0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4-spark/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install gatk4-spark via conda (e.g., from bioconda) +RUN conda install -c bioconda gatk4-spark -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/gatk4-spark_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/gatk4-spark_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/gatk4-spark_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4-spark/app/__pycache__/gatk4-spark_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4-spark/app/__pycache__/gatk4-spark_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8c7dafe8d8ee57b878a6e23ea2947a8cf4839dda Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4-spark/app/__pycache__/gatk4-spark_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4-spark/app/gatk4-spark_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4-spark/app/gatk4-spark_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e3fbf97c016a98d8b8a12af1f4f6bdb596265f9c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4-spark/app/gatk4-spark_server.py @@ -0,0 +1,203 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_gatk4_spark' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def gatk_tool_execute( + tool_name: str, + tool_args: List[str], + java_options: Optional[str] = None, + gatk_config_file: Optional[str] = None, + spark_runner: Optional[str] = None, + spark_master: Optional[str] = None, + extra_spark_args: Optional[List[str]] = None, +) -> Dict[str, Any]: + """ + Execute a GATK4 tool, including Spark-based tools. + + Args: + tool_name: The name of the GATK tool to run (e.g., 'PrintReads', 'HaplotypeCaller', 'PrintReadsSpark'). + tool_args: A list of arguments for the specific GATK tool (e.g., ['-I', 'input.bam', '-O', 'output.bam']). + java_options: Optional JVM arguments (e.g., '-Xmx4G -XX:+PrintGCDetails'). + gatk_config_file: Optional path to a GATK configuration file. + spark_runner: For Spark tools, specify the runner ('LOCAL' or 'SPARK'). + spark_master: For Spark tools, specify the master URL (e.g., 'local[*]', 'spark://host:port'). + extra_spark_args: Additional Spark-specific arguments (e.g., ['--num-executors', '5']). + """ + cmd = ["gatk"] + + # Global GATK options + if java_options: + cmd.extend(["--java-options", java_options]) + + if gatk_config_file: + config_path = Path(gatk_config_file) + if not config_path.exists(): + return {"error": f"GATK config file not found: {gatk_config_file}"} + cmd.extend(["--gatk-config-file", str(config_path)]) + + # The tool to run + cmd.append(tool_name) + + # Tool-specific arguments + cmd.extend(tool_args) + + # Spark-specific arguments (separated by --) + spark_args = [] + if spark_runner: + if spark_runner not in ["LOCAL", "SPARK"]: + return {"error": "spark_runner must be either 'LOCAL' or 'SPARK'"} + spark_args.extend(["--spark-runner", spark_runner]) + + if spark_master: + spark_args.extend(["--spark-master", spark_master]) + + if extra_spark_args: + spark_args.extend(extra_spark_args) + + if spark_args: + cmd.append("--") + cmd.extend(spark_args) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "failed" + } + except FileNotFoundError: + return {"error": "The 'gatk' executable was not found in the system PATH."} + +@mcp.tool() +def gatk_list_tools() -> Dict[str, Any]: + """ + List all available GATK4 tools. + """ + cmd = ["gatk", "--list"] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def gatk_tool_help(tool_name: str) -> Dict[str, Any]: + """ + Get detailed help and parameter information for a specific GATK tool. + + Args: + tool_name: The name of the GATK tool (e.g., 'HaplotypeCaller'). + """ + cmd = ["gatk", tool_name, "--help"] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def gatk_run_spark_local( + tool_name: str, + tool_args: List[str], + parallelism: int = 1, + java_options: Optional[str] = None +) -> Dict[str, Any]: + """ + Convenience tool to run a GATK Spark tool on the local machine with specified parallelism. + + Args: + tool_name: The name of the Spark tool (e.g., 'PrintReadsSpark'). + tool_args: List of tool arguments. + parallelism: Number of local threads to use (default 1). Use -1 for all available cores. + java_options: Optional JVM arguments. + """ + if parallelism == 0: + return {"error": "Parallelism must be a positive integer or -1 for all cores."} + + master_str = f"local[{parallelism}]" if parallelism > 0 else "local[*]" + + return gatk_tool_execute( + tool_name=tool_name, + tool_args=tool_args, + java_options=java_options, + spark_runner="LOCAL", + spark_master=master_str + ) + +@mcp.tool() +def gatk_run_spark_cluster( + tool_name: str, + tool_args: List[str], + spark_master: str, + num_executors: int = 1, + executor_cores: int = 1, + executor_memory: str = "1g", + java_options: Optional[str] = None +) -> Dict[str, Any]: + """ + Execute a GATK Spark tool on an existing Spark cluster. + + Args: + tool_name: The name of the Spark tool. + tool_args: List of tool arguments. + spark_master: The master URL of the Spark cluster. + num_executors: Number of executors to request. + executor_cores: Number of cores per executor. + executor_memory: Memory per executor (e.g., '4g'). + java_options: Optional JVM arguments. + """ + if num_executors < 1: + return {"error": "num_executors must be at least 1"} + if executor_cores < 1: + return {"error": "executor_cores must be at least 1"} + + extra_spark_args = [ + "--num-executors", str(num_executors), + "--executor-cores", str(executor_cores), + "--executor-memory", executor_memory + ] + + return gatk_tool_execute( + tool_name=tool_name, + tool_args=tool_args, + java_options=java_options, + spark_runner="SPARK", + spark_master=spark_master, + extra_spark_args=extra_spark_args + ) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4-spark/app/gatk4-spark_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4-spark/app/gatk4-spark_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e5449d8c3a2070cc1b4ae71372760f443f468846 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4-spark/app/gatk4-spark_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gatk4-spark/app/gatk4-spark_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_gatk4_spark' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4-spark/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4-spark/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4-spark/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4-spark/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4-spark/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b5495f3900987f73800421d0e2927d8d29b99a2e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4-spark/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-gatk4-spark: + build: . + image: mcp-gatk4-spark:latest + container_name: mcp-gatk4-spark + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=gatk4-spark + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4-spark/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4-spark/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..459afcd8526bfe631417b2bb47ef2eaca1e64c96 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4-spark/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - gatk4-spark + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4-spark/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4-spark/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gatk4-spark/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genecircuitry/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genecircuitry/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..213a7bc07c5ea131bfbcb0ebc2ed9aa890fbd852 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genecircuitry/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install genecircuitry via conda (e.g., from bioconda) +RUN conda install -c bioconda genecircuitry -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/genecircuitry_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/genecircuitry_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/genecircuitry_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genecircuitry/app/__pycache__/genecircuitry_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genecircuitry/app/__pycache__/genecircuitry_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f1f72fe05d3c2b0d17618020014f758e61808c2e Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genecircuitry/app/__pycache__/genecircuitry_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genecircuitry/app/genecircuitry_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genecircuitry/app/genecircuitry_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0270b930fb0ae560d203b32f50ba5efd48c34616 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genecircuitry/app/genecircuitry_server.py @@ -0,0 +1,149 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided by the MCP framework. +def tool(func): + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + return wrapper + +mcp = type("mcp", (), {"tool": tool}) + +@mcp.tool +def run_pipeline( + input_file: Path, + output_dir: Path, + steps: Optional[List[str]] = None, + skip_celloracle: bool = False, + skip_hotspot: bool = False, + seed: Optional[int] = None, + n_jobs: int = 1, + min_genes: Optional[int] = None, + cluster_key_stratification: Optional[str] = None, + parallel: bool = False, +): + """ + Runs the complete genecircuitry analysis pipeline for TRN analysis from single-cell data. + + This tool integrates Scanpy for preprocessing, CellOracle for GRN inference, + and Hotspot for identifying embedding-aware gene modules. + """ + # --- Input Validation --- + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + if n_jobs <= 0: + raise ValueError("n_jobs must be a positive integer.") + + allowed_steps = [ + "load", "preprocessing", "stratification", "clustering", + "celloracle", "hotspot", "grn_analysis", "summary" + ] + if steps: + for step in steps: + if step not in allowed_steps: + raise ValueError( + f"Invalid step '{step}'. Allowed steps are: {', '.join(allowed_steps)}" + ) + + if parallel and not cluster_key_stratification: + raise ValueError( + "When --parallel is enabled, --cluster-key-stratification must be provided." + ) + + # --- File Path Handling --- + try: + output_dir.mkdir(parents=True, exist_ok=True) + except OSError as e: + raise OSError(f"Failed to create output directory {output_dir}: {e}") + + # --- Command Construction --- + # The documentation suggests the main entry point is a script, but a `genecircuitry` + # CLI is also mentioned. We will assume the installed package provides this entry point. + cmd = [ + "genecircuitry", + "--input", str(input_file), + "--output", str(output_dir), + ] + + if steps: + cmd.append("--steps") + cmd.extend(steps) + + if skip_celloracle: + cmd.append("--skip-celloracle") + + if skip_hotspot: + cmd.append("--skip-hotspot") + + if seed is not None: + cmd.extend(["--seed", str(seed)]) + + cmd.extend(["--n-jobs", str(n_jobs)]) + + if min_genes is not None: + cmd.extend(["--min-genes", str(min_genes)]) + + if cluster_key_stratification: + cmd.extend(["--cluster-key-stratification", cluster_key_stratification]) + + if parallel: + cmd.append("--parallel") + + command_executed = " ".join(cmd) + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + cwd=output_dir, # Run from the output directory to keep logs/temp files contained + ) + except FileNotFoundError: + return { + "error": "genecircuitry command not found. Please ensure the tool is installed and in the system's PATH.", + "command_executed": command_executed, + "stdout": "", + "stderr": "Executable not found.", + } + except subprocess.CalledProcessError as e: + return { + "error": "GeneCircuitry pipeline failed.", + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + } + + # --- Structured Result Return --- + # Based on the documentation, these are the expected primary output files. + # The exact files generated may depend on the steps run. + output_files = { + "preprocessed_data": str(output_dir / "preprocessed_adata.h5ad"), + "analysis_summary": str(output_dir / "analysis_summary.txt"), + "celloracle_object": str(output_dir / "celloracle" / "oracle_object.celloracle.oracle"), + "celloracle_links": str(output_dir / "celloracle" / "grn_links.celloracle.links"), + "hotspot_autocorrelation": str(output_dir / "hotspot" / "autocorrelation_results.csv"), + "hotspot_significant_genes": str(output_dir / "hotspot" / "significant_genes.csv"), + "hotspot_gene_modules": str(output_dir / "hotspot" / "gene_modules.csv"), + "qc_figures_dir": str(output_dir / "figures" / "qc"), + "grn_analysis_figures_dir": str(output_dir / "figures" / "grn_analysis"), + } + + # Filter out files that might not have been created + final_output_files = { + key: path for key, path in output_files.items() if Path(path).exists() or Path(path).is_dir() + } + + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": final_output_files, + } \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genecircuitry/app/genecircuitry_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genecircuitry/app/genecircuitry_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0bd36d3ac01c251442b1e86708eb75d823bd8bb8 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genecircuitry/app/genecircuitry_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/app/genecircuitry_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_genecircuitry' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genecircuitry/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genecircuitry/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genecircuitry/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genecircuitry/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genecircuitry/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..4305260b7f842346d4014789333765ec1e58a88d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genecircuitry/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-genecircuitry: + build: . + image: mcp-genecircuitry:latest + container_name: mcp-genecircuitry + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=genecircuitry + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genecircuitry/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genecircuitry/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c13817ea451b574b9afccc6bc309ff83684f1444 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genecircuitry/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - genecircuitry + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genecircuitry/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genecircuitry/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genecircuitry/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genomepy/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genomepy/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4a3f716070b1b34672491acdda037e2451615282 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genomepy/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install genomepy via conda (e.g., from bioconda) +RUN conda install -c bioconda genomepy -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/genomepy_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/genomepy_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/genomepy_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genomepy/app/__pycache__/genomepy_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genomepy/app/__pycache__/genomepy_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c44b18c70497330c087dbe60b7f86c9fe0de580a Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genomepy/app/__pycache__/genomepy_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genomepy/app/genomepy_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genomepy/app/genomepy_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4db1d3aff1accbe9398df97ff4055df73796b42a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genomepy/app/genomepy_server.py @@ -0,0 +1,354 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Literal, Dict, Any + +# Define common types for reusability and clarity +GenomeMaskType = Literal["hard", "soft", "none"] +ProviderType = Literal["GENCODE", "Ensembl", "UCSC", "NCBI", "Local", "URL"] +UCSCAnnotationType = Literal["ncbiRefSeq", "refGene", "ensGene", "knownGene"] +PluginName = Literal["blacklist", "bowtie2", "bwa", "gmap", "hisat2", "minimap2", "star"] + +def _run_genomepy_command( + command_args: List[str], + expected_output_paths: Optional[List[Path]] = None +) -> Dict[str, Any]: + """ + Helper function to run genomepy commands and handle output/errors. + """ + cmd = ["genomepy"] + command_args + command_executed = " ".join(map(str, cmd)) + stdout = "" + stderr = "" + output_files_found: List[str] = [] + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + stdout = result.stdout + stderr = result.stderr + + if expected_output_paths: + for p in expected_output_paths: + if p.exists(): + output_files_found.append(str(p.resolve())) + + 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": output_files_found, + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "genomepy command not found. Please ensure it is installed and in your PATH.", + "error": "genomepy executable not found", + "output_files": output_files_found, + } + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files_found, + } + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_genomepy' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def get_version() -> Dict[str, Any]: + """ + Show the genomepy version. + """ + return _run_genomepy_command(["--version"]) + +@mcp.tool() +def search( + term: str, + provider: Optional[ProviderType] = None, + size: bool = False, +) -> Dict[str, Any]: + """ + Search for genomes and gene annotations by name, taxonomy ID, or assembly accession ID. + + Args: + term: The search term (e.g., genome name, taxonomy ID, assembly accession ID). + provider: Limit the search result to a specific provider (e.g., "UCSC", "Ensembl"). + size: If True, get the absolute size of each genome (this option slows down the search). + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + if not term: + raise ValueError("Search term cannot be empty.") + + cmd_args = ["search", term] + if provider: + cmd_args.extend(["--provider", provider]) + if size: + cmd_args.append("--size") + + return _run_genomepy_command(cmd_args) + +@mcp.tool() +def install( + name_or_path_or_url: str, + annotation: bool = False, + provider: Optional[ProviderType] = None, + genomes_dir: Optional[Path] = None, + regex: Optional[str] = None, + no_match: bool = False, + mask: GenomeMaskType = "soft", + bgzip: bool = False, + localname: Optional[str] = None, + url_to_annotation: Optional[str] = None, + local_path_to_annotation: Optional[Path] = None, + force: bool = False, + threads: int = 8, + ucsc_annotation: Optional[UCSCAnnotationType] = None, +) -> Dict[str, Any]: + """ + Install a genome and optionally run active plugins. + Supports downloading from providers (Ensembl, UCSC, NCBI, GENCODE), URLs, or local files. + + Args: + name_or_path_or_url: The genome name, URL, or local file path to install. + annotation: If True, download gene annotation files along with the genome. + provider: Specify the provider by name (e.g., "UCSC", "Ensembl"). Required for URL/Local. + genomes_dir: Directory where genomes will be saved. Defaults to ~/.local/share/genomes/. + regex: A regular expression to filter for matching sequences (e.g., 'chr[0-9XY]+$'). + no_match: Use with --regex to filter for non-matching sequences. + mask: Masking type for genome sequences. Choices: "hard" (ACNNN), "soft" (ACgtN), "none" (ACGTN). + bgzip: If True, compress the downloaded data using bgzip. + localname: Local name for the genome (used when provider is URL or Local). + url_to_annotation: URL to an annotation file (used with --provider URL). + local_path_to_annotation: Filepath to a local annotation file (used with --provider Local). + force: If True, overwrite local files if they exist. + threads: Number of threads to use for aligner index creation (if plugins are active). + ucsc_annotation: Specific UCSC annotation type to download (e.g., "refGene", "ncbiRefSeq"). + Only applicable when --provider UCSC. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + if not name_or_path_or_url: + raise ValueError("Genome name, path, or URL cannot be empty.") + if threads < 1: + raise ValueError("Number of threads must be a positive integer.") + if no_match and not regex: + raise ValueError("--no-match requires --regex to be set.") + if url_to_annotation and provider != "URL": + raise ValueError("--URL-to-annotation can only be used with --provider URL.") + if local_path_to_annotation and provider != "Local": + raise ValueError("--Local-path-to-annotation can only be used with --provider Local.") + if ucsc_annotation and provider != "UCSC": + raise ValueError("--UCSC-annotation can only be used with --provider UCSC.") + if local_path_to_annotation and not Path(local_path_to_annotation).is_file(): + raise FileNotFoundError(f"Local annotation file not found: {local_path_to_annotation}") + + cmd_args = ["install", name_or_path_or_url] + + if annotation: + cmd_args.append("--annotation") + if provider: + cmd_args.extend(["--provider", provider]) + + final_genomes_dir = genomes_dir if genomes_dir else Path.home() / ".local" / "share" / "genomes" + final_genomes_dir.mkdir(parents=True, exist_ok=True) + cmd_args.extend(["--genomes_dir", str(final_genomes_dir)]) + + if regex: + cmd_args.extend(["--regex", regex]) + if no_match: + cmd_args.append("--no-match") + if mask != "soft": + cmd_args.extend(["--mask", mask]) + if bgzip: + cmd_args.append("--bgzip") + if localname: + cmd_args.extend(["--localname", localname]) + if url_to_annotation: + cmd_args.extend(["--URL-to-annotation", url_to_annotation]) + if local_path_to_annotation: + cmd_args.extend(["--Local-path-to-annotation", str(local_path_to_annotation)]) + if force: + cmd_args.append("--force") + if threads != 8: + cmd_args.extend(["--threads", str(threads)]) + if ucsc_annotation: + cmd_args.extend(["--UCSC-annotation", ucsc_annotation]) + + # Determine the local name for the genome, which forms the subfolder name + genome_local_name: str + if localname: + genome_local_name = localname + elif provider in ["Local", "URL"]: + base_name = Path(name_or_path_or_url).name + # Remove common genome file extensions to get the base name genomepy uses for folders + suffixes_to_remove = [".fa.gz", ".fasta.gz", ".fa", ".fasta", ".tar.gz", ".tar"] + for suffix in suffixes_to_remove: + if base_name.endswith(suffix): + base_name = base_name[:-len(suffix)] + break + genome_local_name = base_name + else: + genome_local_name = name_or_path_or_url + + # Predict potential output files + expected_output_paths: List[Path] = [] + genome_output_folder = final_genomes_dir / genome_local_name + + fasta_filename = f"{genome_local_name}.fa.gz" if bgzip else f"{genome_local_name}.fa" + expected_output_paths.append(genome_output_folder / fasta_filename) + expected_output_paths.append(genome_output_folder / f"{fasta_filename}.fai") # pyfaidx index + expected_output_paths.append(genome_output_folder / "README.txt") # Reproducibility file + + if annotation: + expected_output_paths.append(genome_output_folder / f"{genome_local_name}.annotation.gtf") + expected_output_paths.append(genome_output_folder / f"{genome_local_name}.annotation.bed") + + return _run_genomepy_command(cmd_args, expected_output_paths=expected_output_paths) + +@mcp.tool() +def annotation( + genome_name: str, + provider: Optional[ProviderType] = None, + genomes_dir: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Show the first lines of each available gene annotation for a specified genome. + + Args: + genome_name: The name of the genome for which to inspect annotations. + provider: Limit to a specific provider. + genomes_dir: Directory where genomes are stored. Defaults to ~/.local/share/genomes/. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + if not genome_name: + raise ValueError("Genome name cannot be empty.") + + cmd_args = ["annotation", genome_name] + if provider: + cmd_args.extend(["--provider", provider]) + if genomes_dir: + if not genomes_dir.is_dir(): + raise FileNotFoundError(f"Genomes directory not found: {genomes_dir}") + cmd_args.extend(["--genomes_dir", str(genomes_dir)]) + + return _run_genomepy_command(cmd_args) + +@mcp.tool() +def clean() -> Dict[str, Any]: + """ + Remove local provider data and cached genome lists. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + return _run_genomepy_command(["clean"]) + +@mcp.tool() +def config_generate() -> Dict[str, Any]: + """ + Generate a default genomepy configuration file (~/.config/genomepy/genomepy.yaml). + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + config_file = Path.home() / ".config" / "genomepy" / "genomepy.yaml" + return _run_genomepy_command(["config", "generate"], expected_output_paths=[config_file]) + +@mcp.tool() +def genomes( + provider: Optional[ProviderType] = None, + size: bool = False, +) -> Dict[str, Any]: + """ + List available genomes, optionally filtered by provider and including genome sizes. + + Args: + provider: Limit the genome list to a specific provider. + size: If True, get the absolute size of each genome (this option slows down the search). + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + cmd_args = ["genomes"] + if provider: + cmd_args.extend(["--provider", provider]) + if size: + cmd_args.append("--size") + + return _run_genomepy_command(cmd_args) + +@mcp.tool() +def plugin_list() -> Dict[str, Any]: + """ + List currently enabled genomepy plugins. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + return _run_genomepy_command(["plugin", "list"]) + +@mcp.tool() +def plugin_enable( + plugin_name: PluginName, +) -> Dict[str, Any]: + """ + Enable a genomepy plugin. + Plugins are optional steps executed after installing an assembly (e.g., blacklist, aligner indexes). + + Args: + plugin_name: The name of the plugin to enable (e.g., "blacklist", "bwa", "star"). + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + if not plugin_name: + raise ValueError("Plugin name cannot be empty.") + + return _run_genomepy_command(["plugin", "enable", plugin_name]) + +@mcp.tool() +def plugin_disable( + plugin_name: PluginName, +) -> Dict[str, Any]: + """ + Disable a genomepy plugin. + + Args: + plugin_name: The name of the plugin to disable. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + if not plugin_name: + raise ValueError("Plugin name cannot be empty.") + + return _run_genomepy_command(["plugin", "disable", plugin_name]) + +@mcp.tool() +def providers() -> Dict[str, Any]: + """ + List all available genome providers. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + return _run_genomepy_command(["providers"]) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genomepy/app/genomepy_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genomepy/app/genomepy_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..cb35ab9d631cdf25a8939665f1ac2604032e38cf --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genomepy/app/genomepy_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/app/genomepy_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_genomepy' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genomepy/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genomepy/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genomepy/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genomepy/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genomepy/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..3455f14b494854c25f1106be5051c5bd220482dc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genomepy/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-genomepy: + build: . + image: mcp-genomepy:latest + container_name: mcp-genomepy + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=genomepy + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genomepy/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genomepy/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..79d3cd708200e3e876e83229c304fb979ca021d3 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genomepy/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - genomepy + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genomepy/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genomepy/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_genomepy/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gridss/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gridss/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gridss/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gsmap/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gsmap/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..514e5584fe2c6db4fd32bd51397c2c51d01e1aaa --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gsmap/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install gsmap via conda (e.g., from bioconda) +RUN conda install -c bioconda gsmap -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY gsmap_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/gsmap_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/gsmap_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gsmap/app/__pycache__/gsmap_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gsmap/app/__pycache__/gsmap_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..91d133096a4cf43868152b26aca864b94fe33273 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gsmap/app/__pycache__/gsmap_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gsmap/app/gsmap_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gsmap/app/gsmap_server.py new file mode 100644 index 0000000000000000000000000000000000000000..07ea0671fd4f98ea12a2a2eec1e793f7bd6b79c8 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gsmap/app/gsmap_server.py @@ -0,0 +1,643 @@ +import subprocess +import logging +import tempfile +from pathlib import Path +from typing import Optional, List + +# Configure logging +logging.basicConfig(level=logging.INFO) + +# Mock mcp.tool decorator for standalone execution +class mcp: + def tool(func): + return func + +@mcp.tool +def gsmap_quick_mode( + h5ad_path: Path, + gwas_path: Path, + output_dir: Path, + species: str = "human", + n_jobs: int = 1, + chunksize: int = 1, + device: str = "cpu", + ld_path: Optional[Path] = None, + weight_path: Optional[Path] = None, + annotation_path: Optional[Path] = None, + n_causal: int = 1000, + n_causal_annotation: int = 1000, + chrom: str = "all", + non_negative: bool = False, + print_process: bool = False, + find_latent_representations_args: Optional[str] = None, + latent_to_gene_args: Optional[str] = None, + generate_ldscore_args: Optional[str] = None, + spatial_ldsc_args: Optional[str] = None, + cauchy_combination_args: Optional[str] = None, + report_args: Optional[str] = None, +) -> dict: + """ + Run the entire gsMap pipeline in quick mode, utilizing pre-computed weights for faster execution. + """ + # Input validation + if not h5ad_path.exists(): + raise FileNotFoundError(f"Input h5ad file not found: {h5ad_path}") + if not gwas_path.exists(): + raise FileNotFoundError(f"Input GWAS file not found: {gwas_path}") + if species not in ["human", "mouse"]: + raise ValueError("species must be one of 'human' or 'mouse'") + if device not in ["cpu", "cuda"]: + raise ValueError("device must be one of 'cpu' or 'cuda'") + if ld_path and not ld_path.exists(): + raise FileNotFoundError(f"LD scores path not found: {ld_path}") + if weight_path and not weight_path.exists(): + raise FileNotFoundError(f"Weights path not found: {weight_path}") + if annotation_path and not annotation_path.exists(): + raise FileNotFoundError(f"Annotation file not found: {annotation_path}") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "gsmap", "quick_mode", + "--h5ad_path", str(h5ad_path), + "--gwas_path", str(gwas_path), + "--output_dir", str(output_dir), + "--species", species, + "--n_jobs", str(n_jobs), + "--chunksize", str(chunksize), + "--device", device, + "--n_causal", str(n_causal), + "--n_causal_annotation", str(n_causal_annotation), + "--chrom", chrom, + ] + + if ld_path: + cmd.extend(["--ld_path", str(ld_path)]) + if weight_path: + cmd.extend(["--weight_path", str(weight_path)]) + if annotation_path: + cmd.extend(["--annotation_path", str(annotation_path)]) + if non_negative: + cmd.append("--non_negative") + if print_process: + cmd.append("--print_process") + if find_latent_representations_args: + cmd.extend(["--find_latent_representations_args", find_latent_representations_args]) + if latent_to_gene_args: + cmd.extend(["--latent_to_gene_args", latent_to_gene_args]) + if generate_ldscore_args: + cmd.extend(["--generate_ldscore_args", generate_ldscore_args]) + if spatial_ldsc_args: + cmd.extend(["--spatial_ldsc_args", spatial_ldsc_args]) + if cauchy_combination_args: + cmd.extend(["--cauchy_combination_args", cauchy_combination_args]) + if report_args: + cmd.extend(["--report_args", report_args]) + + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + output_files = [str(p) for p in output_dir.rglob('*') if p.is_file()] + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + logging.error(f"gsmap quick_mode failed: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "gsmap quick_mode failed", + "return_code": e.returncode, + } + +@mcp.tool +def gsmap_run_find_latent_representations( + h5ad_path: Path, + output_dir: Path, + n_neighbors: int = 6, + n_pcs: int = 50, + n_epochs: int = 1000, + lr: float = 0.001, + device: str = "cpu", + seed: int = 0, + print_process: bool = False, +) -> dict: + """ + Find the latent representations of each spot by running GNN. + """ + # Input validation + if not h5ad_path.exists(): + raise FileNotFoundError(f"Input h5ad file not found: {h5ad_path}") + if device not in ["cpu", "cuda"]: + raise ValueError("device must be one of 'cpu' or 'cuda'") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "gsmap", "run_find_latent_representations", + "--h5ad_path", str(h5ad_path), + "--output_dir", str(output_dir), + "--n_neighbors", str(n_neighbors), + "--n_pcs", str(n_pcs), + "--n_epochs", str(n_epochs), + "--lr", str(lr), + "--device", device, + "--seed", str(seed), + ] + + if print_process: + cmd.append("--print_process") + + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + # Expected output file based on gsMap logic + output_file = output_dir / "latent.h5ad" + output_files = [str(output_file)] if output_file.exists() else [] + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + logging.error(f"gsmap run_find_latent_representations failed: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "gsmap run_find_latent_representations failed", + "return_code": e.returncode, + } + +@mcp.tool +def gsmap_run_latent_to_gene( + h5ad_path: Path, + output_dir: Path, + n_neighbors: int = 6, + n_jobs: int = 1, + chunksize: int = 1, + print_process: bool = False, +) -> dict: + """ + Estimate gene marker gene scores for each spot by using latent representations from nearby spots. + """ + # Input validation + if not h5ad_path.exists(): + raise FileNotFoundError(f"Input h5ad file not found: {h5ad_path}") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "gsmap", "run_latent_to_gene", + "--h5ad_path", str(h5ad_path), + "--output_dir", str(output_dir), + "--n_neighbors", str(n_neighbors), + "--n_jobs", str(n_jobs), + "--chunksize", str(chunksize), + ] + + if print_process: + cmd.append("--print_process") + + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + # Expected output file based on gsMap logic + output_file = output_dir / "latent_to_gene.h5ad" + output_files = [str(output_file)] if output_file.exists() else [] + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + logging.error(f"gsmap run_latent_to_gene failed: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "gsmap run_latent_to_gene failed", + "return_code": e.returncode, + } + +@mcp.tool +def gsmap_run_generate_ldscore( + output_dir: Path, + species: str, + ld_path: Optional[Path] = None, + weight_path: Optional[Path] = None, + n_jobs: int = 1, + chunksize: int = 1, + print_process: bool = False, +) -> dict: + """ + Generate LD scores for each spot. + """ + # Input validation + if species not in ["human", "mouse"]: + raise ValueError("species must be one of 'human' or 'mouse'") + if ld_path and not ld_path.exists(): + raise FileNotFoundError(f"LD scores path not found: {ld_path}") + if weight_path and not weight_path.exists(): + raise FileNotFoundError(f"Weights path not found: {weight_path}") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "gsmap", "run_generate_ldscore", + "--output_dir", str(output_dir), + "--species", species, + "--n_jobs", str(n_jobs), + "--chunksize", str(chunksize), + ] + + if ld_path: + cmd.extend(["--ld_path", str(ld_path)]) + if weight_path: + cmd.extend(["--weight_path", str(weight_path)]) + if print_process: + cmd.append("--print_process") + + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + # Expected output files based on gsMap logic + output_files = [str(p) for p in (output_dir / "ldscore").glob("*.l2.ldscore.gz")] + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + logging.error(f"gsmap run_generate_ldscore failed: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "gsmap run_generate_ldscore failed", + "return_code": e.returncode, + } + +@mcp.tool +def gsmap_run_spatial_ldsc( + gwas_path: Path, + output_dir: Path, + n_causal: int = 1000, + chrom: str = "all", + non_negative: bool = False, + n_jobs: int = 1, + chunksize: int = 1, + print_process: bool = False, +) -> dict: + """ + Run spatial LDSC for each spot. + """ + # Input validation + if not gwas_path.exists(): + raise FileNotFoundError(f"Input GWAS file not found: {gwas_path}") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "gsmap", "run_spatial_ldsc", + "--gwas_path", str(gwas_path), + "--output_dir", str(output_dir), + "--n_causal", str(n_causal), + "--chrom", chrom, + "--n_jobs", str(n_jobs), + "--chunksize", str(chunksize), + ] + + if non_negative: + cmd.append("--non_negative") + if print_process: + cmd.append("--print_process") + + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + # Expected output file based on gsMap logic + output_file = output_dir / "spatial_ldsc.csv" + output_files = [str(output_file)] if output_file.exists() else [] + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + logging.error(f"gsmap run_spatial_ldsc failed: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "gsmap run_spatial_ldsc failed", + "return_code": e.returncode, + } + +@mcp.tool +def gsmap_run_cauchy_combination( + output_dir: Path, + annotation_path: Path, + n_causal_annotation: int = 1000, + n_jobs: int = 1, + chunksize: int = 1, + print_process: bool = False, +) -> dict: + """ + Run Cauchy combination for each annotation. + """ + # Input validation + if not annotation_path.exists(): + raise FileNotFoundError(f"Annotation file not found: {annotation_path}") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "gsmap", "run_cauchy_combination", + "--output_dir", str(output_dir), + "--annotation_path", str(annotation_path), + "--n_causal_annotation", str(n_causal_annotation), + "--n_jobs", str(n_jobs), + "--chunksize", str(chunksize), + ] + + if print_process: + cmd.append("--print_process") + + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + # Expected output file based on gsMap logic + output_file = output_dir / "cauchy_combination.csv" + output_files = [str(output_file)] if output_file.exists() else [] + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + logging.error(f"gsmap run_cauchy_combination failed: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "gsmap run_cauchy_combination failed", + "return_code": e.returncode, + } + +@mcp.tool +def gsmap_run_report( + h5ad_path: Path, + output_dir: Path, + prefix: str = "gsMap", + spot_level_df_path: Optional[Path] = None, + annotation_level_df_path: Optional[Path] = None, + gene_level_df_path: Optional[Path] = None, + gene_name: Optional[str] = None, + annotation_name: Optional[str] = None, + fdr_threshold: float = 0.05, + dpi: int = 300, + print_process: bool = False, +) -> dict: + """ + Run Report to generate diagnostic plots and tables. + """ + # Input validation + if not h5ad_path.exists(): + raise FileNotFoundError(f"Input h5ad file not found: {h5ad_path}") + if spot_level_df_path and not spot_level_df_path.exists(): + raise FileNotFoundError(f"Spot level dataframe not found: {spot_level_df_path}") + if annotation_level_df_path and not annotation_level_df_path.exists(): + raise FileNotFoundError(f"Annotation level dataframe not found: {annotation_level_df_path}") + if gene_level_df_path and not gene_level_df_path.exists(): + raise FileNotFoundError(f"Gene level dataframe not found: {gene_level_df_path}") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "gsmap", "run_report", + "--h5ad_path", str(h5ad_path), + "--output_dir", str(output_dir), + "--prefix", prefix, + "--fdr_threshold", str(fdr_threshold), + "--dpi", str(dpi), + ] + + if spot_level_df_path: + cmd.extend(["--spot_level_df_path", str(spot_level_df_path)]) + if annotation_level_df_path: + cmd.extend(["--annotation_level_df_path", str(annotation_level_df_path)]) + if gene_level_df_path: + cmd.extend(["--gene_level_df_path", str(gene_level_df_path)]) + if gene_name: + cmd.extend(["--gene_name", gene_name]) + if annotation_name: + cmd.extend(["--annotation_name", annotation_name]) + if print_process: + cmd.append("--print_process") + + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + output_files = [str(p) for p in output_dir.glob(f"{prefix}*")] + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + logging.error(f"gsmap run_report failed: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "gsmap run_report failed", + "return_code": e.returncode, + } + +@mcp.tool +def gsmap_format_sumstats( + gwas_path: Path, + output_path: Path, + snp: str = "SNP", + chr_col: str = "CHR", # Renamed to avoid conflict with builtin 'chr' + pos: str = "POS", + a1: str = "A1", + a2: str = "A2", + z: str = "Z", + n: str = "N", + p: str = "P", + info: str = "INFO", + maf: str = "MAF", + keep_ambiguous: bool = False, + print_process: bool = False, +) -> dict: + """ + Format GWAS summary statistics. + """ + # Input validation + if not gwas_path.exists(): + raise FileNotFoundError(f"Input GWAS file not found: {gwas_path}") + + output_path.parent.mkdir(parents=True, exist_ok=True) + + cmd = [ + "gsmap", "format_sumstats", + "--gwas_path", str(gwas_path), + "--output_path", str(output_path), + "--snp", snp, + "--chr", chr_col, + "--pos", pos, + "--a1", a1, + "--a2", a2, + "--z", z, + "--n", n, + "--p", p, + "--info", info, + "--maf", maf, + ] + + if keep_ambiguous: + cmd.append("--keep_ambiguous") + if print_process: + cmd.append("--print_process") + + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + output_files = [str(output_path)] if output_path.exists() else [] + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + logging.error(f"gsmap format_sumstats failed: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "gsmap format_sumstats failed", + "return_code": e.returncode, + } + +@mcp.tool +def gsmap_create_slice_mean( + h5ad_paths: List[Path], + output_path: Path, + print_process: bool = False, +) -> dict: + """ + Create slice mean from multiple h5ad files. + """ + # Input validation + if not h5ad_paths: + raise ValueError("At least one h5ad path must be provided.") + for path in h5ad_paths: + if not path.exists(): + raise FileNotFoundError(f"Input h5ad file not found: {path}") + + output_path.parent.mkdir(parents=True, exist_ok=True) + + cmd = [ + "gsmap", "create_slice_mean", + "--h5ad_paths", *[str(p) for p in h5ad_paths], + "--output_path", str(output_path), + ] + + if print_process: + cmd.append("--print_process") + + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + output_files = [str(output_path)] if output_path.exists() else [] + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + logging.error(f"gsmap create_slice_mean failed: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "gsmap create_slice_mean failed", + "return_code": e.returncode, + } \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gsmap/app/gsmap_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gsmap/app/gsmap_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ae24f9a5e49ce166b739e27c09b99f431731a452 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gsmap/app/gsmap_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_gsmap/app/gsmap_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_gsmap' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gsmap/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gsmap/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..4e13f33899a40c515c76ae586978946b61fc9c56 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gsmap/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-gsmap: + build: . + image: mcp-gsmap:latest + container_name: mcp-gsmap + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=gsmap + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gsmap/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gsmap/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5182419fea6b98b4648059f2aebc72de2f176678 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gsmap/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - gsmap + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gsmap/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gsmap/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_gsmap/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hifiasm/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hifiasm/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..29eab5646afbc222e4f45d971b3cca493fe33e35 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hifiasm/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install hifiasm via conda (e.g., from bioconda) +RUN conda install -c bioconda hifiasm -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/hifiasm_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/hifiasm_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/hifiasm_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hifiasm/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hifiasm/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a7d8c781f4fac41f5af4f7dbc43d6cbb47c6e928 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hifiasm/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - hifiasm + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hmmer/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hmmer/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4c15664fdf70ee93628bbf59835f65c8ecaa296d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hmmer/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install hmmer via conda (e.g., from bioconda) +RUN conda install -c bioconda hmmer -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/hmmer_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/hmmer_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/hmmer_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hmmer/app/__pycache__/hmmer_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hmmer/app/__pycache__/hmmer_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1e51d305ad5d76f17d9574bad2c6cec6aa00602d Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hmmer/app/__pycache__/hmmer_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hmmer/app/hmmer_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hmmer/app/hmmer_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f32998e7d197b04554e6c0c2bd6b54c894af0f9b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hmmer/app/hmmer_server.py @@ -0,0 +1,1237 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# Assuming mcp.tool is available in the environment. +# No need to import mcp or define a dummy decorator in the final production code. + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_hmmer' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def hmmbuild( + msafile: Path, + hmmfile_out: Path, + name: Optional[str] = None, + output_summary: Optional[Path] = None, + output_annotated_msa: Optional[Path] = None, + informat: Optional[str] = None, + seed: int = 0, + cpu: int = 1, + amino: bool = False, + dna: bool = False, + rna: bool = False, + hand: bool = False, + fast: bool = False, + small: bool = False, + symfrac: float = 0.5, + fragthresh: float = 0.5, + w_beta: Optional[float] = None, + w_length: Optional[int] = None, + wid: Optional[float] = None, + eent: bool = False, + eset: Optional[float] = None, + pnone: bool = False, + plaplace: bool = False, + archpri: float = 0.85, + gapmax: float = 0.5, +) -> dict: + """ + Build a profile HMM from a multiple sequence alignment. + + Args: + msafile: Input multiple sequence alignment file. + hmmfile_out: Output HMM file. + name: Name the HMM . + output_summary: Direct summary output to a file . + output_annotated_msa: Resave annotated MSA to a file . + informat: Assert that the input MSA is in format . + seed: Set the random number seed to (0 means use time). + cpu: Number of parallel CPU workers to use. + amino: Assert that the MSA contains protein sequences. + dna: Assert that the MSA contains DNA sequences. + rna: Assert that the MSA contains RNA sequences. + hand: Manually set model architecture (requires reference annotation). + fast: Use fast heuristic methods for model construction. + small: Use small memory/fast construction pipeline. + symfrac: Set minimum fraction of symbols in columns to be consensus. + fragthresh: Set fragment score threshold. + w_beta: Set beta for window-based relative weights. + w_length: Set window length for relative weights. + wid: Set identity threshold for relative weights. + eent: Use entropy weighting. + eset: Set effective sequence number for entropy weights. + pnone: Don't use any prior. + plaplace: Use a Laplace +1 prior. + archpri: Set architecture posterior probability threshold. + gapmax: Set maximum column fraction of gaps to be consensus. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + if not msafile.is_file(): + raise FileNotFoundError(f"Input MSA file not found: {msafile}") + if cpu < 1: + raise ValueError("The number of CPUs must be a positive integer (>=1).") + if seed < 0: + raise ValueError("The seed must be a non-negative integer.") + if not 0.0 <= symfrac <= 1.0: + raise ValueError("symfrac must be between 0.0 and 1.0.") + if not 0.0 <= fragthresh <= 1.0: + raise ValueError("fragthresh must be between 0.0 and 1.0.") + if not 0.0 <= archpri <= 1.0: + raise ValueError("archpri must be between 0.0 and 1.0.") + if not 0.0 <= gapmax <= 1.0: + raise ValueError("gapmax must be between 0.0 and 1.0.") + + seq_type_flags = [amino, dna, rna] + if sum(seq_type_flags) > 1: + raise ValueError("Only one of --amino, --dna, or --rna can be specified.") + + cmd = ["hmmbuild"] + + if name: + cmd.extend(["-n", name]) + if output_summary: + cmd.extend(["-o", str(output_summary)]) + if output_annotated_msa: + cmd.extend(["-O", str(output_annotated_msa)]) + if informat: + cmd.extend(["--informat", informat]) + if seed != 0: + cmd.extend(["--seed", str(seed)]) + if cpu != 1: + cmd.extend(["--cpu", str(cpu)]) + if amino: + cmd.append("--amino") + if dna: + cmd.append("--dna") + if rna: + cmd.append("--rna") + if hand: + cmd.append("--hand") + if fast: + cmd.append("--fast") + if small: + cmd.append("--small") + if symfrac != 0.5: + cmd.extend(["--symfrac", str(symfrac)]) + if fragthresh != 0.5: + cmd.extend(["--fragthresh", str(fragthresh)]) + if w_beta is not None: + cmd.extend(["--w_beta", str(w_beta)]) + if w_length is not None: + cmd.extend(["--w_length", str(w_length)]) + if wid is not None: + cmd.extend(["--wid", str(wid)]) + if eent: + cmd.append("--eent") + if eset is not None: + cmd.extend(["--eset", str(eset)]) + if pnone: + cmd.append("--pnone") + if plaplace: + cmd.append("--plaplace") + if archpri != 0.85: + cmd.extend(["--archpri", str(archpri)]) + if gapmax != 0.5: + cmd.extend(["--gapmax", str(gapmax)]) + + cmd.extend([str(hmmfile_out), str(msafile)]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + output_files = [str(hmmfile_out)] + if output_summary: + output_files.append(str(output_summary)) + if output_annotated_msa: + output_files.append(str(output_annotated_msa)) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"hmmbuild failed with exit code {e.returncode}", + "output_files": [], + } + +@mcp.tool() +def hmmpress( + hmmfile: Path, + force: bool = False, +) -> dict: + """ + Prepare an HMM database for hmmscan. + + This command creates several binary files derived from the input HMM file. + These files are required for `hmmscan` to work efficiently. + + Args: + hmmfile: The HMM database file to press. + force: Force overwrite of any previous pressed files. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + if not hmmfile.is_file(): + raise FileNotFoundError(f"Input HMM file not found: {hmmfile}") + + cmd = ["hmmpress"] + if force: + cmd.append("-f") + cmd.append(str(hmmfile)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + base_path = str(hmmfile) + output_files = [ + f"{base_path}.h3m", + f"{base_path}.h3i", + f"{base_path}.h3f", + f"{base_path}.h3p", + ] + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"hmmpress failed with exit code {e.returncode}", + "output_files": [], + } + +def _run_hmmer_search( + program: str, + query_file: Path, + db_file: Path, + output_file: Optional[Path] = None, + alignment_output: Optional[Path] = None, + tblout: Optional[Path] = None, + domtblout: Optional[Path] = None, + pfamtblout: Optional[Path] = None, + acc: bool = False, + noali: bool = False, + notextw: bool = False, + textw: int = 120, + e_value_threshold: float = 10.0, + p_value_threshold: Optional[float] = None, + score_threshold: Optional[float] = None, + dom_e_value_threshold: float = 10.0, + dom_p_value_threshold: Optional[float] = None, + dom_score_threshold: Optional[float] = None, + inc_e_value: Optional[float] = None, + inc_p_value: Optional[float] = None, + inc_score: Optional[float] = None, + inc_dom_e_value: Optional[float] = None, + inc_dom_p_value: Optional[float] = None, + inc_dom_score: Optional[float] = None, + cut_ga: bool = False, + cut_nc: bool = False, + cut_tc: bool = False, + max_sensitivity: bool = False, + f1: Optional[float] = None, + f2: Optional[float] = None, + f3: Optional[float] = None, + nobias: bool = False, + nonull2: bool = False, + z_value: Optional[float] = None, + dom_z_value: Optional[float] = None, + seed: int = 0, + qformat: Optional[str] = None, + tformat: Optional[str] = None, + cpu: int = 1, + jackhmmer_iterations: Optional[int] = None, +) -> dict: + """Internal helper function to run HMMER protein search programs.""" + if not query_file.is_file(): + raise FileNotFoundError(f"Input query file not found: {query_file}") + if not db_file.is_file(): + raise FileNotFoundError(f"Input database file not found: {db_file}") + if cpu < 1: + raise ValueError("The number of CPUs must be a positive integer (>=1).") + if seed < 0: + raise ValueError("The seed must be a non-negative integer.") + if notextw and textw != 120: + raise ValueError("Cannot specify --notextw and a custom --textw simultaneously.") + if not 0.0 <= e_value_threshold: + raise ValueError("E-value threshold must be non-negative.") + if p_value_threshold is not None and not 0.0 <= p_value_threshold <= 1.0: + raise ValueError("P-value threshold must be between 0.0 and 1.0.") + if not 0.0 <= dom_e_value_threshold: + raise ValueError("Domain E-value threshold must be non-negative.") + if dom_p_value_threshold is not None and not 0.0 <= dom_p_value_threshold <= 1.0: + raise ValueError("Domain P-value threshold must be between 0.0 and 1.0.") + + if inc_e_value is not None and not 0.0 <= inc_e_value: + raise ValueError("Inclusion E-value threshold must be non-negative.") + if inc_p_value is not None and not 0.0 <= inc_p_value <= 1.0: + raise ValueError("Inclusion P-value threshold must be between 0.0 and 1.0.") + if inc_dom_e_value is not None and not 0.0 <= inc_dom_e_value: + raise ValueError("Inclusion domain E-value threshold must be non-negative.") + if inc_dom_p_value is not None and not 0.0 <= inc_dom_p_value <= 1.0: + raise ValueError("Inclusion domain P-value threshold must be between 0.0 and 1.0.") + + cut_options = [cut_ga, cut_nc, cut_tc] + if sum(cut_options) > 1: + raise ValueError("Only one of --cut_ga, --cut_nc, or --cut_tc can be used at a time.") + + cmd = [program] + output_files = [] + + if output_file: + cmd.extend(["-o", str(output_file)]) + output_files.append(str(output_file)) + if alignment_output: + cmd.extend(["-A", str(alignment_output)]) + output_files.append(str(alignment_output)) + if tblout: + cmd.extend(["--tblout", str(tblout)]) + output_files.append(str(tblout)) + if domtblout: + cmd.extend(["--domtblout", str(domtblout)]) + output_files.append(str(domtblout)) + if pfamtblout: + cmd.extend(["--pfamtblout", str(pfamtblout)]) + output_files.append(str(pfamtblout)) + if acc: + cmd.append("--acc") + if noali: + cmd.append("--noali") + if notextw: + cmd.append("--notextw") + elif textw != 120: + cmd.extend(["--textw", str(textw)]) + + if e_value_threshold != 10.0: + cmd.extend(["-E", str(e_value_threshold)]) + if p_value_threshold is not None: + cmd.extend(["--pvalue", str(p_value_threshold)]) + if score_threshold is not None: + cmd.extend(["-T", str(score_threshold)]) + if dom_e_value_threshold != 10.0: + cmd.extend(["--domE", str(dom_e_value_threshold)]) + if dom_p_value_threshold is not None: + cmd.extend(["--dompvalue", str(dom_p_value_threshold)]) + if dom_score_threshold is not None: + cmd.extend(["--domT", str(dom_score_threshold)]) + + if inc_e_value is not None: + cmd.extend(["--incE", str(inc_e_value)]) + if inc_p_value is not None: + cmd.extend(["--incpvalue", str(inc_p_value)]) + if inc_score is not None: + cmd.extend(["--incT", str(inc_score)]) + if inc_dom_e_value is not None: + cmd.extend(["--incdomE", str(inc_dom_e_value)]) + if inc_dom_p_value is not None: + cmd.extend(["--incdompvalue", str(inc_dom_p_value)]) + if inc_dom_score is not None: + cmd.extend(["--incdomT", str(inc_dom_score)]) + + if cut_ga: + cmd.append("--cut_ga") + if cut_nc: + cmd.append("--cut_nc") + if cut_tc: + cmd.append("--cut_tc") + + if max_sensitivity: + cmd.append("--max") + if f1 is not None: + cmd.extend(["--F1", str(f1)]) + if f2 is not None: + cmd.extend(["--F2", str(f2)]) + if f3 is not None: + cmd.extend(["--F3", str(f3)]) + if nobias: + cmd.append("--nobias") + + if nonull2: + cmd.append("--nonull2") + if z_value is not None: + cmd.extend(["-Z", str(z_value)]) + if dom_z_value is not None: + cmd.extend(["--domZ", str(dom_z_value)]) + if seed != 0: + cmd.extend(["--seed", str(seed)]) + if qformat: + cmd.extend(["--qformat", qformat]) + if tformat: + cmd.extend(["--tformat", tformat]) + if cpu != 1: + cmd.extend(["--cpu", str(cpu)]) + + if jackhmmer_iterations is not None: + cmd.extend(["-N", str(jackhmmer_iterations)]) + + cmd.extend([str(query_file), str(db_file)]) + + 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_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"{program} failed with exit code {e.returncode}", + "output_files": [], + } + +@mcp.tool() +def hmmsearch( + hmmfile: Path, + seqdb: Path, + output_file: Optional[Path] = None, + alignment_output: Optional[Path] = None, + tblout: Optional[Path] = None, + domtblout: Optional[Path] = None, + pfamtblout: Optional[Path] = None, + acc: bool = False, + noali: bool = False, + notextw: bool = False, + textw: int = 120, + e_value_threshold: float = 10.0, + p_value_threshold: Optional[float] = None, + score_threshold: Optional[float] = None, + dom_e_value_threshold: float = 10.0, + dom_p_value_threshold: Optional[float] = None, + dom_score_threshold: Optional[float] = None, + inc_e_value: Optional[float] = None, + inc_p_value: Optional[float] = None, + inc_score: Optional[float] = None, + inc_dom_e_value: Optional[float] = None, + inc_dom_p_value: Optional[float] = None, + inc_dom_score: Optional[float] = None, + cut_ga: bool = False, + cut_nc: bool = False, + cut_tc: bool = False, + max_sensitivity: bool = False, + f1: Optional[float] = None, + f2: Optional[float] = None, + f3: Optional[float] = None, + nobias: bool = False, + nonull2: bool = False, + z_value: Optional[float] = None, + dom_z_value: Optional[float] = None, + seed: int = 0, + tformat: Optional[str] = None, + cpu: int = 1, +) -> dict: + """ + Search a profile HMM against a sequence database. + + Args: + hmmfile: Input HMM profile file. + seqdb: Target sequence database file. + output_file: Direct output to a file instead of stdout. + alignment_output: Save multiple alignment of all hits to a file. + tblout: Save a simple tabular output file. + domtblout: Save a simple tabular output file of domains. + pfamtblout: Save a pfam-style tabular output file. + acc: Use accessions instead of names in output. + noali: Do not output alignments, making the output smaller. + notextw: Unlimit ASCII text output line width. + textw: Set ASCII text output line width (default 120). + e_value_threshold: Report sequences with E-value <= this threshold. + p_value_threshold: Report sequences with P-value <= this threshold. + score_threshold: Report sequences with score >= this threshold. + dom_e_value_threshold: Report domains with E-value <= this threshold. + dom_p_value_threshold: Report domains with P-value <= this threshold. + dom_score_threshold: Report domains with score >= this threshold. + inc_e_value: Include sequences with E-value <= this threshold. + inc_p_value: Include sequences with P-value <= this threshold. + inc_score: Include sequences with score >= this threshold. + inc_dom_e_value: Include domains with E-value <= this threshold. + inc_dom_p_value: Include domains with P-value <= this threshold. + inc_dom_score: Include domains with score >= this threshold. + cut_ga: Use GA gathering thresholds for inclusion. + cut_nc: Use NC noise thresholds for inclusion. + cut_tc: Use TC trusted thresholds for inclusion. + max_sensitivity: Turn off all heuristics and run full Forward/Viterbi. + f1, f2, f3: Stage 1/2/3 (MSV/Vit/Fwd) thresholds. + nobias: Turn off composition bias filter. + nonull2: Turn off biased composition score corrections. + z_value: Set number of sequences for E-value calculation. + dom_z_value: Set number of domains for E-value calculation. + seed: Set random number seed (0=use time). + tformat: Assert target seqdb is in a specific format. + cpu: Number of parallel CPU workers to use. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + return _run_hmmer_search( + program="hmmsearch", + query_file=hmmfile, + db_file=seqdb, + output_file=output_file, + alignment_output=alignment_output, + tblout=tblout, + domtblout=domtblout, + pfamtblout=pfamtblout, + acc=acc, + noali=noali, + notextw=notextw, + textw=textw, + e_value_threshold=e_value_threshold, + p_value_threshold=p_value_threshold, + score_threshold=score_threshold, + dom_e_value_threshold=dom_e_value_threshold, + dom_p_value_threshold=dom_p_value_threshold, + dom_score_threshold=dom_score_threshold, + inc_e_value=inc_e_value, + inc_p_value=inc_p_value, + inc_score=inc_score, + inc_dom_e_value=inc_dom_e_value, + inc_dom_p_value=inc_dom_p_value, + inc_dom_score=inc_dom_score, + cut_ga=cut_ga, + cut_nc=cut_nc, + cut_tc=cut_tc, + max_sensitivity=max_sensitivity, + f1=f1, + f2=f2, + f3=f3, + nobias=nobias, + nonull2=nonull2, + z_value=z_value, + dom_z_value=dom_z_value, + seed=seed, + tformat=tformat, + cpu=cpu, + ) + +@mcp.tool() +def phmmer( + seqfile: Path, + seqdb: Path, + output_file: Optional[Path] = None, + alignment_output: Optional[Path] = None, + tblout: Optional[Path] = None, + domtblout: Optional[Path] = None, + acc: bool = False, + noali: bool = False, + notextw: bool = False, + textw: int = 120, + e_value_threshold: float = 10.0, + score_threshold: Optional[float] = None, + dom_e_value_threshold: float = 10.0, + dom_score_threshold: Optional[float] = None, + inc_e_value: Optional[float] = None, + inc_score: Optional[float] = None, + inc_dom_e_value: Optional[float] = None, + inc_dom_score: Optional[float] = None, + nobias: bool = False, + nonull2: bool = False, + z_value: Optional[float] = None, + dom_z_value: Optional[float] = None, + seed: int = 0, + qformat: Optional[str] = None, + tformat: Optional[str] = None, + cpu: int = 1, +) -> dict: + """ + Search a protein sequence against a protein sequence database. + + Args: + seqfile: Input sequence file. + seqdb: Target sequence database file. + output_file: Direct output to a file instead of stdout. + alignment_output: Save multiple alignment of all hits to a file. + tblout: Save a simple tabular output file. + domtblout: Save a simple tabular output file of domains. + acc: Use accessions instead of names in output. + noali: Do not output alignments, making the output smaller. + notextw: Unlimit ASCII text output line width. + textw: Set ASCII text output line width (default 120). + e_value_threshold: Report sequences with E-value <= this threshold. + score_threshold: Report sequences with score >= this threshold. + dom_e_value_threshold: Report domains with E-value <= this threshold. + dom_score_threshold: Report domains with score >= this threshold. + inc_e_value: Include sequences with E-value <= this threshold. + inc_score: Include sequences with score >= this threshold. + inc_dom_e_value: Include domains with E-value <= this threshold. + inc_dom_score: Include domains with score >= this threshold. + nobias: Turn off composition bias filter. + nonull2: Turn off biased composition score corrections. + z_value: Set number of sequences for E-value calculation. + dom_z_value: Set number of domains for E-value calculation. + seed: Set random number seed (0=use time). + qformat: Assert query seqfile is in a specific format. + tformat: Assert target seqdb is in a specific format. + cpu: Number of parallel CPU workers to use. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + return _run_hmmer_search( + program="phmmer", + query_file=seqfile, + db_file=seqdb, + output_file=output_file, + alignment_output=alignment_output, + tblout=tblout, + domtblout=domtblout, + acc=acc, + noali=noali, + notextw=notextw, + textw=textw, + e_value_threshold=e_value_threshold, + score_threshold=score_threshold, + dom_e_value_threshold=dom_e_value_threshold, + dom_score_threshold=dom_score_threshold, + inc_e_value=inc_e_value, + inc_score=inc_score, + inc_dom_e_value=inc_dom_e_value, + inc_dom_score=inc_dom_score, + nobias=nobias, + nonull2=nonull2, + z_value=z_value, + dom_z_value=dom_z_value, + seed=seed, + qformat=qformat, + tformat=tformat, + cpu=cpu, + ) + +@mcp.tool() +def hmmscan( + hmmdb: Path, + seqfile: Path, + output_file: Optional[Path] = None, + tblout: Optional[Path] = None, + domtblout: Optional[Path] = None, + pfamtblout: Optional[Path] = None, + acc: bool = False, + noali: bool = False, + notextw: bool = False, + textw: int = 120, + e_value_threshold: float = 10.0, + score_threshold: Optional[float] = None, + dom_e_value_threshold: float = 10.0, + dom_score_threshold: Optional[float] = None, + inc_e_value: Optional[float] = None, + inc_score: Optional[float] = None, + inc_dom_e_value: Optional[float] = None, + inc_dom_score: Optional[float] = None, + cut_ga: bool = False, + cut_nc: bool = False, + cut_tc: bool = False, + max_sensitivity: bool = False, + f1: Optional[float] = None, + f2: Optional[float] = None, + f3: Optional[float] = None, + nobias: bool = False, + nonull2: bool = False, + z_value: Optional[float] = None, + dom_z_value: Optional[float] = None, + seed: int = 0, + cpu: int = 1, +) -> dict: + """ + Search a sequence against a profile HMM database. + Note: The HMM database must be prepared with `hmmpress` first. + + Args: + hmmdb: HMM profile database file (must be pressed). + seqfile: Input sequence file. + output_file: Direct output to a file instead of stdout. + tblout: Save a simple tabular output file. + domtblout: Save a simple tabular output file of domains. + pfamtblout: Save a pfam-style tabular output file. + acc: Use accessions instead of names in output. + noali: Do not output alignments, making the output smaller. + notextw: Unlimit ASCII text output line width. + textw: Set ASCII text output line width (default 120). + e_value_threshold: Report sequences with E-value <= this threshold. + score_threshold: Report sequences with score >= this threshold. + dom_e_value_threshold: Report domains with E-value <= this threshold. + dom_score_threshold: Report domains with score >= this threshold. + inc_e_value: Include sequences with E-value <= this threshold. + inc_score: Include sequences with score >= this threshold. + inc_dom_e_value: Include domains with E-value <= this threshold. + inc_dom_score: Include domains with score >= this threshold. + cut_ga: Use GA gathering thresholds for inclusion. + cut_nc: Use NC noise thresholds for inclusion. + cut_tc: Use TC trusted thresholds for inclusion. + max_sensitivity: Turn off all heuristics and run full Forward/Viterbi. + f1, f2, f3: Stage 1/2/3 (MSV/Vit/Fwd) thresholds. + nobias: Turn off composition bias filter. + nonull2: Turn off biased composition score corrections. + z_value: Set number of sequences for E-value calculation. + dom_z_value: Set number of domains for E-value calculation. + seed: Set random number seed (0=use time). + cpu: Number of parallel CPU workers to use. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + return _run_hmmer_search( + program="hmmscan", + query_file=hmmdb, + db_file=seqfile, + output_file=output_file, + tblout=tblout, + domtblout=domtblout, + pfamtblout=pfamtblout, + acc=acc, + noali=noali, + notextw=notextw, + textw=textw, + e_value_threshold=e_value_threshold, + score_threshold=score_threshold, + dom_e_value_threshold=dom_e_value_threshold, + dom_score_threshold=dom_score_threshold, + inc_e_value=inc_e_value, + inc_score=inc_score, + inc_dom_e_value=inc_dom_e_value, + inc_dom_score=inc_dom_score, + cut_ga=cut_ga, + cut_nc=cut_nc, + cut_tc=cut_tc, + max_sensitivity=max_sensitivity, + f1=f1, + f2=f2, + f3=f3, + nobias=nobias, + nonull2=nonull2, + z_value=z_value, + dom_z_value=dom_z_value, + seed=seed, + cpu=cpu, + ) + +@mcp.tool() +def jackhmmer( + seqfile: Path, + seqdb: Path, + iterations: int = 5, + output_file: Optional[Path] = None, + alignment_output: Optional[Path] = None, + tblout: Optional[Path] = None, + domtblout: Optional[Path] = None, + acc: bool = False, + noali: bool = False, + notextw: bool = False, + textw: int = 120, + e_value_threshold: float = 10.0, + score_threshold: Optional[float] = None, + dom_e_value_threshold: float = 10.0, + dom_score_threshold: Optional[float] = None, + inc_e_value: float = 0.01, + inc_score: Optional[float] = None, + inc_dom_e_value: float = 0.01, + inc_dom_score: Optional[float] = None, + nobias: bool = False, + nonull2: bool = False, + z_value: Optional[float] = None, + dom_z_value: Optional[float] = None, + seed: int = 0, + qformat: Optional[str] = None, + tformat: Optional[str] = None, + cpu: int = 1, +) -> dict: + """ + Iteratively search a protein sequence against a protein sequence database. + + Args: + seqfile: Input sequence file. + seqdb: Target sequence database file. + iterations: Number of iterations to perform. + output_file: Direct output to a file instead of stdout. + alignment_output: Save multiple alignment of all hits to a file. + tblout: Save a simple tabular output file. + domtblout: Save a simple tabular output file of domains. + acc: Use accessions instead of names in output. + noali: Do not output alignments, making the output smaller. + notextw: Unlimit ASCII text output line width. + textw: Set ASCII text output line width (default 120). + e_value_threshold: Report sequences with E-value <= this threshold. + score_threshold: Report sequences with score >= this threshold. + dom_e_value_threshold: Report domains with E-value <= this threshold. + dom_score_threshold: Report domains with score >= this threshold. + inc_e_value: Include sequences with E-value <= this threshold in the next round. + inc_score: Include sequences with score >= this threshold in the next round. + inc_dom_e_value: Include domains with E-value <= this threshold in the next round. + inc_dom_score: Include domains with score >= this threshold in the next round. + nobias: Turn off composition bias filter. + nonull2: Turn off biased composition score corrections. + z_value: Set number of sequences for E-value calculation. + dom_z_value: Set number of domains for E-value calculation. + seed: Set random number seed (0=use time). + qformat: Assert query seqfile is in a specific format. + tformat: Assert target seqdb is in a specific format. + cpu: Number of parallel CPU workers to use. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + if iterations < 1: + raise ValueError("Number of iterations must be a positive integer.") + + return _run_hmmer_search( + program="jackhmmer", + query_file=seqfile, + db_file=seqdb, + output_file=output_file, + alignment_output=alignment_output, + tblout=tblout, + domtblout=domtblout, + acc=acc, + noali=noali, + notextw=notextw, + textw=textw, + e_value_threshold=e_value_threshold, + score_threshold=score_threshold, + dom_e_value_threshold=dom_e_value_threshold, + dom_score_threshold=dom_score_threshold, + inc_e_value=inc_e_value, + inc_score=inc_score, + inc_dom_e_value=inc_dom_e_value, + inc_dom_score=inc_dom_score, + nobias=nobias, + nonull2=nonull2, + z_value=z_value, + dom_z_value=dom_z_value, + seed=seed, + qformat=qformat, + tformat=tformat, + cpu=cpu, + jackhmmer_iterations=iterations, + ) + +@mcp.tool() +def nhmmer( + seqfile: Path, + seqdb: Path, + output_file: Optional[Path] = None, + tblout: Optional[Path] = None, + domtblout: Optional[Path] = None, + acc: bool = False, + noali: bool = False, + notextw: bool = False, + textw: int = 120, + e_value_threshold: float = 10.0, + score_threshold: Optional[float] = None, + dom_e_value_threshold: float = 10.0, + dom_score_threshold: Optional[float] = None, + watson: bool = False, + crick: bool = False, + qformat: Optional[str] = None, + tformat: Optional[str] = None, + cpu: int = 1, +) -> dict: + """ + Search a DNA/RNA sequence against a DNA/RNA sequence database. + + Args: + seqfile: Input nucleotide sequence file. + seqdb: Target nucleotide sequence database file. + output_file: Direct output to a file instead of stdout. + tblout: Save a simple tabular output file. + domtblout: Save a simple tabular output file of domains. + acc: Use accessions instead of names in output. + noali: Do not output alignments, making the output smaller. + notextw: Unlimit ASCII text output line width. + textw: Set ASCII text output line width (default 120). + e_value_threshold: Report sequences with E-value <= this threshold. + score_threshold: Report sequences with score >= this threshold. + dom_e_value_threshold: Report domains with E-value <= this threshold. + dom_score_threshold: Report domains with score >= this threshold. + watson: Only search the top strand. + crick: Only search the bottom strand. + qformat: Assert query seqfile is in a specific format. + tformat: Assert target seqdb is in a specific format. + cpu: Number of parallel CPU workers to use. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + if not seqfile.is_file(): + raise FileNotFoundError(f"Input query file not found: {seqfile}") + if not seqdb.is_file(): + raise FileNotFoundError(f"Input database file not found: {seqdb}") + if watson and crick: + raise ValueError("Cannot use --watson and --crick simultaneously.") + if cpu < 1: + raise ValueError("The number of CPUs must be a positive integer (>=1).") + if notextw and textw != 120: + raise ValueError("Cannot specify --notextw and a custom --textw simultaneously.") + if not 0.0 <= e_value_threshold: + raise ValueError("E-value threshold must be non-negative.") + if not 0.0 <= dom_e_value_threshold: + raise ValueError("Domain E-value threshold must be non-negative.") + + cmd = ["nhmmer"] + output_files = [] + + if output_file: + cmd.extend(["-o", str(output_file)]) + output_files.append(str(output_file)) + if tblout: + cmd.extend(["--tblout", str(tblout)]) + output_files.append(str(tblout)) + if domtblout: + cmd.extend(["--domtblout", str(domtblout)]) + output_files.append(str(domtblout)) + if acc: + cmd.append("--acc") + if noali: + cmd.append("--noali") + if notextw: + cmd.append("--notextw") + elif textw != 120: + cmd.extend(["--textw", str(textw)]) + + if e_value_threshold != 10.0: + cmd.extend(["-E", str(e_value_threshold)]) + if score_threshold is not None: + cmd.extend(["-T", str(score_threshold)]) + if dom_e_value_threshold != 10.0: + cmd.extend(["--domE", str(dom_e_value_threshold)]) + if dom_score_threshold is not None: + cmd.extend(["--domT", str(dom_score_threshold)]) + + if watson: + cmd.append("--watson") + if crick: + cmd.append("--crick") + if qformat: + cmd.extend(["--qformat", qformat]) + if tformat: + cmd.extend(["--tformat", tformat]) + if cpu != 1: + cmd.extend(["--cpu", str(cpu)]) + + cmd.extend([str(seqfile), str(seqdb)]) + + 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_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"nhmmer failed with exit code {e.returncode}", + "output_files": [], + } + +@mcp.tool() +def nhmmscan( + hmmdb: Path, + seqfile: Path, + output_file: Optional[Path] = None, + tblout: Optional[Path] = None, + domtblout: Optional[Path] = None, + acc: bool = False, + noali: bool = False, + notextw: bool = False, + textw: int = 120, + e_value_threshold: float = 10.0, + score_threshold: Optional[float] = None, + dom_e_value_threshold: float = 10.0, + dom_score_threshold: Optional[float] = None, + cpu: int = 1, +) -> dict: + """ + Search a DNA/RNA sequence against a DNA/RNA profile HMM database. + Note: The HMM database must be prepared with `hmmpress` first. + + Args: + hmmdb: Nucleotide HMM profile database file (must be pressed). + seqfile: Input nucleotide sequence file. + output_file: Direct output to a file instead of stdout. + tblout: Save a simple tabular output file. + domtblout: Save a simple tabular output file of domains. + acc: Use accessions instead of names in output. + noali: Do not output alignments, making the output smaller. + notextw: Unlimit ASCII text output line width. + textw: Set ASCII text output line width (default 120). + e_value_threshold: Report sequences with E-value <= this threshold. + score_threshold: Report sequences with score >= this threshold. + dom_e_value_threshold: Report domains with E-value <= this threshold. + dom_score_threshold: Report domains with score >= this threshold. + cpu: Number of parallel CPU workers to use. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + if not hmmdb.is_file(): + raise FileNotFoundError(f"Input HMM database not found: {hmmdb}") + if not seqfile.is_file(): + raise FileNotFoundError(f"Input sequence file not found: {seqfile}") + if cpu < 1: + raise ValueError("The number of CPUs must be a positive integer (>=1).") + if notextw and textw != 120: + raise ValueError("Cannot specify --notextw and a custom --textw simultaneously.") + if not 0.0 <= e_value_threshold: + raise ValueError("E-value threshold must be non-negative.") + if not 0.0 <= dom_e_value_threshold: + raise ValueError("Domain E-value threshold must be non-negative.") + + cmd = ["nhmmscan"] + output_files = [] + + if output_file: + cmd.extend(["-o", str(output_file)]) + output_files.append(str(output_file)) + if tblout: + cmd.extend(["--tblout", str(tblout)]) + output_files.append(str(tblout)) + if domtblout: + cmd.extend(["--domtblout", str(domtblout)]) + output_files.append(str(domtblout)) + if acc: + cmd.append("--acc") + if noali: + cmd.append("--noali") + if notextw: + cmd.append("--notextw") + elif textw != 120: + cmd.extend(["--textw", str(textw)]) + + if e_value_threshold != 10.0: + cmd.extend(["-E", str(e_value_threshold)]) + if score_threshold is not None: + cmd.extend(["-T", str(score_threshold)]) + if dom_e_value_threshold != 10.0: + cmd.extend(["--domE", str(dom_e_value_threshold)]) + if dom_score_threshold is not None: + cmd.extend(["--domT", str(dom_score_threshold)]) + + if cpu != 1: + cmd.extend(["--cpu", str(cpu)]) + + cmd.extend([str(hmmdb), str(seqfile)]) + + 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_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"nhmmscan failed with exit code {e.returncode}", + "output_files": [], + } + +@mcp.tool() +def hmmalign( + hmmfile: Path, + seqfile: Path, + output_file: Optional[Path] = None, + trim: bool = False, + amino: bool = False, + dna: bool = False, + rna: bool = False, + informat: Optional[str] = None, + outformat: str = "Stockholm", + allcol: bool = False, + substitute: bool = False, + mapali: Optional[Path] = None, +) -> dict: + """ + Align sequences to a profile HMM. + + Args: + hmmfile: The profile HMM file. + seqfile: The sequence file to align. + output_file: Direct output to a file instead of stdout. + trim: Trim alignment to model consensus columns. + amino: Assert that the sequence file contains protein sequences. + dna: Assert that the sequence file contains DNA sequences. + rna: Assert that the sequence file contains RNA sequences. + informat: Assert that the input sequence file is in a specific format. + outformat: Output alignment in a specific format (default: Stockholm). + allcol: Show all columns, including non-consensus. + substitute: Substitute non-consensus residues with '.'. + mapali: Map coordinates from an existing alignment file. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + if not hmmfile.is_file(): + raise FileNotFoundError(f"Input HMM file not found: {hmmfile}") + if not seqfile.is_file(): + raise FileNotFoundError(f"Input sequence file not found: {seqfile}") + + seq_type_flags = [amino, dna, rna] + if sum(seq_type_flags) > 1: + raise ValueError("Only one of --amino, --dna, or --rna can be specified.") + + cmd = ["hmmalign"] + output_files = [] + + if output_file: + cmd.extend(["-o", str(output_file)]) + output_files.append(str(output_file)) + if trim: + cmd.append("--trim") + if amino: + cmd.append("--amino") + if dna: + cmd.append("--dna") + if rna: + cmd.append("--rna") + if informat: + cmd.extend(["--informat", informat]) + if outformat != "Stockholm": + cmd.extend(["--outformat", outformat]) + if allcol: + cmd.append("--allcol") + if substitute: + cmd.append("--sub") + if mapali: + if not mapali.is_file(): + raise FileNotFoundError(f"Map alignment file not found: {mapali}") + cmd.extend(["--mapali", str(mapali)]) + + cmd.extend([str(hmmfile), str(seqfile)]) + + 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_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"hmmalign failed with exit code {e.returncode}", + "output_files": [], + } + +@mcp.tool() +def hmmfetch( + hmmfile: Path, + key: Optional[str] = None, + output_file: Optional[Path] = None, + index_mode: bool = False, +) -> dict: + """ + Retrieve one or more profile HMMs from an HMM file or index it. + + Args: + hmmfile: The HMM file or database. + key: The key (name or accession) of the HMM to retrieve. Required if not in index_mode. + output_file: Output HMM to a file instead of stdout. + index_mode: If True, index the HMM file instead of fetching a key. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + if not hmmfile.is_file(): + raise FileNotFoundError(f"Input HMM file not found: {hmmfile}") + if not index_mode and not key: + raise ValueError("A 'key' must be provided unless in 'index_mode'.") + if index_mode and key: + raise ValueError("Cannot specify a 'key' when in 'index_mode'.") + + cmd = ["hmmfetch"] + output_files = [] + + if output_file: + cmd.extend(["-o", str(output_file)]) + output_files.append(str(output_file)) + + if index_mode: + cmd.append("--index") + cmd.append(str(hmmfile)) + else: + cmd.extend([str(hmmfile), key]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + if index_mode: + output_files.append(str(hmmfile.with_suffix(hmmfile.suffix + ".ssi"))) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"hmmfetch failed with exit code {e.returncode}", + "output_files": [], + } + +@mcp.tool() +def hmmstat( + hmmfile: Path, +) -> dict: + """ + Show summary statistics for a profile HMM file. + + Args: + hmmfile: The input HMM file. + + Returns: + A dictionary containing the command executed, stdout, and stderr. + """ + if not hmmfile.is_file(): + raise FileNotFoundError(f"Input HMM file not found: {hmmfile}") + + cmd = ["hmmstat", str(hmmfile)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"hmmstat failed with exit code {e.returncode}", + "output_files": [], + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hmmer/app/hmmer_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hmmer/app/hmmer_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d4eca8e253a444861842556d3c847901f8fcfc48 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hmmer/app/hmmer_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hmmer/app/hmmer_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_hmmer' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hmmer/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hmmer/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hmmer/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hmmer/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hmmer/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..dd08eb8769c85c85ce77b7ad5e606d160f1be880 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hmmer/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-hmmer: + build: . + image: mcp-hmmer:latest + container_name: mcp-hmmer + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=hmmer + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hmmer/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hmmer/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4e4863515ac3478c4bea4c93c882eb1ff9f20468 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hmmer/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - hmmer + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hmmer/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hmmer/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_hmmer/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_htseq/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_htseq/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6e00cb1838cf5af18b49110381266a402d523abd --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_htseq/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install htseq via conda (e.g., from bioconda) +RUN conda install -c bioconda htseq -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/htseq_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/htseq_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/htseq_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_htseq/app/__pycache__/htseq_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_htseq/app/__pycache__/htseq_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..63eb87994e3ce80c1071ab924280d2e2150491b6 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_htseq/app/__pycache__/htseq_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_htseq/app/__pycache__/htseq_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_htseq/app/__pycache__/htseq_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a35dd687f2c210b82a1e65ab2a8f145423669b1a Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_htseq/app/__pycache__/htseq_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_htseq/app/htseq_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_htseq/app/htseq_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5824524211bacac94627dc1e15edfd6a787c0619 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_htseq/app/htseq_server.py @@ -0,0 +1,190 @@ +import subprocess +from pathlib import Path +from typing import Optional, List + +# Assume mcp is imported and the decorator is available +# import mcp + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_htseq' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def htseq_count( + alignment_file: Path, + gff_file: Path, + output_file: Optional[Path] = None, + format: str = "sam", + order: str = "name", + stranded: str = "yes", + a: int = 10, + type: str = "exon", + idattr: str = "gene_id", + mode: str = "union", + nonunique: str = "none", + samout: Optional[Path] = None, + quiet: bool = False, + max_reads_in_buffer: int = 30000000, + nprocesses: int = 1, + add_chromosome_info: bool = False, + feature_query: str = "name", + secondary_alignments: str = "score", + supplementary_alignments: str = "score", +) -> dict: + """ + Runs htseq-count to count how many sequencing reads map to each feature. + + This tool takes an alignment file (SAM/BAM) and a feature file (GFF/GTF) + and calculates for each feature the number of reads mapping to it. + + Args: + alignment_file: The alignment file in SAM or BAM format. + gff_file: The feature file in GFF or GTF format. + output_file: Optional path to write the counts output. If not provided, + counts are returned in the 'stdout' field. + format: Type of alignment_file data. Must be 'sam' or 'bam'. + order: For paired-end data, sorting order of the alignment file. + Must be 'pos' or 'name'. + stranded: Whether the data is from a strand-specific assay. + Must be 'yes', 'no', or 'reverse'. + a: Skip all reads with alignment quality lower than this value. + type: Feature type (3rd column in GFF file) to be used. + idattr: GFF attribute to be used as feature ID (e.g., 'gene_id'). + mode: Mode to handle reads overlapping multiple features. Must be + 'union', 'intersection-strict', or 'intersection-nonempty'. + nonunique: Mode to handle reads that align to multiple features. + Must be 'none' or 'all'. + samout: Optional path to write out all SAM alignment records, annotated + with the feature they have been assigned to. + quiet: Suppress progress report and warnings. + max_reads_in_buffer: Maximum number of reads to keep in memory. + Must be a positive, even number. + nprocesses: Number of processes to use. + add_chromosome_info: Store chromosome and position of the feature. + feature_query: Method to query features. Must be 'name' or 'read'. + secondary_alignments: How to deal with secondary alignments. + Must be 'score' or 'ignore'. + supplementary_alignments: How to deal with supplementary alignments. + Must be 'score' or 'ignore'. + + Returns: + A dictionary containing the command executed, stdout, stderr, + and a list of output files. + """ + # --- Input Validation --- + if not alignment_file.is_file(): + raise FileNotFoundError(f"Alignment file not found: {alignment_file}") + if not gff_file.is_file(): + raise FileNotFoundError(f"GFF/GTF file not found: {gff_file}") + + # Validate choice parameters + valid_formats = ["sam", "bam"] + if format not in valid_formats: + raise ValueError(f"Invalid format '{format}'. Must be one of {valid_formats}") + + valid_orders = ["pos", "name"] + if order not in valid_orders: + raise ValueError(f"Invalid order '{order}'. Must be one of {valid_orders}") + + valid_stranded = ["yes", "no", "reverse"] + if stranded not in valid_stranded: + raise ValueError(f"Invalid strandedness '{stranded}'. Must be one of {valid_stranded}") + + valid_modes = ["union", "intersection-strict", "intersection-nonempty"] + if mode not in valid_modes: + raise ValueError(f"Invalid mode '{mode}'. Must be one of {valid_modes}") + + valid_nonunique = ["none", "all"] + if nonunique not in valid_nonunique: + raise ValueError(f"Invalid nonunique mode '{nonunique}'. Must be one of {valid_nonunique}") + + valid_feature_query = ["name", "read"] + if feature_query not in valid_feature_query: + raise ValueError(f"Invalid feature_query '{feature_query}'. Must be one of {valid_feature_query}") + + valid_secondary = ["score", "ignore"] + if secondary_alignments not in valid_secondary: + raise ValueError(f"Invalid secondary_alignments mode '{secondary_alignments}'. Must be one of {valid_secondary}") + + valid_supplementary = ["score", "ignore"] + if supplementary_alignments not in valid_supplementary: + raise ValueError(f"Invalid supplementary_alignments mode '{supplementary_alignments}'. Must be one of {valid_supplementary}") + + # Validate integer parameters + if a < 0: + raise ValueError("Minimum alignment quality 'a' cannot be negative.") + if max_reads_in_buffer <= 0 or max_reads_in_buffer % 2 != 0: + raise ValueError("'max_reads_in_buffer' must be a positive, even number.") + if nprocesses < 1: + raise ValueError("'nprocesses' must be at least 1.") + + # --- Command Construction --- + cmd = ["htseq-count"] + cmd.extend(["--format", format]) + cmd.extend(["--order", order]) + cmd.extend(["--stranded", stranded]) + cmd.extend(["-a", str(a)]) + cmd.extend(["--type", type]) + cmd.extend(["--idattr", idattr]) + cmd.extend(["--mode", mode]) + cmd.extend(["--nonunique", nonunique]) + cmd.extend(["--max-reads-in-buffer", str(max_reads_in_buffer)]) + cmd.extend(["--nprocesses", str(nprocesses)]) + cmd.extend(["--feature-query", feature_query]) + cmd.extend(["--secondary-alignments", secondary_alignments]) + cmd.extend(["--supplementary-alignments", supplementary_alignments]) + + if samout: + cmd.extend(["--samout", str(samout)]) + if quiet: + cmd.append("--quiet") + if add_chromosome_info: + cmd.append("--add-chromosome-info") + + # Positional arguments must be last + cmd.extend([str(alignment_file), str(gff_file)]) + command_executed = " ".join(cmd) + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + + output_files: List[str] = [] + if output_file: + output_file.write_text(result.stdout) + output_files.append(str(output_file)) + if samout: + output_files.append(str(samout)) + + 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: 'htseq-count' command not found. Please ensure HTSeq is installed and in your PATH.", + "error": "Command not found", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"htseq-count failed with exit code {e.returncode}", + "output_files": [] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_htseq/app/htseq_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_htseq/app/htseq_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6a7e2086d3819f40cc512301f1cbb8422bd89f91 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_htseq/app/htseq_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htseq/app/htseq_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_htseq' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_htseq/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_htseq/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_htseq/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_htseq/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_htseq/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..9866d73ab39b96b4a7d11b9f2fba35598e22e1c2 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_htseq/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-htseq: + build: . + image: mcp-htseq:latest + container_name: mcp-htseq + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=htseq + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_htseq/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_htseq/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..93913d98e91a3b073b9de5b75cdad7f2180ef59c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_htseq/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - htseq + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_htseq/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_htseq/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_htseq/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipython-cluster-helper/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipython-cluster-helper/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9b18187e520a44623297eb5b58cb3eac46852d2f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipython-cluster-helper/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install ipython-cluster-helper via conda (e.g., from bioconda) +RUN conda install -c bioconda ipython-cluster-helper -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/ipython-cluster-helper_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/ipython-cluster-helper_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/ipython-cluster-helper_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipython-cluster-helper/app/__pycache__/ipython-cluster-helper_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipython-cluster-helper/app/__pycache__/ipython-cluster-helper_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..93181f61c500aff317c25ee340403bd59a7b713c Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipython-cluster-helper/app/__pycache__/ipython-cluster-helper_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipython-cluster-helper/app/ipython-cluster-helper_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipython-cluster-helper/app/ipython-cluster-helper_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ca99b48e8c29a8df5b9444002f5ce4e6f0e71943 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipython-cluster-helper/app/ipython-cluster-helper_server.py @@ -0,0 +1,442 @@ +import subprocess +import shlex +from pathlib import Path +from typing import Optional, List, Literal + +# MCP decorator is not defined in this context, but the code is written +# as if it were, following the user's request. +# from mcp import mcp + +class MCPPlaceholder: + def tool(self): + def decorator(func): + return func + return decorator + +mcp = MCPPlaceholder() + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_ipython_cluster_helper' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def start( + queue: str, + num_cores: Optional[int] = None, + profile: Optional[str] = None, + timeout: Optional[int] = None, + retries: Optional[int] = None, + scheduler: Optional[Literal["lsf", "sge", "slurm", "torque", "pbspro"]] = None, + resources: Optional[List[str]] = None, + engine: Optional[Literal["ipython", "torque", "slurm", "sge", "lsf", "pbspro"]] = None, + extra_args: Optional[str] = None, +): + """ + Starts an IPython cluster. + + Args: + queue: The queue to submit jobs to. + num_cores: The number of cores to start. + profile: The IPython profile to use. + timeout: The timeout in seconds to wait for the cluster to start. + retries: The number of times to retry starting the cluster. + scheduler: The type of scheduler to use. + resources: Extra scheduler resource flags. Can be specified multiple times. + engine: The engine to use. + extra_args: Extra arguments to pass to the ipcluster engines. + """ + # Input validation + if num_cores is not None and num_cores <= 0: + raise ValueError("num_cores must be a positive integer.") + if timeout is not None and timeout <= 0: + raise ValueError("timeout must be a positive integer.") + if retries is not None and retries < 0: + raise ValueError("retries must be a non-negative integer.") + + command = ["ipython-cluster-helper", "start", "-q", queue] + + if num_cores is not None: + command.extend(["-n", str(num_cores)]) + if profile: + command.extend(["-p", profile]) + if timeout is not None: + command.extend(["-t", str(timeout)]) + if retries is not None: + command.extend(["-r", str(retries)]) + if scheduler: + command.extend(["--scheduler", scheduler]) + if resources: + for resource in resources: + command.extend(["--resources", resource]) + if engine: + command.extend(["--engine", engine]) + if extra_args: + command.extend(["--extra-args", extra_args]) + + command_str = shlex.join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: ipython-cluster-helper not found. Is it installed and in your PATH?", + "error": "Tool not found", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Process failed with exit code {e.returncode}", + "output_files": [] + } + +@mcp.tool() +def stop( + profile: Optional[str] = None, + timeout: Optional[int] = None, +): + """ + Stops an IPython cluster. + + Args: + profile: The IPython profile to use. + timeout: The timeout in seconds to wait for the cluster to stop. + """ + # Input validation + if timeout is not None and timeout <= 0: + raise ValueError("timeout must be a positive integer.") + + command = ["ipython-cluster-helper", "stop"] + + if profile: + command.extend(["-p", profile]) + if timeout is not None: + command.extend(["-t", str(timeout)]) + + command_str = shlex.join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: ipython-cluster-helper not found. Is it installed and in your PATH?", + "error": "Tool not found", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Process failed with exit code {e.returncode}", + "output_files": [] + } + +@mcp.tool() +def update( + queue: str, + num_cores: int, + profile: Optional[str] = None, + timeout: Optional[int] = None, +): + """ + Updates an IPython cluster. + + Args: + queue: The queue to submit jobs to. + num_cores: The number of cores to start. + profile: The IPython profile to use. + timeout: The timeout in seconds to wait for the cluster to start. + """ + # Input validation + if num_cores <= 0: + raise ValueError("num_cores must be a positive integer.") + if timeout is not None and timeout <= 0: + raise ValueError("timeout must be a positive integer.") + + command = ["ipython-cluster-helper", "update", "-q", queue, "-n", str(num_cores)] + + if profile: + command.extend(["-p", profile]) + if timeout is not None: + command.extend(["-t", str(timeout)]) + + command_str = shlex.join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: ipython-cluster-helper not found. Is it installed and in your PATH?", + "error": "Tool not found", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Process failed with exit code {e.returncode}", + "output_files": [] + } + +@mcp.tool() +def info( + profile: Optional[str] = None, + queue: Optional[str] = None, +): + """ + Gets information on an IPython cluster. + + Args: + profile: The IPython profile to use. + queue: The queue to submit jobs to. + """ + command = ["ipython-cluster-helper", "info"] + + if profile: + command.extend(["-p", profile]) + if queue: + command.extend(["-q", queue]) + + command_str = shlex.join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: ipython-cluster-helper not found. Is it installed and in your PATH?", + "error": "Tool not found", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Process failed with exit code {e.returncode}", + "output_files": [] + } + +@mcp.tool() +def clean( + profile: Optional[str] = None, +): + """ + Cleans a cluster's log and pid files. + + Args: + profile: The IPython profile to use. + """ + command = ["ipython-cluster-helper", "clean"] + + if profile: + command.extend(["-p", profile]) + + command_str = shlex.join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: ipython-cluster-helper not found. Is it installed and in your PATH?", + "error": "Tool not found", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Process failed with exit code {e.returncode}", + "output_files": [] + } + +@mcp.tool() +def log( + profile: Optional[str] = None, +): + """ + Tails the log of a cluster. + + Args: + profile: The IPython profile to use. + """ + command = ["ipython-cluster-helper", "log"] + + if profile: + command.extend(["-p", profile]) + + command_str = shlex.join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: ipython-cluster-helper not found. Is it installed and in your PATH?", + "error": "Tool not found", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Process failed with exit code {e.returncode}", + "output_files": [] + } + +@mcp.tool() +def test( + queue: str, + num_cores: Optional[int] = None, + profile: Optional[str] = None, + scheduler: Optional[Literal["lsf", "sge", "slurm", "torque", "pbspro"]] = None, + engine: Optional[Literal["ipython", "torque", "slurm", "sge", "lsf", "pbspro"]] = None, + retries: Optional[int] = None, +): + """ + Tests an IPython cluster. + + Args: + queue: The queue to submit jobs to. + num_cores: The number of cores to start. + profile: The IPython profile to use. + scheduler: The type of scheduler to use. + engine: The engine to use. + retries: The number of times to retry starting the cluster. + """ + # Input validation + if num_cores is not None and num_cores <= 0: + raise ValueError("num_cores must be a positive integer.") + if retries is not None and retries < 0: + raise ValueError("retries must be a non-negative integer.") + + command = ["ipython-cluster-helper", "test", "-q", queue] + + if num_cores is not None: + command.extend(["-n", str(num_cores)]) + if profile: + command.extend(["-p", profile]) + if scheduler: + command.extend(["--scheduler", scheduler]) + if engine: + command.extend(["--engine", engine]) + if retries is not None: + command.extend(["--retries", str(retries)]) + + command_str = shlex.join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: ipython-cluster-helper not found. Is it installed and in your PATH?", + "error": "Tool not found", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Process failed with exit code {e.returncode}", + "output_files": [] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipython-cluster-helper/app/ipython-cluster-helper_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipython-cluster-helper/app/ipython-cluster-helper_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..78a06322b9d1e9c7dac0dc07de6abed253dc1d1a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipython-cluster-helper/app/ipython-cluster-helper_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipython-cluster-helper/app/ipython-cluster-helper_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_ipython_cluster_helper' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipython-cluster-helper/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipython-cluster-helper/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipython-cluster-helper/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipython-cluster-helper/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipython-cluster-helper/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..3e61a4b48ffa9a2d6a43e3f2ac8fa971ff76c75d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipython-cluster-helper/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-ipython-cluster-helper: + build: . + image: mcp-ipython-cluster-helper:latest + container_name: mcp-ipython-cluster-helper + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=ipython-cluster-helper + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipython-cluster-helper/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipython-cluster-helper/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..54859e08ce535db7e3a52c09ea7e6c21f89dc37c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipython-cluster-helper/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - ipython-cluster-helper + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipython-cluster-helper/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipython-cluster-helper/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ipython-cluster-helper/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_itsxpress/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_itsxpress/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..69fbb3f2b4f0e34d6cb8adf20339db91bc0adb4f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_itsxpress/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install itsxpress via conda (e.g., from bioconda) +RUN conda install -c bioconda itsxpress -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/itsxpress_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/itsxpress_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/itsxpress_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_itsxpress/app/__pycache__/itsxpress_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_itsxpress/app/__pycache__/itsxpress_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e3cba9ba46125996b90c23a8eaac495efe531cf3 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_itsxpress/app/__pycache__/itsxpress_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_itsxpress/app/itsxpress_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_itsxpress/app/itsxpress_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0eaae60557e062fee06dd9241b793191590b6655 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_itsxpress/app/itsxpress_server.py @@ -0,0 +1,158 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Literal + +# The mcp.tool decorator is omitted as per the instructions. +# In a real MCP environment, it would be: +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_itsxpress' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def itsxpress( + fastq: Path, + outfile: Path, + region: Literal["ITS1", "ITS2", "ALL"], + taxa: Literal[ + "Alveolata", "Amoebozoa", "Bacillariophyta", "Bryophyta", "Chlorophyta", + "Eustigmatophyceae", "Euglenozoa", "Fungi", "Haptophyceae", "Marchantiophyta", + "Metazoa", "Oomycota", "Parabasalia", "Phaeophyceae", "Raphidophyceae", + "Rhizaria", "Rhodophyta", "Synurophyceae", "Tracheophyta", "All" + ] = "Fungi", + single_end: bool = False, + fastq2: Optional[Path] = None, + outfile2: Optional[Path] = None, + log: Optional[Path] = None, + tempdir: Optional[Path] = None, + keeptemp: bool = False, + cluster_id: float = 1.0, + threads: int = 1, + reversed_primers: bool = False, + allow_staggered_reads: bool = True, +) -> dict: + """ + Rapidly trims the Internally Transcribed Spacer (ITS) region from FASTQ files. + + ITSxpress takes FASTQ data, de-replicates the sequences, identifies the start + and stop sites using HMMSearch, and returns the trimmed sequences. It can + process single-end or paired-end reads and can target the ITS1, ITS2, or the + entire ITS region. + + Args: + fastq: Input FASTQ file (e.g., .fastq, .fq, .fastq.gz, .fq.gz). + outfile: Path for the trimmed output FASTQ file. + region: The ITS region to trim {'ITS1', 'ITS2', 'ALL'}. + taxa: The taxonomic group sequenced. Defaults to "Fungi". + single_end: Flag to specify that the input is single-ended. Defaults to False. + fastq2: Input FASTQ file for read 2 (for paired-end data). + outfile2: Path for the trimmed output FASTQ file for read 2. If used, + reads are returned as unmerged pairs. + log: Path for the log file. Defaults to 'ITSxpress.log' in the CWD. + tempdir: Specify a directory for temporary files. + keeptemp: If True, intermediate files will be kept. Defaults to False. + cluster_id: The percent identity for clustering reads [0.99-1.0]. + Set to 1.0 for exact de-replication. Defaults to 1.0. + threads: Number of processor threads to use. Defaults to 1. + reversed_primers: Set if primers are in reverse orientation. Trimmed reads + will be flipped to the forward orientation. Defaults to False. + allow_staggered_reads: Allow merging of staggered reads via Vsearch. + Defaults to True. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list + of output file paths. + """ + # 1. Input Validation + if not fastq.exists(): + raise FileNotFoundError(f"Input file not found: {fastq}") + if fastq2 and not fastq2.exists(): + raise FileNotFoundError(f"Input read 2 file not found: {fastq2}") + + if single_end and fastq2: + raise ValueError("The --fastq2 parameter cannot be used when --single_end is True.") + if not single_end and not fastq2: + raise ValueError("For paired-end data (--single_end is False), the --fastq2 parameter is required.") + if outfile2 and not fastq2: + raise ValueError("The --outfile2 parameter requires --fastq2 to be specified.") + + if not (0.99 <= cluster_id <= 1.0): + raise ValueError(f"cluster_id must be between 0.99 and 1.0, but was {cluster_id}.") + if threads < 1: + raise ValueError(f"threads must be a positive integer, but was {threads}.") + + # 2. Command Construction + cmd = [ + "itsxpress", + "--fastq", str(fastq), + "--outfile", str(outfile), + "--region", region, + "--taxa", taxa, + "--cluster_id", str(cluster_id), + "--threads", str(threads), + ] + + if single_end: + cmd.append("--single_end") + elif fastq2: + cmd.extend(["--fastq2", str(fastq2)]) + + if outfile2: + cmd.extend(["--outfile2", str(outfile2)]) + + if log: + cmd.extend(["--log", str(log)]) + + if tempdir: + cmd.extend(["--tempdir", str(tempdir)]) + + if keeptemp: + cmd.append("--keeptemp") + + if reversed_primers: + cmd.append("--reversed_primers") + + if allow_staggered_reads: + cmd.append("--allow_staggered_reads") + + # 3. Subprocess Execution + command_str = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except FileNotFoundError: + raise RuntimeError("itsxpress command not found. Please ensure it is installed and in your PATH.") + except subprocess.CalledProcessError as e: + # Return a structured error dictionary if the command fails + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + "error": "ITSxpress execution failed." + } + + # 4. Output File Collection + output_files = [str(outfile)] + if outfile2: + output_files.append(str(outfile2)) + + # The tool creates 'ITSxpress.log' by default if --log is not specified + log_path = log if log else Path("ITSxpress.log") + if log_path.exists(): + output_files.append(str(log_path)) + + # 5. Structured Result Return + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": sorted(list(set(output_files))) # Ensure unique paths + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_itsxpress/app/itsxpress_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_itsxpress/app/itsxpress_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5001caa3a0d4c93d4d64f5dec2f0305efb25509f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_itsxpress/app/itsxpress_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_itsxpress/app/itsxpress_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_itsxpress' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_itsxpress/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_itsxpress/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_itsxpress/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_itsxpress/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_itsxpress/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..eebb6c5d4aeda79f5d46a5862a22da254508fc6a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_itsxpress/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-itsxpress: + build: . + image: mcp-itsxpress:latest + container_name: mcp-itsxpress + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=itsxpress + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_itsxpress/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_itsxpress/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c248caddd57439045da1bb2cccecfa689d565c1a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_itsxpress/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - itsxpress + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_itsxpress/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_itsxpress/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_itsxpress/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ivar/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ivar/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6b38b27f5e3c24b53aef7f525064603a39633b94 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ivar/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install ivar via conda (e.g., from bioconda) +RUN conda install -c bioconda ivar -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/ivar_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/ivar_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/ivar_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ivar/app/__pycache__/ivar_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ivar/app/__pycache__/ivar_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc7ca1b032669da6b61e30d5a387e7d7a29519ba Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ivar/app/__pycache__/ivar_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ivar/app/ivar_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ivar/app/ivar_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6f7331a37ec6cb719a24edbb55d398574c2ab9bb --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ivar/app/ivar_server.py @@ -0,0 +1,467 @@ +import subprocess +from pathlib import Path +from typing import Optional, List + +# MCP decorator is a placeholder for the final environment. +# It is not defined here, so this code is not directly executable +# without the MCP framework. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_ivar' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def ivar_trim( + bam_file: Path, + bed_file: Path, + output_prefix: str, + include_mismatches: bool = False, + min_length: int = 30, + min_quality: int = 20, + window_size: int = 5, +) -> dict: + """ + Trims reads in a BAM file based on primer locations and quality. + This is useful for removing primer sequences from reads in amplicon-based sequencing. + """ + # --- Input Validation --- + if not bam_file.is_file(): + raise FileNotFoundError(f"Input BAM file not found: {bam_file}") + if not bed_file.is_file(): + raise FileNotFoundError(f"Input BED file not found: {bed_file}") + if not output_prefix: + raise ValueError("Output prefix cannot be empty.") + if min_length < 0: + raise ValueError("min_length must be a non-negative integer.") + if not (0 <= min_quality <= 40): + raise ValueError("min_quality must be between 0 and 40.") + if window_size <= 0: + raise ValueError("window_size must be a positive integer.") + + output_bam = Path(f"{output_prefix}.trimmed.bam") + + # --- Command Construction --- + cmd = [ + "ivar", "trim", + "-i", str(bam_file), + "-b", str(bed_file), + "-p", output_prefix, + "-m", str(min_length), + "-q", str(min_quality), + "-s", str(window_size), + ] + if include_mismatches: + cmd.append("-e") + + # --- Subprocess Execution --- + 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": [str(output_bam)], + } + except FileNotFoundError: + raise RuntimeError("ivar command not found. Please ensure it is in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"ivar trim exited with non-zero status: {e.returncode}", + "output_files": [], + } + +@mcp.tool() +def ivar_variants( + bam_file: Path, + output_prefix: str, + reference_fasta: Path, + gff3_file: Path, + min_depth: int = 10, + min_mapq: int = 20, + min_frequency: float = 0.03, + ambiguous_char: str = 'N', + bed_file: Optional[Path] = None, +) -> dict: + """ + Calls variants (SNPs and indels) from a sorted and trimmed BAM file. + """ + # --- Input Validation --- + if not bam_file.is_file(): + raise FileNotFoundError(f"Input BAM file not found: {bam_file}") + if not reference_fasta.is_file(): + raise FileNotFoundError(f"Reference FASTA file not found: {reference_fasta}") + if not gff3_file.is_file(): + raise FileNotFoundError(f"GFF3 file not found: {gff3_file}") + if bed_file and not bed_file.is_file(): + raise FileNotFoundError(f"Optional BED file not found: {bed_file}") + if not output_prefix: + raise ValueError("Output prefix cannot be empty.") + if min_depth < 1: + raise ValueError("min_depth must be at least 1.") + if min_mapq < 0: + raise ValueError("min_mapq must be a non-negative integer.") + if not (0.0 <= min_frequency <= 1.0): + raise ValueError("min_frequency must be between 0.0 and 1.0.") + if len(ambiguous_char) != 1: + raise ValueError("ambiguous_char must be a single character.") + + output_tsv = Path(f"{output_prefix}.tsv") + output_vcf = Path(f"{output_prefix}.vcf") + + # --- Command Construction --- + cmd = [ + "ivar", "variants", + "-p", output_prefix, + "-r", str(reference_fasta), + "-g", str(gff3_file), + "-m", str(min_depth), + "-q", str(min_mapq), + "-t", str(min_frequency), + "-n", ambiguous_char, + ] + if bed_file: + cmd.extend(["-b", str(bed_file)]) + + cmd.append(str(bam_file)) # Positional argument + + # --- Subprocess Execution --- + 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": [str(output_tsv), str(output_vcf)], + } + except FileNotFoundError: + raise RuntimeError("ivar command not found. Please ensure it is in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"ivar variants exited with non-zero status: {e.returncode}", + "output_files": [], + } + +@mcp.tool() +def ivar_filtervariants( + output_prefix: str, + vcf_file: Optional[Path] = None, + tsv_file: Optional[Path] = None, + bed_file: Optional[Path] = None, + min_quality: int = 20, + gatk_pass: bool = False, +) -> dict: + """ + Filters variants from a VCF file based on a TSV file from 'ivar variants'. + """ + # --- Input Validation --- + if not output_prefix: + raise ValueError("Output prefix cannot be empty.") + + actual_vcf = vcf_file if vcf_file else Path(f"{output_prefix}.vcf") + actual_tsv = tsv_file if tsv_file else Path(f"{output_prefix}.tsv") + + if not actual_vcf.is_file(): + raise FileNotFoundError(f"Input VCF file not found: {actual_vcf}") + if not actual_tsv.is_file(): + raise FileNotFoundError(f"Input TSV file not found: {actual_tsv}") + if bed_file and not bed_file.is_file(): + raise FileNotFoundError(f"Optional BED file not found: {bed_file}") + if min_quality < 0: + raise ValueError("min_quality must be a non-negative integer.") + + output_pass_vcf = Path(f"{output_prefix}.pass.vcf") + output_pass_tsv = Path(f"{output_prefix}.pass.tsv") + + # --- Command Construction --- + cmd = [ + "ivar", "filtervariants", + "-p", output_prefix, + "-q", str(min_quality), + ] + if vcf_file: + cmd.extend(["-v", str(vcf_file)]) + if tsv_file: + cmd.extend(["-t", str(tsv_file)]) + if bed_file: + cmd.extend(["-f", str(bed_file)]) + if gatk_pass: + cmd.append("-g") + + # --- Subprocess Execution --- + 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": [str(output_pass_vcf), str(output_pass_tsv)], + } + except FileNotFoundError: + raise RuntimeError("ivar command not found. Please ensure it is in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"ivar filtervariants exited with non-zero status: {e.returncode}", + "output_files": [], + } + +@mcp.tool() +def ivar_consensus( + bam_file: Path, + output_prefix: str, + min_depth: int = 10, + min_frequency: float = 0.0, + min_mapq: int = 20, + ambiguous_char: str = 'N', + fasta_id: str = 'consensus', + keep_indels: bool = False, +) -> dict: + """ + Generates a consensus sequence from a sorted and trimmed BAM file. + """ + # --- Input Validation --- + if not bam_file.is_file(): + raise FileNotFoundError(f"Input BAM file not found: {bam_file}") + if not output_prefix: + raise ValueError("Output prefix cannot be empty.") + if min_depth < 1: + raise ValueError("min_depth must be at least 1.") + if not (0.0 <= min_frequency <= 1.0): + raise ValueError("min_frequency must be between 0.0 and 1.0.") + if min_mapq < 0: + raise ValueError("min_mapq must be a non-negative integer.") + if len(ambiguous_char) != 1: + raise ValueError("ambiguous_char must be a single character.") + + output_fasta = Path(f"{output_prefix}.fa") + + # --- Command Construction --- + cmd = [ + "ivar", "consensus", + "-p", output_prefix, + "-m", str(min_depth), + "-t", str(min_frequency), + "-q", str(min_mapq), + "-n", ambiguous_char, + "-i", fasta_id, + ] + if keep_indels: + cmd.append("-k") + + cmd.append(str(bam_file)) # Positional argument + + # --- Subprocess Execution --- + 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": [str(output_fasta)], + } + except FileNotFoundError: + raise RuntimeError("ivar command not found. Please ensure it is in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"ivar consensus exited with non-zero status: {e.returncode}", + "output_files": [], + } + +@mcp.tool() +def ivar_getmasked( + tsv_file: Path, + bed_file: Path, + fasta_file: Path, + output_prefix: str, + min_frequency: int = 0, +) -> dict: + """ + Identifies primer sites and masks them in the consensus sequence. + """ + # --- Input Validation --- + if not tsv_file.is_file(): + raise FileNotFoundError(f"Input TSV file not found: {tsv_file}") + if not bed_file.is_file(): + raise FileNotFoundError(f"Input BED file not found: {bed_file}") + if not fasta_file.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {fasta_file}") + if not output_prefix: + raise ValueError("Output prefix cannot be empty.") + if min_frequency < 0: + raise ValueError("min_frequency must be a non-negative integer.") + + output_fasta = Path(f"{output_prefix}.masked.fa") + + # --- Command Construction --- + cmd = [ + "ivar", "getmasked", + "-i", str(tsv_file), + "-b", str(bed_file), + "-f", str(fasta_file), + "-p", output_prefix, + "-m", str(min_frequency), + ] + + # --- Subprocess Execution --- + 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": [str(output_fasta)], + } + except FileNotFoundError: + raise RuntimeError("ivar command not found. Please ensure it is in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"ivar getmasked exited with non-zero status: {e.returncode}", + "output_files": [], + } + +@mcp.tool() +def ivar_removereads( + bam_file: Path, + bed_file: Path, + output_prefix: str, +) -> dict: + """ + Removes reads from a BAM file that overlap with positions in a BED file. + """ + # --- Input Validation --- + if not bam_file.is_file(): + raise FileNotFoundError(f"Input BAM file not found: {bam_file}") + if not bed_file.is_file(): + raise FileNotFoundError(f"Input BED file not found: {bed_file}") + if not output_prefix: + raise ValueError("Output prefix cannot be empty.") + + output_bam = Path(f"{output_prefix}.bam") + + # --- Command Construction --- + cmd = [ + "ivar", "removereads", + "-i", str(bam_file), + "-t", str(bed_file), + "-p", output_prefix, + ] + + # --- Subprocess Execution --- + 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": [str(output_bam)], + } + except FileNotFoundError: + raise RuntimeError("ivar command not found. Please ensure it is in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"ivar removereads exited with non-zero status: {e.returncode}", + "output_files": [], + } + +@mcp.tool() +def ivar_ampliconstats( + bam_file: Path, + bed_file: Path, +) -> dict: + """ + Calculates statistics for amplicons from a BAM file. + """ + # --- Input Validation --- + if not bam_file.is_file(): + raise FileNotFoundError(f"Input BAM file not found: {bam_file}") + if not bed_file.is_file(): + raise FileNotFoundError(f"Input BED file not found: {bed_file}") + + # --- Command Construction --- + cmd = [ + "ivar", "ampliconstats", + "-b", str(bed_file), + str(bam_file), # Positional argument + ] + + # --- Subprocess Execution --- + 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": [], # This command outputs to stdout + } + except FileNotFoundError: + raise RuntimeError("ivar command not found. Please ensure it is in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"ivar ampliconstats exited with non-zero status: {e.returncode}", + "output_files": [], + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ivar/app/ivar_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ivar/app/ivar_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..707af9e466688fdd2b735eb3b48aede41e82f6d7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ivar/app/ivar_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ivar/app/ivar_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_ivar' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ivar/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ivar/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ivar/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ivar/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ivar/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..2c9de720f34b4d5e7d6dc8d43eca9a8dc1a38b6c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ivar/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-ivar: + build: . + image: mcp-ivar:latest + container_name: mcp-ivar + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=ivar + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ivar/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ivar/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6d284eeb26cefed8699ad767ff567bc3470213ec --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ivar/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - ivar + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ivar/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ivar/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ivar/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_java-jdk/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_java-jdk/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c0060c346e4817572532973e52ef1b76763cc483 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_java-jdk/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install java-jdk via conda (e.g., from bioconda) +RUN conda install -c bioconda java-jdk -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/java-jdk_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/java-jdk_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/java-jdk_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_java-jdk/app/__pycache__/java-jdk_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_java-jdk/app/__pycache__/java-jdk_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7b1268ad56f282bd6304e0e245d8cb5dc1b6868 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_java-jdk/app/__pycache__/java-jdk_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_java-jdk/app/java-jdk_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_java-jdk/app/java-jdk_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ba01728dc1b668153f76f0da6d219db6bbaab659 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_java-jdk/app/java-jdk_server.py @@ -0,0 +1,268 @@ +import subprocess +import shlex +from pathlib import Path +from typing import Optional, List, Dict, Literal + +# MCP-compliant tool definitions for the java-jdk tool + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_java_jdk' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def java_execute_jar( + jar_file: Path, + args: Optional[List[str]] = None, + use_32bit_datamodel: bool = False, + use_64bit_datamodel: bool = False, + select_server_vm: bool = False, + class_path: Optional[List[Path]] = None, + system_properties: Optional[Dict[str, str]] = None, + verbose_output: Optional[Literal["class", "gc", "jni"]] = None, + show_version_and_continue: bool = False, + require_version: Optional[str] = None, + jre_restrict_search: Optional[bool] = None, + enable_assertions: Optional[str] = None, + disable_assertions: Optional[str] = None, + enable_system_assertions: bool = False, + disable_system_assertions: bool = False, + agent_library: Optional[str] = None, + agent_path: Optional[str] = None, + java_agent: Optional[str] = None, + splash_screen_image: Optional[Path] = None, +): + """ + Executes a Java application packaged as a JAR file. + + This corresponds to the `java -jar jarfile [args...]` command. + + Args: + jar_file: Path to the executable JAR file. + args: A list of arguments to pass to the Java application's main method. + use_32bit_datamodel: Use a 32-bit data model if available (-d32). + use_64bit_datamodel: Use a 64-bit data model if available (-d64). + select_server_vm: Select the "server" VM (-server). + class_path: A list of directories, JAR archives, and ZIP archives to search for class files (-cp, -classpath). + system_properties: A dictionary of system properties to set (-D=). + verbose_output: Enable verbose output for 'class', 'gc', or 'jni'. + show_version_and_continue: Print product version and continue execution (-showversion). + require_version: Require a specific Java version to run (-version:). Deprecated. + jre_restrict_search: If True, include user private JREs in version search (-jre-restrict-search). If False, exclude them (-no-jre-restrict-search). Deprecated. + enable_assertions: Enable assertions. Provide an empty string for `-ea` or a string like `:` for granularity. + disable_assertions: Disable assertions. Provide an empty string for `-da` or a string like `:` for granularity. + enable_system_assertions: Enable system assertions (-esa). + disable_system_assertions: Disable system assertions (-dsa). + agent_library: Load a native agent library by name, e.g., 'hprof' or 'jdwp=help' (-agentlib:[=]). + agent_path: Load a native agent library by full pathname (-agentpath:[=]). + java_agent: Load a Java programming language agent (-javaagent:[=]). + splash_screen_image: Show a splash screen with the specified image (-splash:). + """ + # Input validation + if not jar_file.is_file(): + raise FileNotFoundError(f"JAR file not found: {jar_file}") + if use_32bit_datamodel and use_64bit_datamodel: + raise ValueError("Cannot specify both -d32 and -d64 options.") + if splash_screen_image and not splash_screen_image.is_file(): + raise FileNotFoundError(f"Splash screen image not found: {splash_screen_image}") + if class_path: + for p in class_path: + if not p.exists(): + raise FileNotFoundError(f"Classpath entry not found: {p}") + + cmd = ["java"] + + # Options + if use_32bit_datamodel: cmd.append("-d32") + if use_64bit_datamodel: cmd.append("-d64") + if select_server_vm: cmd.append("-server") + if class_path: cmd.extend(["-cp", ":".join(map(str, class_path))]) + if system_properties: + for key, value in system_properties.items(): + cmd.append(f"-D{key}={value}") + if verbose_output: cmd.append(f"-verbose:{verbose_output}") + if show_version_and_continue: cmd.append("-showversion") + if require_version: cmd.append(f"-version:{require_version}") + if jre_restrict_search is not None: + cmd.append("-jre-restrict-search" if jre_restrict_search else "-no-jre-restrict-search") + if enable_assertions is not None: cmd.append(f"-ea{enable_assertions}") + if disable_assertions is not None: cmd.append(f"-da{disable_assertions}") + if enable_system_assertions: cmd.append("-esa") + if disable_system_assertions: cmd.append("-dsa") + if agent_library: cmd.append(f"-agentlib:{agent_library}") + if agent_path: cmd.append(f"-agentpath:{agent_path}") + if java_agent: cmd.append(f"-javaagent:{java_agent}") + if splash_screen_image: cmd.append(f"-splash:{str(splash_screen_image)}") + + # Main execution command + cmd.extend(["-jar", str(jar_file)]) + + # Application arguments + if args: cmd.extend(args) + + command_executed = shlex.join(cmd) + + try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Java execution failed", + "return_code": e.returncode + } + +@mcp.tool() +def java_execute_class( + class_name: str, + class_path: List[Path], + args: Optional[List[str]] = None, + use_32bit_datamodel: bool = False, + use_64bit_datamodel: bool = False, + select_server_vm: bool = False, + system_properties: Optional[Dict[str, str]] = None, + verbose_output: Optional[Literal["class", "gc", "jni"]] = None, + show_version_and_continue: bool = False, + require_version: Optional[str] = None, + jre_restrict_search: Optional[bool] = None, + enable_assertions: Optional[str] = None, + disable_assertions: Optional[str] = None, + enable_system_assertions: bool = False, + disable_system_assertions: bool = False, + agent_library: Optional[str] = None, + agent_path: Optional[str] = None, + java_agent: Optional[str] = None, + splash_screen_image: Optional[Path] = None, +): + """ + Executes a Java class file. + + This corresponds to the `java [options] class [args...]` command. + + Args: + class_name: The fully qualified name of the class to execute. + class_path: A list of directories, JAR archives, and ZIP archives to search for class files (-cp, -classpath). This is required. + args: A list of arguments to pass to the Java application's main method. + use_32bit_datamodel: Use a 32-bit data model if available (-d32). + use_64bit_datamodel: Use a 64-bit data model if available (-d64). + select_server_vm: Select the "server" VM (-server). + system_properties: A dictionary of system properties to set (-D=). + verbose_output: Enable verbose output for 'class', 'gc', or 'jni'. + show_version_and_continue: Print product version and continue execution (-showversion). + require_version: Require a specific Java version to run (-version:). Deprecated. + jre_restrict_search: If True, include user private JREs in version search (-jre-restrict-search). If False, exclude them (-no-jre-restrict-search). Deprecated. + enable_assertions: Enable assertions. Provide an empty string for `-ea` or a string like `:` for granularity. + disable_assertions: Disable assertions. Provide an empty string for `-da` or a string like `:` for granularity. + enable_system_assertions: Enable system assertions (-esa). + disable_system_assertions: Disable system assertions (-dsa). + agent_library: Load a native agent library by name, e.g., 'hprof' or 'jdwp=help' (-agentlib:[=]). + agent_path: Load a native agent library by full pathname (-agentpath:[=]). + java_agent: Load a Java programming language agent (-javaagent:[=]). + splash_screen_image: Show a splash screen with the specified image (-splash:). + """ + # Input validation + if not class_path: + raise ValueError("A non-empty class_path must be provided to execute a class.") + for p in class_path: + if not p.exists(): + raise FileNotFoundError(f"Classpath entry not found: {p}") + if use_32bit_datamodel and use_64bit_datamodel: + raise ValueError("Cannot specify both -d32 and -d64 options.") + if splash_screen_image and not splash_screen_image.is_file(): + raise FileNotFoundError(f"Splash screen image not found: {splash_screen_image}") + + cmd = ["java"] + + # Options + if use_32bit_datamodel: cmd.append("-d32") + if use_64bit_datamodel: cmd.append("-d64") + if select_server_vm: cmd.append("-server") + if system_properties: + for key, value in system_properties.items(): + cmd.append(f"-D{key}={value}") + if verbose_output: cmd.append(f"-verbose:{verbose_output}") + if show_version_and_continue: cmd.append("-showversion") + if require_version: cmd.append(f"-version:{require_version}") + if jre_restrict_search is not None: + cmd.append("-jre-restrict-search" if jre_restrict_search else "-no-jre-restrict-search") + if enable_assertions is not None: cmd.append(f"-ea{enable_assertions}") + if disable_assertions is not None: cmd.append(f"-da{disable_assertions}") + if enable_system_assertions: cmd.append("-esa") + if disable_system_assertions: cmd.append("-dsa") + if agent_library: cmd.append(f"-agentlib:{agent_library}") + if agent_path: cmd.append(f"-agentpath:{agent_path}") + if java_agent: cmd.append(f"-javaagent:{java_agent}") + if splash_screen_image: cmd.append(f"-splash:{str(splash_screen_image)}") + + # Classpath is required for this mode + cmd.extend(["-classpath", ":".join(map(str, class_path))]) + + # Main execution command + cmd.append(class_name) + + # Application arguments + if args: cmd.extend(args) + + command_executed = shlex.join(cmd) + + try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Java execution failed", + "return_code": e.returncode + } + +@mcp.tool() +def java_show_info( + version: bool = False, + non_standard_options_help: bool = False +): + """ + Shows Java version information or help for non-standard options. + + Args: + version: If True, print the product version and exit (`java -version`). + non_standard_options_help: If True, print help on non-standard options (`java -X`). + """ + if not (version ^ non_standard_options_help): + raise ValueError("Exactly one of 'version' or 'non_standard_options_help' must be True.") + + cmd = ["java"] + if version: + cmd.append("-version") + else: # non_standard_options_help is True + cmd.append("-X") + + command_executed = shlex.join(cmd) + try: + # Note: `java -version` often prints to stderr, and `java -X` can have a non-zero exit code + # on some versions while still printing help. We don't use check=True here. + result = subprocess.run(cmd, capture_output=True, text=True) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "return_code": result.returncode + } + except FileNotFoundError: + raise RuntimeError("Java executable not found. Please ensure it is in your PATH.") + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_java-jdk/app/java-jdk_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_java-jdk/app/java-jdk_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0bf5806823cb453d87050887b091ef48590d9c15 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_java-jdk/app/java-jdk_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_java-jdk/app/java-jdk_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_java_jdk' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_java-jdk/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_java-jdk/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_java-jdk/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_java-jdk/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_java-jdk/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..cc8a826c3123b37e12dfbdadac00a5fddbeee745 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_java-jdk/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-java-jdk: + build: . + image: mcp-java-jdk:latest + container_name: mcp-java-jdk + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=java-jdk + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_java-jdk/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_java-jdk/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4b0dd85c23da221fca5aed00095b2724c58934ad --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_java-jdk/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - java-jdk + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_java-jdk/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_java-jdk/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_java-jdk/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_jcvi/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_jcvi/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5cdf3e9e231da1c3b813bc122b6156c45fbe7283 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_jcvi/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install jcvi via conda (e.g., from bioconda) +RUN conda install -c bioconda jcvi -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/jcvi_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/jcvi_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/jcvi_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_jcvi/app/__pycache__/jcvi_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_jcvi/app/__pycache__/jcvi_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9b1d117b3fbaa989ed2545659e1cffe77b0c486d Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_jcvi/app/__pycache__/jcvi_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_jcvi/app/jcvi_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_jcvi/app/jcvi_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b085b7c86c725ad5523220a8440cd72ea7f896b1 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_jcvi/app/jcvi_server.py @@ -0,0 +1,476 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Literal, Optional +import logging +import shlex + +# Setup basic logging +logging.basicConfig(level=logging.INFO) + +# MCP decorator is assumed to be provided by the execution environment. +# This is a placeholder for development and linting. +class mcp: + """Placeholder for the MCP decorator.""" + def tool(func): + return func + +# Helper function to run commands and handle outputs +def _run_command(cmd: List[str], output_path: Optional[Path] = None): + """Executes a command, captures output, and handles errors.""" + command_str = shlex.join(cmd) + logging.info(f"Executing command: {command_str}") + + try: + if output_path: + with open(output_path, "w") as f: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + stdout=f + ) + # Read back a snippet of stdout for the return dict if needed + stdout_capture = f"Output written to {output_path}" + else: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True + ) + stdout_capture = result.stdout + + return { + "command_executed": command_str, + "stdout": stdout_capture, + "stderr": result.stderr, + "output_files": [str(output_path)] if output_path else [] + } + except FileNotFoundError: + raise RuntimeError(f"Command '{cmd[0]}' not found. Ensure 'python' is in the system's PATH.") + except subprocess.CalledProcessError as e: + logging.error(f"Command failed with exit code {e.returncode}") + logging.error(f"Stderr: {e.stderr}") + logging.error(f"Stdout: {e.stdout}") + raise e + + +@mcp.tool +def jcvi_formats_fasta_clean( + input_fasta: Path, + output_fasta: Path +): + """Removes irregular characters in FASTA sequences.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "clean", str(input_fasta)] + return _run_command(cmd, output_path=output_fasta) + +@mcp.tool +def jcvi_formats_fasta_diff( + fasta1: Path, + fasta2: Path +): + """Checks if two FASTA files contain the same record information.""" + if not fasta1.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {fasta1}") + if not fasta2.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {fasta2}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "diff", str(fasta1), str(fasta2)] + return _run_command(cmd) + +@mcp.tool +def jcvi_formats_fasta_extract( + fasta_file: Path, + ids_file: Path, + output_fasta: Path +): + """Given a FASTA file and a file with sequence IDs, retrieves the sequences.""" + if not fasta_file.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {fasta_file}") + if not ids_file.is_file(): + raise FileNotFoundError(f"IDs file not found: {ids_file}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "extract", str(fasta_file), str(ids_file)] + return _run_command(cmd, output_path=output_fasta) + +@mcp.tool +def jcvi_formats_fasta_fastq( + fasta_file: Path, + qual_file: Path, + output_fastq: Path +): + """Combines FASTA and QUAL files to create a FASTQ file.""" + if not fasta_file.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {fasta_file}") + if not qual_file.is_file(): + raise FileNotFoundError(f"Input QUAL file not found: {qual_file}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "fastq", str(fasta_file), str(qual_file)] + return _run_command(cmd, output_path=output_fastq) + +@mcp.tool +def jcvi_formats_fasta_filter( + fasta_file: Path, + output_fasta: Path, + min_size: int = 0, + max_size: int = 0 +): + """Filters FASTA records by sequence size.""" + if not fasta_file.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {fasta_file}") + if min_size < 0: + raise ValueError("min_size must be non-negative.") + if max_size < 0: + raise ValueError("max_size must be non-negative.") + + cmd = ["python", "-m", "jcvi.formats.fasta", "filter", f"--min_size={min_size}", f"--max_size={max_size}", str(fasta_file)] + return _run_command(cmd, output_path=output_fasta) + +@mcp.tool +def jcvi_formats_fasta_format( + input_fasta: Path, + output_fasta: Path, + mapping_file: Optional[Path] = None +): + """Trims accession ID to the first space or switches ID based on a mapping file.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "format", str(input_fasta)] + if mapping_file: + if not mapping_file.is_file(): + raise FileNotFoundError(f"Mapping file not found: {mapping_file}") + cmd.append(str(mapping_file)) + + return _run_command(cmd, output_path=output_fasta) + +@mcp.tool +def jcvi_formats_fasta_fromtab( + tab_file: Path, + output_fasta: Path +): + """Converts a 2-column (ID, sequence) tab-separated file to FASTA format.""" + if not tab_file.is_file(): + raise FileNotFoundError(f"Input tab file not found: {tab_file}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "fromtab", str(tab_file)] + return _run_command(cmd, output_path=output_fasta) + +@mcp.tool +def jcvi_formats_fasta_gaps( + input_fasta: Path, + output_report: Path +): + """Prints out a list of gap sizes within sequences.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "gaps", str(input_fasta)] + return _run_command(cmd, output_path=output_report) + +@mcp.tool +def jcvi_formats_fasta_gc( + input_fasta: Path, + output_plot: Path +): + """Plots G+C content distribution. Assumes output is an image or data file.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + + # The tool might generate a specific filename, e.g., input_fasta.gc.pdf + # We will run it and then move the expected output to the desired location. + # For simplicity here, we assume it writes to stdout or can be directed. + cmd = ["python", "-m", "jcvi.formats.fasta", "gc", str(input_fasta), f"--outfile={output_plot}"] + return _run_command(cmd, output_path=None) # Command handles output file + +@mcp.tool +def jcvi_formats_fasta_identical( + fasta1: Path, + fasta2: Path +): + """Given 2 FASTA files, finds all exactly identical records.""" + if not fasta1.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {fasta1}") + if not fasta2.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {fasta2}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "identical", str(fasta1), str(fasta2)] + return _run_command(cmd) + +@mcp.tool +def jcvi_formats_fasta_ids( + input_fasta: Path, + output_ids: Path +): + """Generates a list of headers from a FASTA file.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "ids", str(input_fasta)] + return _run_command(cmd, output_path=output_ids) + +@mcp.tool +def jcvi_formats_fasta_info( + input_fasta: Path +): + """Runs `sequence_info` on FASTA files and prints a report.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "info", str(input_fasta)] + return _run_command(cmd) + +@mcp.tool +def jcvi_formats_fasta_ispcr( + primers_file: Path, + output_query: Path +): + """Reformats paired primers into isPcr query format.""" + if not primers_file.is_file(): + raise FileNotFoundError(f"Primers file not found: {primers_file}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "ispcr", str(primers_file)] + return _run_command(cmd, output_path=output_query) + +@mcp.tool +def jcvi_formats_fasta_join( + input_fastas: List[Path], + output_fasta: Path +): + """Concatenates a list of sequences and adds gaps in between.""" + cmd = ["python", "-m", "jcvi.formats.fasta", "join"] + for fasta_file in input_fastas: + if not fasta_file.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {fasta_file}") + cmd.append(str(fasta_file)) + + return _run_command(cmd, output_path=output_fasta) + +@mcp.tool +def jcvi_formats_fasta_longestorf( + cds_fasta: Path, + output_fasta: Path +): + """Finds the longest ORF for each sequence in a CDS FASTA file.""" + if not cds_fasta.is_file(): + raise FileNotFoundError(f"Input CDS FASTA file not found: {cds_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "longestorf", str(cds_fasta)] + return _run_command(cmd, output_path=output_fasta) + +@mcp.tool +def jcvi_formats_fasta_pair( + input_fasta: Path, + output_pairs_prefix: str +): + """Sorts paired reads to .pairs, and the rest to .fragments.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "pair", str(input_fasta), f"--prefix={output_pairs_prefix}"] + result = _run_command(cmd) + result["output_files"] = [f"{output_pairs_prefix}.pairs", f"{output_pairs_prefix}.fragments"] + return result + +@mcp.tool +def jcvi_formats_fasta_pairinplace( + fragment_fasta: Path, + output_fasta: Path +): + """Starting from fragment.fasta, finds if adjacent records can form pairs.""" + if not fragment_fasta.is_file(): + raise FileNotFoundError(f"Input fragment FASTA file not found: {fragment_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "pairinplace", str(fragment_fasta)] + return _run_command(cmd, output_path=output_fasta) + +@mcp.tool +def jcvi_formats_fasta_pool( + input_fastas: List[Path], + output_fasta: Path +): + """Pools multiple FASTA files together and adds a prefix to each record ID.""" + cmd = ["python", "-m", "jcvi.formats.fasta", "pool", str(output_fasta)] + for fasta_file in input_fastas: + if not fasta_file.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {fasta_file}") + cmd.append(str(fasta_file)) + + # This tool's argument order might be different, assuming output first. + # Re-running without output redirection as the tool might handle it directly. + command_str = shlex.join(cmd) + try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_fasta)] + } + except subprocess.CalledProcessError as e: + logging.error(f"Command failed: {e.stderr}") + raise e + +@mcp.tool +def jcvi_formats_fasta_qual( + input_fasta: Path, + output_qual: Path +): + """Generates a dummy .qual file based on a FASTA file.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "qual", str(input_fasta)] + return _run_command(cmd, output_path=output_qual) + +@mcp.tool +def jcvi_formats_fasta_random( + input_fasta: Path, + output_fasta: Path, + num_records: int = 100 +): + """Randomly samples a specified number of records from a FASTA file.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + if num_records <= 0: + raise ValueError("Number of records must be positive.") + + cmd = ["python", "-m", "jcvi.formats.fasta", "random", str(input_fasta), str(num_records)] + return _run_command(cmd, output_path=output_fasta) + +@mcp.tool +def jcvi_formats_fasta_sequin( + input_fasta: Path, + output_gapped_fasta: Path +): + """Generates a gapped FASTA file for sequin submission.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "sequin", str(input_fasta)] + return _run_command(cmd, output_path=output_gapped_fasta) + +@mcp.tool +def jcvi_formats_fasta_simulate( + output_fasta: Path, + num_records: int = 100, + seq_len: int = 1000 +): + """Simulates a random FASTA file for testing purposes.""" + if num_records <= 0 or seq_len <= 0: + raise ValueError("Number of records and sequence length must be positive.") + + cmd = ["python", "-m", "jcvi.formats.fasta", "simulate", f"--records={num_records}", f"--len={seq_len}"] + return _run_command(cmd, output_path=output_fasta) + +@mcp.tool +def jcvi_formats_fasta_some( + input_fasta: Path, + ids_file: Path, + output_fasta: Path, + exclude: bool = False +): + """Includes or excludes a list of records from a FASTA file.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + if not ids_file.is_file(): + raise FileNotFoundError(f"IDs file not found: {ids_file}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "some", str(input_fasta), str(ids_file)] + if exclude: + cmd.append("--exclude") + + return _run_command(cmd, output_path=output_fasta) + +@mcp.tool +def jcvi_formats_fasta_sort( + input_fasta: Path, + output_fasta: Path, + sort_by: Literal["id", "size", "length"] = "id", + reverse: bool = False +): + """Sorts the records in a FASTA file by IDs, sizes, etc.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "sort", str(input_fasta), f"--by={sort_by}"] + if reverse: + cmd.append("--reverse") + + return _run_command(cmd, output_path=output_fasta) + +@mcp.tool +def jcvi_formats_fasta_summary( + input_fasta: Path +): + """Reports the real number of bases and N's in a FASTA file.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "summary", str(input_fasta)] + return _run_command(cmd) + +@mcp.tool +def jcvi_formats_fasta_tidy( + input_fasta: Path, + output_fasta: Path +): + """Normalizes gap sizes and removes small components in a FASTA file.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "tidy", str(input_fasta)] + return _run_command(cmd, output_path=output_fasta) + +@mcp.tool +def jcvi_formats_fasta_translate( + cds_fasta: Path, + output_protein_fasta: Path +): + """Translates CDS sequences to proteins.""" + if not cds_fasta.is_file(): + raise FileNotFoundError(f"Input CDS FASTA file not found: {cds_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "translate", str(cds_fasta)] + return _run_command(cmd, output_path=output_protein_fasta) + +@mcp.tool +def jcvi_formats_fasta_trim( + screened_fasta: Path, + output_fasta: Path +): + """Given a cross_match screened FASTA, trims the sequences.""" + if not screened_fasta.is_file(): + raise FileNotFoundError(f"Input screened FASTA file not found: {screened_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "trim", str(screened_fasta)] + return _run_command(cmd, output_path=output_fasta) + +@mcp.tool +def jcvi_formats_fasta_trimsplit( + input_fasta: Path, + output_fasta: Path +): + """Splits sequences at lower-cased letters.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "trimsplit", str(input_fasta)] + return _run_command(cmd, output_path=output_fasta) + +@mcp.tool +def jcvi_formats_fasta_uniq( + input_fasta: Path, + output_fasta: Path +): + """Removes records that are identical.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "uniq", str(input_fasta)] + return _run_command(cmd, output_path=output_fasta) \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_jcvi/app/jcvi_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_jcvi/app/jcvi_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fa9bd15e1c706458c5ebe4b2792654a879bcc3a6 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_jcvi/app/jcvi_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jcvi/app/jcvi_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_jcvi' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_jcvi/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_jcvi/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_jcvi/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_jcvi/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_jcvi/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..6e160923c70e4e72a482f3c4f8e18716284b2f73 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_jcvi/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-jcvi: + build: . + image: mcp-jcvi:latest + container_name: mcp-jcvi + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=jcvi + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_jcvi/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_jcvi/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d88f90b31d41086e601dcd6f87d684a7be368762 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_jcvi/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - jcvi + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_jcvi/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_jcvi/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_jcvi/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_libdeflate/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_libdeflate/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..49409e80936f47683817454756c98374f09cf81f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_libdeflate/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install libdeflate via conda (e.g., from bioconda) +RUN conda install -c bioconda libdeflate -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/libdeflate_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/libdeflate_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/libdeflate_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_libdeflate/app/__pycache__/libdeflate_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_libdeflate/app/__pycache__/libdeflate_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d8f078e8df8109e074bdaa7a5a3ae505b72b432d Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_libdeflate/app/__pycache__/libdeflate_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_libdeflate/app/libdeflate_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_libdeflate/app/libdeflate_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0cb36ef7b13583518067f52b2f6d12292e76e17a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_libdeflate/app/libdeflate_server.py @@ -0,0 +1,288 @@ +from typing import Optional, List +import subprocess +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_libdeflate' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def libdeflate_gzip( + input_file: str, + output_file: Optional[str] = None, + compression_level: int = 6, + keep: bool = True, + force: bool = False, + no_name: bool = False, + verbose: bool = False, +): + """ + Compress files using libdeflate-gzip, a fast drop-in replacement for gzip. + + Args: + input_file: Path to the file to compress. + output_file: Optional path for the output .gz file. If not provided, uses input_file + .gz. + compression_level: Compression level (1-12). Higher is better but slower. Default is 6. + keep: Keep (don't delete) input files during compression. Default is True. + force: Force overwrite of output files. + no_name: Do not save or restore the original name and timestamp. + verbose: Verbose mode. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + + if compression_level < 1 or compression_level > 12: + return {"error": "Compression level must be between 1 and 12."} + + cmd = ["libdeflate-gzip"] + + # Compression level + cmd.append(f"-{compression_level}") + + if keep: + cmd.append("-k") + if force: + cmd.append("-f") + if no_name: + cmd.append("-n") + if verbose: + cmd.append("-v") + + cmd.append(str(input_path)) + + # Handle output file redirection if specified + # libdeflate-gzip supports -c for stdout + if output_file: + cmd.insert(1, "-c") + output_path = Path(output_file) + else: + output_path = Path(f"{input_file}.gz") + + try: + if output_file: + with open(output_path, "w") as out_f: + process = subprocess.run( + cmd, + check=True, + stdout=out_f, + stderr=subprocess.PIPE, + text=True + ) + stdout = "Output written to " + output_file + stderr = process.stderr + else: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True + ) + stdout = process.stdout + stderr = process.stderr + + return { + "command_executed": " ".join(cmd), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_path)] if output_path.exists() else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def libdeflate_gunzip( + input_file: str, + output_file: Optional[str] = None, + keep: bool = True, + force: bool = False, + verbose: bool = False, +): + """ + Decompress .gz files using libdeflate-gunzip. + + Args: + input_file: Path to the .gz file to decompress. + output_file: Optional path for the decompressed output. + keep: Keep (don't delete) input files during decompression. Default is True. + force: Force overwrite of output files. + verbose: Verbose mode. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + + cmd = ["libdeflate-gunzip"] + + if keep: + cmd.append("-k") + if force: + cmd.append("-f") + if verbose: + cmd.append("-v") + + cmd.append(str(input_path)) + + # Handle output file redirection + if output_file: + cmd.insert(1, "-c") + output_path = Path(output_file) + else: + # Default gunzip behavior removes .gz + if input_file.endswith(".gz"): + output_path = Path(input_file[:-3]) + else: + output_path = Path(f"{input_file}.out") + + try: + if output_file: + with open(output_path, "w") as out_f: + process = subprocess.run( + cmd, + check=True, + stdout=out_f, + stderr=subprocess.PIPE, + text=True + ) + stdout = "Output written to " + output_file + stderr = process.stderr + else: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True + ) + stdout = process.stdout + stderr = process.stderr + + return { + "command_executed": " ".join(cmd), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_path)] if output_path.exists() else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def libdeflate_benchmark( + input_file: str, + compression_level: int = 6, + engine: str = "libdeflate", +): + """ + Run a round-trip compression and decompression benchmark on the provided data. + + Args: + input_file: Path to the data file to benchmark. + compression_level: Compression level to test (1-12). Default is 6. + engine: Compression engine to use. Options: 'libdeflate', 'zlib', or 'both'. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + + if compression_level < 1 or compression_level > 12: + return {"error": "Compression level must be between 1 and 12."} + + # The benchmark tool is usually named 'benchmark' in the libdeflate source + # but might be prefixed in some distributions. + cmd = ["benchmark"] + + cmd.append(f"-{compression_level}") + + if engine.lower() == "zlib": + cmd.append("-zlib") + elif engine.lower() == "both": + cmd.append("-both") + elif engine.lower() != "libdeflate": + return {"error": "Invalid engine. Choose 'libdeflate', 'zlib', or 'both'."} + + cmd.append(str(input_path)) + + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + except FileNotFoundError: + return {"error": "The 'benchmark' executable was not found in the PATH."} + +@mcp.tool() +def libdeflate_checksum( + input_file: str, + algorithm: str = "crc32", +): + """ + Compute Adler-32 or CRC-32 checksums using libdeflate's optimized implementations. + + Args: + input_file: Path to the file to checksum. + algorithm: Checksum algorithm to use. Options: 'crc32' or 'adler32'. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + + # The checksum tool is usually named 'checksum' in the libdeflate source + cmd = ["checksum"] + + if algorithm.lower() == "adler32": + cmd.append("-adler32") + elif algorithm.lower() == "crc32": + cmd.append("-crc32") + else: + return {"error": "Invalid algorithm. Choose 'crc32' or 'adler32'."} + + cmd.append(str(input_path)) + + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + except FileNotFoundError: + return {"error": "The 'checksum' executable was not found in the PATH."} + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_libdeflate/app/libdeflate_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_libdeflate/app/libdeflate_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8f0357cac19e6d37071f5b0fd309a1b7a2159f90 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_libdeflate/app/libdeflate_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libdeflate/app/libdeflate_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_libdeflate' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_libdeflate/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_libdeflate/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_libdeflate/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_libdeflate/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_libdeflate/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..672ec17d8ddc18ab1bd483d5ed8338f73dca6390 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_libdeflate/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-libdeflate: + build: . + image: mcp-libdeflate:latest + container_name: mcp-libdeflate + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=libdeflate + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_libdeflate/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_libdeflate/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e3b30e5b91eb620439529d8c62a88e87a2bcaa6e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_libdeflate/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - libdeflate + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_libdeflate/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_libdeflate/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_libdeflate/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_locarna/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_locarna/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2f54d18f08bf933f847ef9ebbfee1d5e2d6030cb --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_locarna/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install locarna via conda (e.g., from bioconda) +RUN conda install -c bioconda locarna -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/locarna_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/locarna_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/locarna_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_locarna/app/__pycache__/locarna_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_locarna/app/__pycache__/locarna_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18fa949d0aa0ebf98eaa5346416f70f167e9878d Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_locarna/app/__pycache__/locarna_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_locarna/app/locarna_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_locarna/app/locarna_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4941ab134f0f5b5738eba91994731c5202c2e270 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_locarna/app/locarna_server.py @@ -0,0 +1,351 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_locarna' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def locarna( + fasta_1: str, + fasta_2: str, + tau: int = 50, + struct_weight: int = 180, + indel: int = 400, + indel_opening: int = 400, + min_prob: float = 0.0005, + max_diff: int = -1, + max_diff_am: int = -1, + free_endgaps: bool = False, + sequ_weight: int = 100, + match: int = 50, + mismatch: int = 0, + consensus_structure: Optional[str] = None, +) -> Dict[str, Any]: + """ + Perform pairwise local or global alignment of RNA sequences using LocARNA. + + Args: + fasta_1: Path to the first FASTA file. + fasta_2: Path to the second FASTA file. + tau: Sequence contribution (default 50). + struct_weight: Structure contribution (default 180). + indel: Indel penalty (default 400). + indel_opening: Indel opening penalty (default 400). + min_prob: Minimal base pair probability (default 0.0005). + max_diff: Maximal difference for alignment (default -1, no limit). + max_diff_am: Maximal difference for alignment in AM (default -1). + free_endgaps: Whether to allow free endgaps (local alignment). + sequ_weight: Weight for sequence similarity. + match: Match score. + mismatch: Mismatch penalty. + consensus_structure: Optional fixed consensus structure. + """ + p1 = Path(fasta_1) + p2 = Path(fasta_2) + if not p1.exists() or not p2.exists(): + return {"error": "One or both input FASTA files do not exist."} + + cmd = [ + "locarna", + str(p1), + str(p2), + f"--tau={tau}", + f"--struct-weight={struct_weight}", + f"--indel={indel}", + f"--indel-opening={indel_opening}", + f"--min-prob={min_prob}", + f"--max-diff={max_diff}", + f"--max-diff-am={max_diff_am}", + f"--sequ-weight={sequ_weight}", + f"--match={match}", + f"--mismatch={mismatch}" + ] + + if free_endgaps: + cmd.append("--free-endgaps") + if consensus_structure: + cmd.extend(["--consensus-structure", consensus_structure]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def mlocarna( + input_fasta: str, + output_dir: str = "mlocarna_results", + threads: int = 1, + iterative: bool = False, + refinement: bool = False, + probabilistic: bool = False, + consistency: bool = False, + consistency_weight: int = 100, + tg_struct: Optional[str] = None, + min_prob: float = 0.001, +) -> Dict[str, Any]: + """ + Perform multiple alignment of RNA sequences using the mlocarna wrapper. + + Args: + input_fasta: Path to the input FASTA file containing multiple sequences. + output_dir: Directory to store results. + threads: Number of threads to use. + iterative: Use iterative refinement. + refinement: Perform alignment refinement. + probabilistic: Use probabilistic consistency transformation. + consistency: Use consistency transformation. + consistency_weight: Weight for consistency. + tg_struct: Target structure for structure-guided alignment. + min_prob: Minimal base pair probability. + """ + p_in = Path(input_fasta) + if not p_in.exists(): + return {"error": f"Input file {input_fasta} not found."} + + cmd = [ + "mlocarna", + str(p_in), + f"--threads={threads}", + f"--min-prob={min_prob}", + f"--output-dir={output_dir}" + ] + + if iterative: + cmd.append("--iterative") + if refinement: + cmd.append("--refinement") + if probabilistic: + cmd.append("--probabilistic") + if consistency: + cmd.append("--consistency") + cmd.append(f"--consistency-weight={consistency_weight}") + if tg_struct: + cmd.extend(["--tg-struct", tg_struct]) + + 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": output_dir, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def locarna_p( + fasta_1: str, + fasta_2: str, + tau: int = 50, + struct_weight: int = 180, + min_prob: float = 0.0005, + temperature: float = 37.0, +) -> Dict[str, Any]: + """ + Calculate the partition function and base pair probabilities for RNA alignment. + + Args: + fasta_1: Path to the first FASTA file. + fasta_2: Path to the second FASTA file. + tau: Sequence contribution. + struct_weight: Structure contribution. + min_prob: Minimal base pair probability. + temperature: Temperature in Celsius. + """ + p1 = Path(fasta_1) + p2 = Path(fasta_2) + if not p1.exists() or not p2.exists(): + return {"error": "Input files not found."} + + cmd = [ + "locarna_p", + str(p1), + str(p2), + f"--tau={tau}", + f"--struct-weight={struct_weight}", + f"--min-prob={min_prob}", + f"--temperature={temperature}" + ] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def sparse_locarna( + fasta_1: str, + fasta_2: str, + exp_prob: float = 0.0, + min_prob: float = 0.0005, + struct_weight: int = 180, + indel: int = 400, +) -> Dict[str, Any]: + """ + Perform memory-efficient RNA alignment using Sparse LocARNA. + + Args: + fasta_1: Path to the first FASTA file. + fasta_2: Path to the second FASTA file. + exp_prob: Expected probability for sparsification. + min_prob: Minimal base pair probability. + struct_weight: Structure contribution. + indel: Indel penalty. + """ + p1 = Path(fasta_1) + p2 = Path(fasta_2) + if not p1.exists() or not p2.exists(): + return {"error": "Input files not found."} + + cmd = [ + "sparse_locarna", + str(p1), + str(p2), + f"--exp-prob={exp_prob}", + f"--min-prob={min_prob}", + f"--struct-weight={struct_weight}", + f"--indel={indel}" + ] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def locarna_eval( + alignment_file: str, + reference_file: str, + verbose: bool = False +) -> Dict[str, Any]: + """ + Evaluate a LocARNA alignment against a reference alignment. + + Args: + alignment_file: Path to the alignment to evaluate (Clustal or Stockholm format). + reference_file: Path to the reference alignment. + verbose: Enable verbose output. + """ + p_aln = Path(alignment_file) + p_ref = Path(reference_file) + + if not p_aln.exists() or not p_ref.exists(): + return {"error": "Alignment or reference file not found."} + + cmd = ["locarna-eval", str(p_aln), str(p_ref)] + if verbose: + cmd.append("--verbose") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def locarna_predict_and_plot( + input_fasta: str, + output_ps: str = "alignment.ps", + width: int = 80, + columns: int = 3 +) -> Dict[str, Any]: + """ + Predict RNA consensus structure and generate a secondary structure plot. + + Args: + input_fasta: Path to the input FASTA/alignment file. + output_ps: Filename for the output PostScript plot. + width: Width of the plot. + columns: Number of columns in the plot. + """ + p_in = Path(input_fasta) + if not p_in.exists(): + return {"error": f"Input file {input_fasta} not found."} + + cmd = [ + "locarna-predict-and-plot", + str(p_in), + "--out", output_ps, + "--width", str(width), + "--columns", str(columns) + ] + + 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_ps], + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_locarna/app/locarna_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_locarna/app/locarna_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f4039765636379966147f86d3fd423e50ce2b034 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_locarna/app/locarna_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_locarna/app/locarna_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_locarna' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_locarna/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_locarna/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_locarna/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_locarna/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_locarna/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..005c7386259f8d1e35e27864130c4cbd69f4296a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_locarna/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-locarna: + build: . + image: mcp-locarna:latest + container_name: mcp-locarna + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=locarna + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_locarna/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_locarna/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2408eea7d962edc9ea0fa0095488f08e62a86f0c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_locarna/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - locarna + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_locarna/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_locarna/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_locarna/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mageck/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mageck/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4cf7afbb0214ab52f8cd6b6edf2d42fd9151ec22 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mageck/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install mageck via conda (e.g., from bioconda) +RUN conda install -c bioconda mageck -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/mageck_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/mageck_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/mageck_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mageck/app/__pycache__/mageck_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mageck/app/__pycache__/mageck_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a95fba16bf743a55fffc48ea07d1c0377ba1a13a Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mageck/app/__pycache__/mageck_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mageck/app/mageck_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mageck/app/mageck_server.py new file mode 100644 index 0000000000000000000000000000000000000000..bf68a0973ae9405aa474390490a979e655dbf7cf --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mageck/app/mageck_server.py @@ -0,0 +1,654 @@ +import subprocess +import logging +from pathlib import Path +from typing import List, Optional, Literal + +# Set up a logger for better feedback +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) + +# This is a mock decorator. In a real MCP environment, this would be provided by the MCP framework. +class mcp: + @staticmethod + def tool(): + def decorator(f): + return f + return decorator + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_mageck' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def mageck_count( + library_file: Path, + fastq_files: List[Path], + sample_labels: List[str], + output_prefix: str, + sgrna_len: int = 20, + trim_5: int = 0, + count_n: bool = False, + unmapped_to_file: bool = False, + pdf_report: bool = False, + norm_method: Literal['median', 'total', 'none'] = 'median', + day0_label: Optional[str] = None, + gmt_file: Optional[Path] = None, + additional_id: bool = False, + threads: int = 1 +) -> dict: + """ + Run the MAGeCK 'count' command to generate a read count table from FASTQ files. + + Args: + library_file: The library file used in the screen. + fastq_files: A list of FASTQ files for read counting. + sample_labels: The labels for samples, corresponding to the FASTQ files. + output_prefix: The prefix for the output file(s). + sgrna_len: The length of the sgRNA sequence. + trim_5: The number of base pairs to be trimmed from the 5' end. + count_n: If True, count sgRNAs containing 'N' bases. + unmapped_to_file: If True, save unmapped reads to a file. + pdf_report: If True, generate a PDF report of the quality control. + norm_method: Method for normalization ('median', 'total', 'none'). + day0_label: The sample label for day 0. Must be in the sample_labels list. + gmt_file: The GMT file for pathway analysis on QC results. + additional_id: If True, add an additional column for gene IDs in the count table. + threads: The number of threads to use. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # Input validation + if not library_file.is_file(): + raise FileNotFoundError(f"Library file not found: {library_file}") + if not fastq_files: + raise ValueError("At least one FASTQ file must be provided.") + for fq in fastq_files: + if not fq.is_file(): + raise FileNotFoundError(f"FASTQ file not found: {fq}") + if len(fastq_files) != len(sample_labels): + raise ValueError("The number of FASTQ files must match the number of sample labels.") + if day0_label and day0_label not in sample_labels: + raise ValueError(f"day0_label '{day0_label}' not found in sample_labels.") + if gmt_file and not gmt_file.is_file(): + raise FileNotFoundError(f"GMT file not found: {gmt_file}") + if threads < 1: + raise ValueError("Number of threads must be at least 1.") + + # Command construction + cmd = [ + "mageck", "count", + "-l", str(library_file), + "-r" + ] + cmd.extend([str(f) for f in fastq_files]) + cmd.extend(["--sample-label", ",".join(sample_labels)]) + cmd.extend(["-n", output_prefix]) + cmd.extend(["--sgrna-len", str(sgrna_len)]) + cmd.extend(["--trim-5", str(trim_5)]) + cmd.extend(["--norm-method", norm_method]) + cmd.extend(["--threads", str(threads)]) + + if count_n: + cmd.append("--count-n") + if unmapped_to_file: + cmd.append("--unmapped-to-file") + if pdf_report: + cmd.append("--pdf-report") + if day0_label: + cmd.extend(["--day0-label", day0_label]) + if gmt_file: + cmd.extend(["--gmt-file", str(gmt_file)]) + if additional_id: + cmd.append("--additional-id") + + # Execute command + command_executed = " ".join(cmd) + logger.info(f"Executing command: {command_executed}") + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True + ) + + # Define expected output files + output_files = [ + f"{output_prefix}.count.txt", + f"{output_prefix}.log", + f"{output_prefix}.countsummary.txt" + ] + if pdf_report: + output_files.append(f"{output_prefix}.QC.pdf") + if unmapped_to_file: + output_files.extend([f"{label}.unmapped.fastq" for label in sample_labels]) + + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(Path(f)) for f in output_files if Path(f).exists()] + } + except subprocess.CalledProcessError as e: + logger.error(f"MAGeCK count failed with exit code {e.returncode}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Process failed with exit code {e.returncode}" + } + +@mcp.tool() +def mageck_test( + count_table: Path, + treatment_samples: List[str], + control_samples: List[str], + output_prefix: str, + sgrna_len: int = 20, + adjust_method: Literal['fdr', 'holm', 'pounds'] = 'fdr', + sort_by: Literal['pos', 'neg'] = 'pos', + variance_estimation_samples: Optional[List[str]] = None, + remove_zero: Literal['none', 'control', 'all', 'both'] = 'none', + remove_zero_threshold: int = 0, + norm_method: Literal['median', 'total', 'control', 'none'] = 'median', + control_sgrna: Optional[Path] = None, + paired: bool = False, + permutation_round: int = 10000, + pdf_plot: bool = False, + gene_lfc_method: Literal['alphamean', 'mean'] = 'alphamean', + gene_test_fdr_threshold: float = 0.25, + cnv_norm: Optional[Path] = None, + cell_line: Optional[str] = None, + control_gene: Optional[Path] = None +) -> dict: + """ + Run the MAGeCK 'test' command to perform statistical tests on a count table. + + Args: + count_table: The read count table from 'mageck count'. + treatment_samples: A list of treatment sample labels. + control_samples: A list of control sample labels. + output_prefix: The prefix for the output file(s). + sgrna_len: The length of the sgRNA sequence. + adjust_method: Method for multiple testing correction. + sort_by: Sort gene summary by positive ('pos') or negative ('neg') selection. + variance_estimation_samples: Sample labels for variance estimation. + remove_zero: Method to remove zero counts. + remove_zero_threshold: Threshold for removing zero counts. + norm_method: Method for normalization. + control_sgrna: A file containing a list of control sgRNAs. + paired: If True, perform a paired test. + permutation_round: The number of permutations. + pdf_plot: If True, generate PDF plots. + gene_lfc_method: Method to calculate gene Log Fold Change (LFC). + gene_test_fdr_threshold: The FDR threshold for gene testing. + cnv_norm: The Copy Number Variation (CNV) normalization file. + cell_line: The cell line for CNV normalization. + control_gene: The control gene file for normalization. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # Input validation + if not count_table.is_file(): + raise FileNotFoundError(f"Count table not found: {count_table}") + if not treatment_samples: + raise ValueError("At least one treatment sample must be provided.") + if not control_samples: + raise ValueError("At least one control sample must be provided.") + if paired and len(treatment_samples) != len(control_samples): + raise ValueError("For paired tests, the number of treatment and control samples must be equal.") + if control_sgrna and not control_sgrna.is_file(): + raise FileNotFoundError(f"Control sgRNA file not found: {control_sgrna}") + if cnv_norm and not cnv_norm.is_file(): + raise FileNotFoundError(f"CNV normalization file not found: {cnv_norm}") + if control_gene and not control_gene.is_file(): + raise FileNotFoundError(f"Control gene file not found: {control_gene}") + + # Command construction + cmd = [ + "mageck", "test", + "-k", str(count_table), + "-t", ",".join(treatment_samples), + "-c", ",".join(control_samples), + "-n", output_prefix, + "--sgrna-len", str(sgrna_len), + "--adjust-method", adjust_method, + "--sort-by", sort_by, + "--remove-zero", remove_zero, + "--remove-zero-threshold", str(remove_zero_threshold), + "--norm-method", norm_method, + "--permutation-round", str(permutation_round), + "--gene-lfc-method", gene_lfc_method, + "--gene-test-fdr-threshold", str(gene_test_fdr_threshold) + ] + + if variance_estimation_samples: + cmd.extend(["--variance-estimation-samples", ",".join(variance_estimation_samples)]) + if control_sgrna: + cmd.extend(["--control-sgrna", str(control_sgrna)]) + if paired: + cmd.append("--paired") + if pdf_plot: + cmd.append("--pdf-plot") + if cnv_norm: + cmd.extend(["--cnv-norm", str(cnv_norm)]) + if cell_line: + cmd.extend(["--cell-line", cell_line]) + if control_gene: + cmd.extend(["--control-gene", str(control_gene)]) + + # Execute command + command_executed = " ".join(cmd) + logger.info(f"Executing command: {command_executed}") + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True + ) + + output_files = [ + f"{output_prefix}.gene_summary.txt", + f"{output_prefix}.sgrna_summary.txt", + f"{output_prefix}.log" + ] + if pdf_plot: + output_files.append(f"{output_prefix}.plot.pdf") + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(Path(f)) for f in output_files if Path(f).exists()] + } + except subprocess.CalledProcessError as e: + logger.error(f"MAGeCK test failed with exit code {e.returncode}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Process failed with exit code {e.returncode}" + } + +@mcp.tool() +def mageck_mle( + count_table: Path, + design_matrix: Path, + output_prefix: str, + sgrna_len: int = 20, + norm_method: Literal['median', 'total', 'control', 'none'] = 'median', + control_sgrna: Optional[Path] = None, + threads: int = 1, + permutation_round: int = 10000, + pdf_plot: bool = False, + gene_lfc_method: Literal['alphamean', 'mean'] = 'alphamean', + gene_test_fdr_threshold: float = 0.25, + cnv_norm: Optional[Path] = None, + cell_line: Optional[str] = None, + control_gene: Optional[Path] = None, + beta_labels: Optional[List[str]] = None +) -> dict: + """ + Run the MAGeCK 'mle' command for Maximum-Likelihood Estimation based analysis. + + Args: + count_table: The read count table from 'mageck count'. + design_matrix: The design matrix file. + output_prefix: The prefix for the output file(s). + sgrna_len: The length of the sgRNA sequence. + norm_method: Method for normalization. + control_sgrna: A file containing a list of control sgRNAs. + threads: The number of threads to use. + permutation_round: The number of permutations. + pdf_plot: If True, generate PDF plots. + gene_lfc_method: Method to calculate gene Log Fold Change (LFC). + gene_test_fdr_threshold: The FDR threshold for gene testing. + cnv_norm: The Copy Number Variation (CNV) normalization file. + cell_line: The cell line for CNV normalization. + control_gene: The control gene file for normalization. + beta_labels: Labels for beta scores, separated by comma. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # Input validation + if not count_table.is_file(): + raise FileNotFoundError(f"Count table not found: {count_table}") + if not design_matrix.is_file(): + raise FileNotFoundError(f"Design matrix file not found: {design_matrix}") + if control_sgrna and not control_sgrna.is_file(): + raise FileNotFoundError(f"Control sgRNA file not found: {control_sgrna}") + if cnv_norm and not cnv_norm.is_file(): + raise FileNotFoundError(f"CNV normalization file not found: {cnv_norm}") + if control_gene and not control_gene.is_file(): + raise FileNotFoundError(f"Control gene file not found: {control_gene}") + if threads < 1: + raise ValueError("Number of threads must be at least 1.") + + # Command construction + cmd = [ + "mageck", "mle", + "-k", str(count_table), + "-d", str(design_matrix), + "-n", output_prefix, + "--sgrna-len", str(sgrna_len), + "--norm-method", norm_method, + "--threads", str(threads), + "--permutation-round", str(permutation_round), + "--gene-lfc-method", gene_lfc_method, + "--gene-test-fdr-threshold", str(gene_test_fdr_threshold) + ] + + if control_sgrna: + cmd.extend(["--control-sgrna", str(control_sgrna)]) + if pdf_plot: + cmd.append("--pdf-plot") + if cnv_norm: + cmd.extend(["--cnv-norm", str(cnv_norm)]) + if cell_line: + cmd.extend(["--cell-line", cell_line]) + if control_gene: + cmd.extend(["--control-gene", str(control_gene)]) + if beta_labels: + cmd.extend(["--beta-labels", ",".join(beta_labels)]) + + # Execute command + command_executed = " ".join(cmd) + logger.info(f"Executing command: {command_executed}") + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True + ) + + output_files = [ + f"{output_prefix}.gene_summary.txt", + f"{output_prefix}.sgrna_summary.txt", + f"{output_prefix}.log" + ] + if pdf_plot: + output_files.append(f"{output_prefix}.plot.pdf") + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(Path(f)) for f in output_files if Path(f).exists()] + } + except subprocess.CalledProcessError as e: + logger.error(f"MAGeCK mle failed with exit code {e.returncode}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Process failed with exit code {e.returncode}" + } + +@mcp.tool() +def mageck_pathway( + gene_ranking: Path, + output_prefix: str, + gmt_file: Optional[Path] = None, + permutation: int = 1000, + fdr_method: Literal['fdr', 'holm'] = 'fdr', + pathway_size_min: int = 10, + pathway_size_max: int = 500 +) -> dict: + """ + Run the MAGeCK 'pathway' command for pathway enrichment analysis. + + Args: + gene_ranking: The gene summary file from 'mageck test' or 'mageck mle'. + output_prefix: The prefix for the output file(s). + gmt_file: The GMT file for pathway analysis. + permutation: The number of permutations. + fdr_method: The method for multiple testing correction. + pathway_size_min: The minimum size of a pathway. + pathway_size_max: The maximum size of a pathway. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # Input validation + if not gene_ranking.is_file(): + raise FileNotFoundError(f"Gene ranking file not found: {gene_ranking}") + if gmt_file and not gmt_file.is_file(): + raise FileNotFoundError(f"GMT file not found: {gmt_file}") + if pathway_size_min < 1: + raise ValueError("pathway_size_min must be at least 1.") + if pathway_size_max < pathway_size_min: + raise ValueError("pathway_size_max must be greater than or equal to pathway_size_min.") + + # Command construction + cmd = [ + "mageck", "pathway", + "--gene-ranking", str(gene_ranking), + "-n", output_prefix, + "--permutation", str(permutation), + "--fdr-method", fdr_method, + "--pathway-size-min", str(pathway_size_min), + "--pathway-size-max", str(pathway_size_max) + ] + + if gmt_file: + cmd.extend(["--gmt-file", str(gmt_file)]) + + # Execute command + command_executed = " ".join(cmd) + logger.info(f"Executing command: {command_executed}") + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True + ) + + output_files = [f"{output_prefix}.pathway_summary.txt"] + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(Path(f)) for f in output_files if Path(f).exists()] + } + except subprocess.CalledProcessError as e: + logger.error(f"MAGeCK pathway failed with exit code {e.returncode}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Process failed with exit code {e.returncode}" + } + +@mcp.tool() +def mageck_flute( + gene_summary: Path, + output_prefix: str, + treatment_id: Optional[List[str]] = None, + control_id: Optional[List[str]] = None, + top: int = 5, + remove_prefix: bool = False, + x_axis: Optional[str] = None, + y_axis: Optional[str] = None, + label_column: Optional[str] = None, + width: float = 8.0, + height: float = 6.0, + plot_type: Literal['volcano', 'rank', 'square'] = 'volcano', + scale_by_size: bool = False, + day0: bool = False +) -> dict: + """ + Run the MAGeCK 'flute' command for visualizing MAGeCK results. + + Args: + gene_summary: The gene summary file from 'mageck test'. + output_prefix: The prefix for the output file(s). + treatment_id: The treatment sample label(s). + control_id: The control sample label(s). + top: The number of top-ranked genes to label in the plot. + remove_prefix: If True, remove prefix in the gene names. + x_axis: The column name for the x-axis. + y_axis: The column name for the y-axis. + label_column: The column name for labels. + width: The width of the plot. + height: The height of the plot. + plot_type: The type of the plot. + scale_by_size: If True, scale the plot by size. + day0: If True, indicates the screen is a day 0 screen. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # Input validation + if not gene_summary.is_file(): + raise FileNotFoundError(f"Gene summary file not found: {gene_summary}") + + # Command construction + cmd = [ + "mageck", "flute", + str(gene_summary), + "-n", output_prefix, + "--top", str(top), + "--width", str(width), + "--height", str(height), + "--plot-type", plot_type + ] + + if treatment_id: + cmd.extend(["--treatment-id", ",".join(treatment_id)]) + if control_id: + cmd.extend(["--control-id", ",".join(control_id)]) + if remove_prefix: + cmd.append("--remove-prefix") + if x_axis: + cmd.extend(["--x-axis", x_axis]) + if y_axis: + cmd.extend(["--y-axis", y_axis]) + if label_column: + cmd.extend(["--label", label_column]) + if scale_by_size: + cmd.append("--scale-by-size") + if day0: + cmd.append("--day0") + + # Execute command + command_executed = " ".join(cmd) + logger.info(f"Executing command: {command_executed}") + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True + ) + + # Flute can generate multiple plots. This is a best-effort guess. + output_files = [ + f"{output_prefix}_volcano.pdf", + f"{output_prefix}_rank.pdf", + f"{output_prefix}_square.pdf", + f"{output_prefix}_summary.txt" + ] + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(Path(f)) for f in output_files if Path(f).exists()] + } + except subprocess.CalledProcessError as e: + logger.error(f"MAGeCK flute failed with exit code {e.returncode}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Process failed with exit code {e.returncode}" + } + +@mcp.tool() +def mageck_vispr( + count_table: Path, + sample_labels: List[str], + design_matrix: Path, + output_prefix: str, + sgrna_len: int = 20, + norm_method: Literal['median', 'total', 'none'] = 'median', + project_name: Optional[str] = None +) -> dict: + """ + Run the MAGeCK 'vispr' command to generate files for VISPR visualization. + + Args: + count_table: The read count table from 'mageck count'. + sample_labels: The labels for samples, separated by comma. + design_matrix: The design matrix file. + output_prefix: The prefix for the output file(s) and directory. + sgrna_len: The length of the sgRNA sequence. + norm_method: Method for normalization. + project_name: The name of the project. + + Returns: + A dictionary containing the executed command, stdout, stderr, and the output directory. + """ + # Input validation + if not count_table.is_file(): + raise FileNotFoundError(f"Count table not found: {count_table}") + if not design_matrix.is_file(): + raise FileNotFoundError(f"Design matrix file not found: {design_matrix}") + if not sample_labels: + raise ValueError("At least one sample label must be provided.") + + # Command construction + cmd = [ + "mageck", "vispr", + "-k", str(count_table), + "-l", ",".join(sample_labels), + "-d", str(design_matrix), + "-n", output_prefix, + "--sgrna-len", str(sgrna_len), + "--norm-method", norm_method + ] + + if project_name: + cmd.extend(["--project-name", project_name]) + + # Execute command + command_executed = " ".join(cmd) + logger.info(f"Executing command: {command_executed}") + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True + ) + + # VISPR creates a directory with the name of the output prefix + output_dir = Path(output_prefix) + output_files = [str(output_dir)] if output_dir.is_dir() else [] + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + logger.error(f"MAGeCK vispr failed with exit code {e.returncode}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Process failed with exit code {e.returncode}" + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mageck/app/mageck_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mageck/app/mageck_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3d7c74b5e5d04d535607de45886049ef3e319249 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mageck/app/mageck_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mageck/app/mageck_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_mageck' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mageck/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mageck/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mageck/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mageck/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mageck/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d39a5c9a98465156717134e3088326949a552872 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mageck/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-mageck: + build: . + image: mcp-mageck:latest + container_name: mcp-mageck + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=mageck + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mageck/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mageck/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..25dc251f7006cda5958506e42743c56b191db135 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mageck/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - mageck + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mageck/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mageck/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mageck/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_markerrepo/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_markerrepo/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e4521ee58f2375efde7c4c17f946c47c932d40fc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_markerrepo/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install markerrepo via conda (e.g., from bioconda) +RUN conda install -c bioconda markerrepo -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/markerrepo_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/markerrepo_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/markerrepo_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_markerrepo/app/__pycache__/markerrepo_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_markerrepo/app/__pycache__/markerrepo_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..362d40f6419dfd6e8b3e43e3e5edf318999bd431 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_markerrepo/app/__pycache__/markerrepo_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_markerrepo/app/markerrepo_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_markerrepo/app/markerrepo_server.py new file mode 100644 index 0000000000000000000000000000000000000000..880a24a22e60f6cc611a60877927fb26df089f83 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_markerrepo/app/markerrepo_server.py @@ -0,0 +1,229 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# MCP decorator is assumed to be defined elsewhere +# For local testing, you can use a dummy decorator: +# def mcp_tool_dummy(*args, **kwargs): +# def decorator(func): +# return func +# return decorator +# mcp = type("MCP", (), {"tool": mcp_tool_dummy}) + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_markerrepo' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def markerrepo_clone(url: str, path: Path): + """ + Clones a marker repository from a given git URL to a specified local path. + + Args: + url: URL of the git repository to clone. + path: Path to clone the repository to. This directory will be created. + """ + # Input validation + if path.exists(): + raise ValueError(f"Output path '{path}' already exists. Please specify a non-existent directory.") + path.parent.mkdir(parents=True, exist_ok=True) + + command = [ + "markerrepo", + "clone", + url, + str(path), + ] + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + # The output is the directory itself. We can list its contents or just return the path. + output_files = [str(p) for p in path.rglob('*') if p.is_file()] + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": { + "cloned_repo_dir": str(path) + } + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "error": "MarkerRepo clone failed", + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + } + + +@mcp.tool() +def markerrepo_update(path: Path): + """ + Updates a local marker repository by pulling the latest changes from the remote. + + Args: + path: Path to the existing local marker repository. + """ + # Input validation + if not path.is_dir(): + raise FileNotFoundError(f"The specified repository path '{path}' does not exist or is not a directory.") + if not (path / ".git").is_dir(): + raise ValueError(f"The path '{path}' does not appear to be a git repository.") + + command = [ + "markerrepo", + "update", + str(path), + ] + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "error": "MarkerRepo update failed", + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + } + + +@mcp.tool() +def markerrepo_list( + repo_path: Path, + species: Optional[str] = None, + tissue: Optional[str] = None, +): + """ + Lists available markers in a local repository, with optional filtering. + + Args: + repo_path: Path to the local marker repository. + species: Optional species to filter by (e.g., 'human', 'mouse'). + tissue: Optional tissue to filter by. + """ + # Input validation + if not repo_path.is_dir(): + raise FileNotFoundError(f"The specified repository path '{repo_path}' does not exist or is not a directory.") + + command = [ + "markerrepo", + "list", + str(repo_path), + ] + if species: + command.extend(["--species", species]) + if tissue: + command.extend(["--tissue", tissue]) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "error": "MarkerRepo list failed", + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + } + + +@mcp.tool() +def markerrepo_annotate( + repo_path: Path, + adata_path: Path, + output_path: Path, + groupby: str = "leiden", + species: str = "human", + tissue: Optional[str] = None, + key_added: str = "cell_type", +): + """ + Annotates a scanpy AnnData object (.h5ad) using markers from a repository. + + Args: + repo_path: Path to the local marker repository. + adata_path: Path to the input AnnData object (.h5ad). + output_path: Path to save the annotated AnnData object. + groupby: Column in adata.obs to group by for annotation. + species: Species to use for annotation (e.g., 'human', 'mouse'). + tissue: Optional tissue to use for annotation. + key_added: Key to add the annotation to in adata.obs. + """ + # Input validation + if not repo_path.is_dir(): + raise FileNotFoundError(f"The specified repository path '{repo_path}' does not exist or is not a directory.") + if not adata_path.is_file(): + raise FileNotFoundError(f"The input AnnData file '{adata_path}' does not exist.") + if output_path.exists(): + raise ValueError(f"Output path '{output_path}' already exists. Please specify a new file path.") + output_path.parent.mkdir(parents=True, exist_ok=True) + + command = [ + "markerrepo", + "annotate", + str(repo_path), + str(adata_path), + str(output_path), + "--groupby", groupby, + "--species", species, + "--key_added", key_added, + ] + if tissue: + command.extend(["--tissue", tissue]) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": { + "annotated_adata": str(output_path) + } + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "error": "MarkerRepo annotate failed", + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_markerrepo/app/markerrepo_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_markerrepo/app/markerrepo_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..95767cb510886e8a97ac7d5ee196e391dbf49d35 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_markerrepo/app/markerrepo_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_markerrepo/app/markerrepo_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_markerrepo' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_markerrepo/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_markerrepo/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_markerrepo/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_markerrepo/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_markerrepo/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..2a8efecd77a6ba457e223fb0c2d251f3bbdf4485 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_markerrepo/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-markerrepo: + build: . + image: mcp-markerrepo:latest + container_name: mcp-markerrepo + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=markerrepo + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_markerrepo/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_markerrepo/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a590b4269fe0d9edb40a00ea6baaab6f2f0c3aa8 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_markerrepo/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - markerrepo + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_markerrepo/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_markerrepo/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_markerrepo/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mash/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mash/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9ea3dcd4e7f0095f435acdd947c521c320e017f9 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mash/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install mash via conda (e.g., from bioconda) +RUN conda install -c bioconda mash -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/mash_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/mash_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/mash_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mash/app/__pycache__/mash_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mash/app/__pycache__/mash_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ef08e732861dc91952eb083d117920de7fd2a9b3 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mash/app/__pycache__/mash_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mash/app/mash_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mash/app/mash_server.py new file mode 100644 index 0000000000000000000000000000000000000000..65c0b48560aae7ebef267fe151685d85f256126b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mash/app/mash_server.py @@ -0,0 +1,663 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# MCP decorator is not imported as per instructions. +# It is assumed to be available in the execution environment. + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_mash' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def mash_sketch( + files: List[Path], + output_file: Optional[Path] = None, + kmer_size: int = 21, + sketch_size: int = 1000, + threads: int = 1, + file_list: Optional[Path] = None, + individual_sequences: bool = False, + reads: bool = False, + min_copies: int = 1, + min_coverage: int = 1, + genome_size: Optional[int] = None, + warning_threshold: float = 0.01, + buffer_size: Optional[str] = None, + verbose: bool = False, + seed: int = 42, + non_canonical: bool = False, + amino_acid: bool = False, + amino_acid_01: bool = False, + comment: Optional[str] = None, + concatenated: bool = False, +) -> dict: + """ + Create sketches (reduced representations for fast operations) from sequence files. + + Args: + files: One or more FASTA/FASTQ file(s) to sketch. + output_file: Output file for the sketch. If not provided, sketches are written to stdout. + kmer_size: k-mer size (must be <= 32). + sketch_size: Number of hashes per sketch. + threads: Number of parallel threads to use. + file_list: A file containing a list of input files, one per line. + individual_sequences: Sketch individual sequences (e.g., contigs) instead of whole files. + reads: Input files are sequence reads. This is required for coverage filtering. + min_copies: Minimum copies of each k-mer to include (k-mer filtering). + min_coverage: Minimum coverage for k-mers from reads to be considered (requires 'reads' to be True). + genome_size: Target genome size for p-value calculation. If not set, it's estimated. + warning_threshold: Probability of a random match for p-value calculation. + buffer_size: Input buffer size. Suffixes K, M, G are allowed (e.g., '100M'). + verbose: Print verbose messages to stderr. + seed: Seed for the hash function. + non_canonical: Use non-canonical k-mers. + amino_acid: Use amino acid alphabet (k <= 16). + amino_acid_01: Use amino acid alphabet with 0-1 encoding (k <= 16). + comment: Set a comment for the sketch. + concatenated: Create a sketch from a single, concatenated sequence. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # Input validation + if not files and not file_list: + raise ValueError("Either 'files' or 'file_list' must be provided.") + if files and file_list: + raise ValueError("'files' and 'file_list' are mutually exclusive.") + if kmer_size > 32 or kmer_size < 1: + raise ValueError("'kmer_size' must be between 1 and 32.") + if sketch_size <= 0: + raise ValueError("'sketch_size' must be a positive integer.") + if threads <= 0: + raise ValueError("'threads' must be a positive integer.") + if min_copies <= 0: + raise ValueError("'min_copies' must be a positive integer.") + if min_coverage > 1 and not reads: + raise ValueError("'min_coverage' > 1 requires 'reads' to be True.") + if amino_acid and amino_acid_01: + raise ValueError("'amino_acid' and 'amino_acid_01' are mutually exclusive.") + if (amino_acid or amino_acid_01) and kmer_size > 16: + raise ValueError("For amino acid sketches, 'kmer_size' must be <= 16.") + + cmd = ["mash", "sketch"] + + cmd.extend(["-k", str(kmer_size)]) + cmd.extend(["-s", str(sketch_size)]) + cmd.extend(["-p", str(threads)]) + cmd.extend(["-S", str(seed)]) + + if output_file: + cmd.extend(["-o", str(output_file)]) + if file_list: + cmd.extend(["-l", str(file_list)]) + if individual_sequences: + cmd.append("-i") + if reads: + cmd.append("-r") + if min_copies > 1: + cmd.extend(["-m", str(min_copies)]) + if min_coverage > 1: + cmd.extend(["-c", str(min_coverage)]) + if genome_size is not None: + cmd.extend(["-g", str(genome_size)]) + if warning_threshold != 0.01: + cmd.extend(["-w", str(warning_threshold)]) + if buffer_size: + cmd.extend(["-b", buffer_size]) + if verbose: + cmd.append("-v") + if non_canonical: + cmd.append("-n") + if amino_acid: + cmd.append("-a") + if amino_acid_01: + cmd.append("-A") + if comment: + cmd.extend(["-I", comment]) + if concatenated: + cmd.append("-C") + + if files: + for file_path in files: + if not file_path.exists(): + raise FileNotFoundError(f"Input file not found: {file_path}") + cmd.append(str(file_path)) + + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True + ) + output_files = [str(output_file)] if output_file else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Mash sketch failed", + "return_code": e.returncode, + } + +@mcp.tool() +def mash_dist( + reference_sketch: Path, + query_files: List[Path], + query_list: Optional[Path] = None, + threads: int = 1, + tabular: bool = False, + max_distance: float = 1.0, + max_p_value: float = 1.0, + sketch_size: Optional[int] = None, + kmer_size: Optional[int] = None, + seed: int = 42, + top_pair_only: bool = False, + amino_acid: bool = False, + amino_acid_01: bool = False, + individual_sequences: bool = False, + write_comments: Optional[Path] = None, + read_comments: Optional[Path] = None, +) -> dict: + """ + Estimate the distance of query sequences to references. + + Args: + reference_sketch: The reference sketch file (.msh). + query_files: One or more query files (FASTA/FASTQ or .msh). + query_list: A file containing a list of query files, one per line. + threads: Number of parallel threads to use. + tabular: Output in a tab-separated format. + max_distance: Maximum distance to report. + max_p_value: Maximum p-value to report. + sketch_size: Override sketch size from the sketch file. + kmer_size: Override k-mer size from the sketch file. + seed: Seed for the hash function. + top_pair_only: For pairwise distances, only write the top pair by distance. + amino_acid: Use amino acid alphabet (k <= 16). + amino_acid_01: Use amino acid alphabet with 0-1 encoding (k <= 16). + individual_sequences: Sketch individual sequences if query files are not sketches. + write_comments: Write comments to the specified file. + read_comments: Read comments from the specified file. + + Returns: + A dictionary containing the executed command, stdout, and stderr. + """ + # Input validation + if not reference_sketch.exists(): + raise FileNotFoundError(f"Reference sketch not found: {reference_sketch}") + if not query_files and not query_list: + raise ValueError("Either 'query_files' or 'query_list' must be provided.") + if query_files and query_list: + raise ValueError("'query_files' and 'query_list' are mutually exclusive.") + if threads <= 0: + raise ValueError("'threads' must be a positive integer.") + if amino_acid and amino_acid_01: + raise ValueError("'amino_acid' and 'amino_acid_01' are mutually exclusive.") + + cmd = ["mash", "dist"] + cmd.extend(["-p", str(threads)]) + cmd.extend(["-S", str(seed)]) + + if tabular: + cmd.append("-t") + if max_distance < 1.0: + cmd.extend(["-d", str(max_distance)]) + if max_p_value < 1.0: + cmd.extend(["-v", str(max_p_value)]) + if sketch_size is not None: + if sketch_size <= 0: + raise ValueError("'sketch_size' must be a positive integer.") + cmd.extend(["-s", str(sketch_size)]) + if kmer_size is not None: + if kmer_size <= 0 or kmer_size > 32: + raise ValueError("'kmer_size' must be between 1 and 32.") + cmd.extend(["-k", str(kmer_size)]) + if top_pair_only: + cmd.append("-w") + if amino_acid: + cmd.append("-a") + if amino_acid_01: + cmd.append("-A") + if individual_sequences: + cmd.append("-i") + if write_comments: + cmd.extend(["-c", str(write_comments)]) + if read_comments: + cmd.extend(["-C", str(read_comments)]) + if query_list: + cmd.extend(["-l", str(query_list)]) + + cmd.append(str(reference_sketch)) + + if query_files: + for file_path in query_files: + if not file_path.exists(): + raise FileNotFoundError(f"Query file not found: {file_path}") + cmd.append(str(file_path)) + + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True + ) + output_files = [str(write_comments)] if write_comments else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Mash dist failed", + "return_code": e.returncode, + } + +@mcp.tool() +def mash_screen( + reference_sketch: Path, + query_files: List[Path], + threads: int = 1, + p_value_threshold: float = 0.01, + winner_takes_all: bool = False, + identity_threshold: float = 0.95, + bloom_filter_size: Optional[str] = None, + no_bloom_filter: bool = False, + amino_acid: bool = False, + amino_acid_01: bool = False, + seed: int = 42, +) -> dict: + """ + Determine whether query sequences are within a larger mixture of sequences. + + Args: + reference_sketch: The reference sketch file (.msh). + query_files: One or more query FASTA/FASTQ files. + threads: Number of parallel threads to use. + p_value_threshold: p-value threshold for winning. + winner_takes_all: Only report the best match for each query. + identity_threshold: Identity threshold for winning (0 to 1). + bloom_filter_size: Bloom filter size. Suffixes K, M, G are allowed. + no_bloom_filter: Do not use a Bloom filter (slower). + amino_acid: Use amino acid alphabet (k <= 16). + amino_acid_01: Use amino acid alphabet with 0-1 encoding (k <= 16). + seed: Seed for the hash function. + + Returns: + A dictionary containing the executed command, stdout, and stderr. + """ + # Input validation + if not reference_sketch.exists(): + raise FileNotFoundError(f"Reference sketch not found: {reference_sketch}") + if not query_files: + raise ValueError("'query_files' must be provided and not empty.") + if threads <= 0: + raise ValueError("'threads' must be a positive integer.") + if not (0.0 <= identity_threshold <= 1.0): + raise ValueError("'identity_threshold' must be between 0 and 1.") + if bloom_filter_size and no_bloom_filter: + raise ValueError("'bloom_filter_size' and 'no_bloom_filter' are mutually exclusive.") + if amino_acid and amino_acid_01: + raise ValueError("'amino_acid' and 'amino_acid_01' are mutually exclusive.") + + cmd = ["mash", "screen"] + cmd.extend(["-p", str(threads)]) + cmd.extend(["-S", str(seed)]) + + if p_value_threshold != 0.01: + cmd.extend(["-v", str(p_value_threshold)]) + if winner_takes_all: + cmd.append("-w") + if identity_threshold != 0.95: + cmd.extend(["-i", str(identity_threshold)]) + if bloom_filter_size: + cmd.extend(["-b", bloom_filter_size]) + if no_bloom_filter: + cmd.append("-n") + if amino_acid: + cmd.append("-a") + if amino_acid_01: + cmd.append("-A") + + cmd.append(str(reference_sketch)) + + for file_path in query_files: + if not file_path.exists(): + raise FileNotFoundError(f"Query file not found: {file_path}") + cmd.append(str(file_path)) + + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Mash screen failed", + "return_code": e.returncode, + } + +@mcp.tool() +def mash_triangle( + sketches: Path, + output_file: Optional[Path] = None, + threads: int = 1, + list_names_only: bool = False, + omit_query_vs_query: bool = False, + max_distance: float = 1.0, + max_p_value: float = 1.0, + write_comments: Optional[Path] = None, + read_comments: Optional[Path] = None, +) -> dict: + """ + Estimate a lower-triangular distance matrix from a single sketch file. + + Args: + sketches: A single sketch file (.msh) containing multiple sketches. + output_file: Output file for the distance matrix. Defaults to stdout. + threads: Number of parallel threads to use. + list_names_only: List sequence names only. + omit_query_vs_query: Omit query-vs-query distances. + max_distance: Maximum distance to report. + max_p_value: Maximum p-value to report. + write_comments: Write comments to the specified file. + read_comments: Read comments from the specified file. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # Input validation + if not sketches.exists(): + raise FileNotFoundError(f"Sketch file not found: {sketches}") + if threads <= 0: + raise ValueError("'threads' must be a positive integer.") + + cmd = ["mash", "triangle"] + cmd.extend(["-p", str(threads)]) + + if output_file: + cmd.extend(["-o", str(output_file)]) + if list_names_only: + cmd.append("-l") + if omit_query_vs_query: + cmd.append("-E") + if max_distance < 1.0: + cmd.extend(["-d", str(max_distance)]) + if max_p_value < 1.0: + cmd.extend(["-v", str(max_p_value)]) + if write_comments: + cmd.extend(["-c", str(write_comments)]) + if read_comments: + cmd.extend(["-C", str(read_comments)]) + + cmd.append(str(sketches)) + + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True + ) + output_files = [] + if output_file: + output_files.append(str(output_file)) + if write_comments: + output_files.append(str(write_comments)) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Mash triangle failed", + "return_code": e.returncode, + } + +@mcp.tool() +def mash_paste( + output_name: str, + sketch_files: List[Path], + sketch_list_file: Optional[Path] = None, +) -> dict: + """ + Create a single sketch file from multiple sketch files. + + Args: + output_name: The name/prefix for the output sketch file. '.msh' will be appended. + sketch_files: One or more sketch files to combine. + sketch_list_file: A file containing a list of sketch files, one per line. + + Returns: + A dictionary containing the executed command, stdout, stderr, and the path to the output sketch file. + """ + # Input validation + if not sketch_files and not sketch_list_file: + raise ValueError("Either 'sketch_files' or 'sketch_list_file' must be provided.") + if sketch_files and sketch_list_file: + raise ValueError("'sketch_files' and 'sketch_list_file' are mutually exclusive.") + + cmd = ["mash", "paste", output_name] + + if sketch_list_file: + if not sketch_list_file.exists(): + raise FileNotFoundError(f"Sketch list file not found: {sketch_list_file}") + cmd.extend(["-l", str(sketch_list_file)]) + + if sketch_files: + for file_path in sketch_files: + if not file_path.exists(): + raise FileNotFoundError(f"Sketch file not found: {file_path}") + cmd.append(str(file_path)) + + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True + ) + output_file = f"{output_name}.msh" + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Mash paste failed", + "return_code": e.returncode, + } + +@mcp.tool() +def mash_info( + sketch_files: List[Path], + tabular: bool = False, + show_comments: bool = False, + show_data: bool = False, +) -> dict: + """ + Display information about sketch files. + + Args: + sketch_files: One or more sketch files to inspect. + tabular: Output in a tab-separated format. + show_comments: Show comments within the sketch files. + show_data: Show sketch data (hashes). + + Returns: + A dictionary containing the executed command, stdout, and stderr. + """ + # Input validation + if not sketch_files: + raise ValueError("'sketch_files' must be provided and not empty.") + + cmd = ["mash", "info"] + + if tabular: + cmd.append("-t") + if show_comments: + cmd.append("-c") + if show_data: + cmd.append("-d") + + for file_path in sketch_files: + if not file_path.exists(): + raise FileNotFoundError(f"Sketch file not found: {file_path}") + cmd.append(str(file_path)) + + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Mash info failed", + "return_code": e.returncode, + } + +@mcp.tool() +def mash_bounds() -> dict: + """ + Print a table of Mash error bounds. This command takes no arguments. + + Returns: + A dictionary containing the executed command, stdout, and stderr. + """ + cmd = ["mash", "bounds"] + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Mash bounds failed", + "return_code": e.returncode, + } + +@mcp.tool() +def mash_taxscreen( + taxonomy_map: Path, + screen_output: Path, + output_file: Optional[Path] = None, + threads: int = 1, + taxonomy_tree: Optional[Path] = None, + taxonomy_names: Optional[Path] = None, + min_identity: float = 0.95, + min_hashes: int = 10, + rank: str = "species", + report_unclassified: bool = False, + report_zeroes: bool = False, +) -> dict: + """ + Create a Kraken-style taxonomic report based on mash screen output. + + Args: + taxonomy_map: A file mapping sequence IDs to tax IDs. + screen_output: The output file from 'mash screen'. + output_file: Output file for the report. Defaults to stdout. + threads: Number of parallel threads to use. + taxonomy_tree: Taxonomy tree file (e.g., nodes.dmp). + taxonomy_names: Taxonomy names file (e.g., names.dmp). + min_identity: Minimum identity to consider a hit. + min_hashes: Minimum number of hashes to consider a hit. + rank: Rank to report (e.g., species, genus). + report_unclassified: Report unclassified reads. + report_zeroes: Report taxa with zero hits. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # Input validation + if not taxonomy_map.exists(): + raise FileNotFoundError(f"Taxonomy map file not found: {taxonomy_map}") + if not screen_output.exists(): + raise FileNotFoundError(f"Mash screen output file not found: {screen_output}") + if threads <= 0: + raise ValueError("'threads' must be a positive integer.") + if not (0.0 <= min_identity <= 1.0): + raise ValueError("'min_identity' must be between 0 and 1.") + if min_hashes <= 0: + raise ValueError("'min_hashes' must be a positive integer.") + + cmd = ["mash", "taxscreen"] + + if output_file: + cmd.extend(["-o", str(output_file)]) + if threads > 1: + cmd.extend(["-p", str(threads)]) + if taxonomy_tree: + cmd.extend(["-t", str(taxonomy_tree)]) + if taxonomy_names: + cmd.extend(["-n", str(taxonomy_names)]) + if min_identity != 0.95: + cmd.extend(["-m", str(min_identity)]) + if min_hashes != 10: + cmd.extend(["-l", str(min_hashes)]) + if rank != "species": + cmd.extend(["-r", rank]) + if report_unclassified: + cmd.append("--report-unclassified") + if report_zeroes: + cmd.append("--report-zeroes") + + cmd.append(str(taxonomy_map)) + cmd.append(str(screen_output)) + + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True + ) + output_files = [str(output_file)] if output_file else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Mash taxscreen failed", + "return_code": e.returncode, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mash/app/mash_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mash/app/mash_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b0bfd0506f53a90d50af0e866cd62401f08d5306 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mash/app/mash_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mash/app/mash_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_mash' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mash/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mash/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mash/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mash/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mash/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..59aa6986d816e37f0633fc7e61f2b5d48e83ad7f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mash/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-mash: + build: . + image: mcp-mash:latest + container_name: mcp-mash + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=mash + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mash/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mash/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bad3fd0f70c2665f4210fece911e36ba15aa78c2 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mash/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - mash + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mash/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mash/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mash/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mikado/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mikado/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4a86b54822351d724ec57dd4385403125bb9da77 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mikado/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install mikado via conda (e.g., from bioconda) +RUN conda install -c bioconda mikado -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/mikado_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/mikado_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/mikado_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mikado/app/__pycache__/mikado_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mikado/app/__pycache__/mikado_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0bab2454dca3db0fbc422644d871bae14c12bdb9 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mikado/app/__pycache__/mikado_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mikado/app/mikado_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mikado/app/mikado_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a9ca145741ca88596e51ea47de11abd4750f95a9 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mikado/app/mikado_server.py @@ -0,0 +1,696 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_mikado' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def mikado_configure( + scoring_file: Path, + requirements_file: Path, + preset: str = "standard", + copy_json: Optional[Path] = None, + force: bool = False, +): + """ + Creates template configuration files (scoring and requirements) for Mikado. + + Args: + scoring_file: Path to the scoring file to create (e.g., scoring.yaml). + requirements_file: Path to the requirements file to create (e.g., requirements.yaml). + preset: The preset configuration to use. + copy_json: Path to copy the default JSON schema to. + force: If True, overwrite existing files. + """ + preset_choices = ["standard", "sensitive", "cautious", "mag", "pacbio-isoseq"] + if preset not in preset_choices: + raise ValueError(f"Invalid preset '{preset}'. Choose from {preset_choices}.") + + cmd = [ + "mikado", "configure", + str(scoring_file), + str(requirements_file), + "--preset", preset, + ] + + if copy_json: + cmd.extend(["--copy-json", str(copy_json)]) + if force: + cmd.append("--force") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Mikado configure failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\nStdout: {e.stdout}" + ) from e + + output_files = [str(scoring_file), str(requirements_file)] + if copy_json: + output_files.append(str(copy_json)) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + + +@mcp.tool() +def mikado_prepare( + json_conf: Path, + reference: Path, + transcripts: Path, + output_prefix: str = "mikado", + log_file: Optional[Path] = None, + log_level: str = "INFO", + cpus: int = 1, + seed: Optional[int] = None, + no_cds_validation: bool = False, + write_invalid: Optional[Path] = None, + tempdir: Optional[Path] = None, +): + """ + Prepares transcript data for Mikado by creating a consolidated GFF3 file and transcript sequences. + + Args: + json_conf: Path to the configuration file in JSON format listing input GFF/GTF files. + reference: Path to the reference genome FASTA file. + transcripts: Path to the transcript sequences in FASTA format. + output_prefix: Prefix for the output files. + log_file: Path to the log file. + log_level: Logging level. + cpus: Number of CPUs to use. + seed: Random seed for reproducibility. + no_cds_validation: If True, disables CDS validation against the reference genome. + write_invalid: Path to write invalid transcripts to. + tempdir: Path to a temporary directory. + """ + if not json_conf.exists(): + raise FileNotFoundError(f"Configuration file not found: {json_conf}") + if not reference.exists(): + raise FileNotFoundError(f"Reference genome not found: {reference}") + if not transcripts.exists(): + raise FileNotFoundError(f"Transcripts FASTA not found: {transcripts}") + + log_level_choices = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] + if log_level.upper() not in log_level_choices: + raise ValueError(f"Invalid log level '{log_level}'. Choose from {log_level_choices}.") + + if cpus < 1: + raise ValueError("Number of CPUs must be at least 1.") + + cmd = [ + "mikado", "prepare", + "--json-conf", str(json_conf), + "--reference", str(reference), + "--transcripts", str(transcripts), + "-o", output_prefix, + "--log-level", log_level.upper(), + "--cpus", str(cpus), + ] + + if log_file: + cmd.extend(["--log-file", str(log_file)]) + if seed is not None: + cmd.extend(["--seed", str(seed)]) + if no_cds_validation: + cmd.append("--no-cds-validation") + if write_invalid: + cmd.extend(["--write-invalid", str(write_invalid)]) + if tempdir: + cmd.extend(["--tempdir", str(tempdir)]) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Mikado prepare failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\nStdout: {e.stdout}" + ) from e + + output_files_paths = [ + Path(f"{output_prefix}.loci.gff3"), + Path(f"{output_prefix}.transcripts.fasta"), + ] + if log_file: + output_files_paths.append(log_file) + if write_invalid: + output_files_paths.append(write_invalid) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(p) for p in output_files_paths if p.exists()], + } + + +@mcp.tool() +def mikado_serialise( + json_conf: Path, + output_file: Path = Path("mikado.db"), + blast_xml: Optional[List[Path]] = None, + blast_targets: Optional[Path] = None, + orfs: Optional[List[Path]] = None, + junctions: Optional[List[Path]] = None, + quantification: Optional[List[str]] = None, + db_type: str = "sqlite", + db_name: Optional[str] = None, + db_user: Optional[str] = None, + db_password: Optional[str] = None, + db_host: Optional[str] = None, + db_port: Optional[int] = None, + log_file: Optional[Path] = None, + log_level: str = "INFO", + cpus: int = 1, + chunk_size: int = 10000, + force: bool = False, +): + """ + Loads prepared data and external evidence (BLAST, ORFs, junctions) into a Mikado database. + + Args: + json_conf: Path to the configuration file in JSON format. + output_file: Path to the output database file (for sqlite). + blast_xml: List of paths to BLAST XML results. + blast_targets: Path to a file listing BLAST targets. + orfs: List of paths to ORF predictions in GFF3 format. + junctions: List of paths to Portcullis junctions files in GFF3 format. + quantification: List of quantification files in 'name:path' format. + db_type: Type of database to use. + db_name: Database name (for mysql/postgresql). + db_user: Database user (for mysql/postgresql). + db_password: Database password (for mysql/postgresql). + db_host: Database host (for mysql/postgresql). + db_port: Database port (for mysql/postgresql). + log_file: Path to the log file. + log_level: Logging level. + cpus: Number of CPUs to use. + chunk_size: Number of records to process per chunk. + force: If True, overwrite an existing database. + """ + if not json_conf.exists(): + raise FileNotFoundError(f"Configuration file not found: {json_conf}") + + log_level_choices = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] + if log_level.upper() not in log_level_choices: + raise ValueError(f"Invalid log level '{log_level}'. Choose from {log_level_choices}.") + + db_type_choices = ["sqlite", "mysql", "postgresql"] + if db_type not in db_type_choices: + raise ValueError(f"Invalid db_type '{db_type}'. Choose from {db_type_choices}.") + + cmd = [ + "mikado", "serialise", + "--json-conf", str(json_conf), + "--db-type", db_type, + "--log-level", log_level.upper(), + "--cpus", str(cpus), + "--chunk_size", str(chunk_size), + ] + + if db_type == "sqlite": + cmd.extend(["-o", str(output_file)]) + else: + if not all([db_name, db_user, db_host]): + raise ValueError("For mysql/postgresql, db_name, db_user, and db_host must be provided.") + cmd.extend(["--db-name", db_name, "--db-user", db_user, "--db-host", db_host]) + if db_password: + cmd.extend(["--db-password", db_password]) + if db_port: + cmd.extend(["--db-port", str(db_port)]) + + if blast_xml: + for xml_file in blast_xml: + if not xml_file.exists(): + raise FileNotFoundError(f"BLAST XML file not found: {xml_file}") + cmd.extend(["--xml", str(xml_file)]) + if blast_targets: + if not blast_targets.exists(): + raise FileNotFoundError(f"BLAST targets file not found: {blast_targets}") + cmd.extend(["--blast_targets", str(blast_targets)]) + if orfs: + for orf_file in orfs: + if not orf_file.exists(): + raise FileNotFoundError(f"ORF file not found: {orf_file}") + cmd.extend(["--orfs", str(orf_file)]) + if junctions: + for junc_file in junctions: + if not junc_file.exists(): + raise FileNotFoundError(f"Junctions file not found: {junc_file}") + cmd.extend(["--junctions", str(junc_file)]) + if quantification: + for quant in quantification: + if ":" not in quant or len(quant.split(":")) != 2: + raise ValueError(f"Invalid quantification format: '{quant}'. Expected 'name:path'.") + cmd.extend(["--quantification", quant]) + if log_file: + cmd.extend(["--log-file", str(log_file)]) + if force: + cmd.append("--force") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Mikado serialise failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\nStdout: {e.stdout}" + ) from e + + output_files_list = [] + if db_type == "sqlite": + output_files_list.append(str(output_file)) + if log_file: + output_files_list.append(str(log_file)) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files_list, + } + + +@mcp.tool() +def mikado_pick( + json_conf: Path, + output_file: Path, + scoring_file: Path, + requirements_file: Path, + reference: Path, + subloci_out: Optional[Path] = None, + loci_out: Optional[Path] = None, + stats_out: Optional[Path] = None, + write_scores: Optional[Path] = None, + log_file: Optional[Path] = None, + log_level: str = "INFO", + cpus: int = 1, + seed: Optional[int] = None, + mode: str = "permissive", + max_intron: Optional[int] = None, + min_intron_len: int = 20, + max_intron_overlap: int = 10, + num_genes: Optional[int] = None, + shuffle: bool = False, + no_chimeras: bool = False, + keep_chimeras: bool = False, +): + """ + Selects the best transcript models for each locus based on scoring and requirements. + + Args: + json_conf: Path to the configuration file in JSON format. + output_file: Path for the main output GFF3 file. + scoring_file: Path to the scoring YAML file. + requirements_file: Path to the requirements YAML file. + reference: Path to the reference genome FASTA file. + subloci_out: Path to output GFF3 with subloci information. + loci_out: Path to output GFF3 with loci information. + stats_out: Path to output statistics file in JSON format. + write_scores: Path to write detailed scores to. + log_file: Path to the log file. + log_level: Logging level. + cpus: Number of CPUs to use. + seed: Random seed for reproducibility. + mode: Selection mode, 'permissive' or 'strict'. + max_intron: Maximum allowed intron size. + min_intron_len: Minimum intron length. + max_intron_overlap: Maximum overlap between introns. + num_genes: Limit the number of genes to process (for testing). + shuffle: If True, shuffle genes before processing. + no_chimeras: If True, disable chimera detection. + keep_chimeras: If True, keep chimeric transcripts in the output. + """ + if not json_conf.exists(): + raise FileNotFoundError(f"Configuration file not found: {json_conf}") + if not scoring_file.exists(): + raise FileNotFoundError(f"Scoring file not found: {scoring_file}") + if not requirements_file.exists(): + raise FileNotFoundError(f"Requirements file not found: {requirements_file}") + if not reference.exists(): + raise FileNotFoundError(f"Reference genome not found: {reference}") + + log_level_choices = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] + if log_level.upper() not in log_level_choices: + raise ValueError(f"Invalid log level '{log_level}'. Choose from {log_level_choices}.") + + mode_choices = ["permissive", "strict"] + if mode not in mode_choices: + raise ValueError(f"Invalid mode '{mode}'. Choose from {mode_choices}.") + + cmd = [ + "mikado", "pick", + "--json-conf", str(json_conf), + "-o", str(output_file), + "--scoring-file", str(scoring_file), + "--requirements-file", str(requirements_file), + "--reference", str(reference), + "--log-level", log_level.upper(), + "--cpus", str(cpus), + "--mode", mode, + "--min-intron-len", str(min_intron_len), + "--max-intron-overlap", str(max_intron_overlap), + ] + + if subloci_out: + cmd.extend(["--subloci-out", str(subloci_out)]) + if loci_out: + cmd.extend(["--loci-out", str(loci_out)]) + if stats_out: + cmd.extend(["--stats-out", str(stats_out)]) + if write_scores: + cmd.extend(["--write-scores", str(write_scores)]) + if log_file: + cmd.extend(["--log-file", str(log_file)]) + if seed is not None: + cmd.extend(["--seed", str(seed)]) + if max_intron is not None: + cmd.extend(["--max-intron", str(max_intron)]) + if num_genes is not None: + cmd.extend(["--num-genes", str(num_genes)]) + if shuffle: + cmd.append("--shuffle") + if no_chimeras: + cmd.append("--no-chimeras") + if keep_chimeras: + cmd.append("--keep-chimeras") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Mikado pick failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\nStdout: {e.stdout}" + ) from e + + output_files_paths = [output_file] + if subloci_out: + output_files_paths.append(subloci_out) + if loci_out: + output_files_paths.append(loci_out) + if stats_out: + output_files_paths.append(stats_out) + if write_scores: + output_files_paths.append(write_scores) + if log_file: + output_files_paths.append(log_file) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(p) for p in output_files_paths if p.exists()], + } + + +@mcp.tool() +def mikado_compare( + reference: Path, + predicted: Path, + output_prefix: str, + log_file: Optional[Path] = None, + log_level: str = "INFO", + cpus: int = 1, + labels: str = "reference,predicted", + json_output: bool = False, +): + """ + Compares two annotation files (reference vs. predicted) and generates statistics. + + Args: + reference: Path to the reference annotation file (GFF3/GTF). + predicted: Path to the predicted annotation file (GFF3/GTF). + output_prefix: Prefix for output files. + log_file: Path to the log file. + log_level: Logging level. + cpus: Number of CPUs to use. + labels: Comma-separated labels for reference and prediction. + json_output: If True, output statistics in JSON format. + """ + if not reference.exists(): + raise FileNotFoundError(f"Reference annotation not found: {reference}") + if not predicted.exists(): + raise FileNotFoundError(f"Predicted annotation not found: {predicted}") + + log_level_choices = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] + if log_level.upper() not in log_level_choices: + raise ValueError(f"Invalid log level '{log_level}'. Choose from {log_level_choices}.") + + cmd = [ + "mikado", "compare", + "-r", str(reference), + "-p", str(predicted), + "-o", output_prefix, + "--log-level", log_level.upper(), + "--cpus", str(cpus), + "--labels", labels, + ] + + if log_file: + cmd.extend(["-l", str(log_file)]) + if json_output: + cmd.append("--json") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Mikado compare failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\nStdout: {e.stdout}" + ) from e + + # Mikado compare creates several output files with the given prefix + # We can list the most common ones. + output_files_paths = [ + Path(f"{output_prefix}.stats.tsv"), + Path(f"{output_prefix}.tmap"), + Path(f"{output_prefix}.refmap"), + ] + if json_output: + output_files_paths.append(Path(f"{output_prefix}.stats.json")) + if log_file: + output_files_paths.append(log_file) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(p) for p in output_files_paths if p.exists()], + } + + +@mcp.tool() +def mikado_util_blast_to_gff3( + blast_xml: Path, + output_gff3: Path, + log_file: Optional[Path] = None, + log_level: str = "INFO", +): + """ + Utility to convert BLAST XML results to GFF3 format. + + Args: + blast_xml: Path to the input BLAST XML file. + output_gff3: Path for the output GFF3 file. + log_file: Path to the log file. + log_level: Logging level. + """ + if not blast_xml.exists(): + raise FileNotFoundError(f"BLAST XML file not found: {blast_xml}") + + log_level_choices = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] + if log_level.upper() not in log_level_choices: + raise ValueError(f"Invalid log level '{log_level}'. Choose from {log_level_choices}.") + + cmd = [ + "mikado", "util", "blast-to-gff3", + str(blast_xml), + str(output_gff3), + "--log-level", log_level.upper(), + ] + if log_file: + cmd.extend(["--log-file", str(log_file)]) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Mikado util blast-to-gff3 failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\nStdout: {e.stdout}" + ) from e + + output_files_list = [str(output_gff3)] + if log_file: + output_files_list.append(str(log_file)) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files_list, + } + + +@mcp.tool() +def mikado_util_gff_to_fasta( + input_gff: Path, + reference_fasta: Path, + output_fasta: Path, + feature: str = "transcript", + id_attribute: str = "ID", + log_file: Optional[Path] = None, + log_level: str = "INFO", +): + """ + Utility to extract sequences from a GFF file given a reference genome. + + Args: + input_gff: Path to the input GFF/GTF file. + reference_fasta: Path to the reference genome FASTA file. + output_fasta: Path for the output FASTA file. + feature: Feature type to extract (e.g., 'transcript', 'CDS'). + id_attribute: GFF attribute to use for FASTA headers. + log_file: Path to the log file. + log_level: Logging level. + """ + if not input_gff.exists(): + raise FileNotFoundError(f"Input GFF file not found: {input_gff}") + if not reference_fasta.exists(): + raise FileNotFoundError(f"Reference FASTA file not found: {reference_fasta}") + + log_level_choices = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] + if log_level.upper() not in log_level_choices: + raise ValueError(f"Invalid log level '{log_level}'. Choose from {log_level_choices}.") + + cmd = [ + "mikado", "util", "gff-to-fasta", + str(input_gff), + str(reference_fasta), + str(output_fasta), + "--feature", feature, + "--id-attribute", id_attribute, + "--log-level", log_level.upper(), + ] + if log_file: + cmd.extend(["--log-file", str(log_file)]) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Mikado util gff-to-fasta failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\nStdout: {e.stdout}" + ) from e + + output_files_list = [str(output_fasta)] + if log_file: + output_files_list.append(str(log_file)) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files_list, + } + + +@mcp.tool() +def mikado_util_transcripts_to_gff3( + input_fasta: Path, + output_gff3: Path, + log_file: Optional[Path] = None, + log_level: str = "INFO", +): + """ + Utility to convert a transcript FASTA file to a basic GFF3 representation. + + Args: + input_fasta: Path to the input transcript FASTA file. + output_gff3: Path for the output GFF3 file. + log_file: Path to the log file. + log_level: Logging level. + """ + if not input_fasta.exists(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + + log_level_choices = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] + if log_level.upper() not in log_level_choices: + raise ValueError(f"Invalid log level '{log_level}'. Choose from {log_level_choices}.") + + cmd = [ + "mikado", "util", "transcripts-to-gff3", + str(input_fasta), + str(output_gff3), + "--log-level", log_level.upper(), + ] + if log_file: + cmd.extend(["--log-file", str(log_file)]) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Mikado util transcripts-to-gff3 failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\nStdout: {e.stdout}" + ) from e + + output_files_list = [str(output_gff3)] + if log_file: + output_files_list.append(str(log_file)) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files_list, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mikado/app/mikado_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mikado/app/mikado_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4ab1e7347340946e2b4de34d352582ad354079ad --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mikado/app/mikado_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mikado/app/mikado_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_mikado' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mikado/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mikado/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mikado/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mikado/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mikado/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f8967c46303e6f0c253991aa1ecd52cff09dab97 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mikado/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-mikado: + build: . + image: mcp-mikado:latest + container_name: mcp-mikado + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=mikado + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mikado/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mikado/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8ad2f4c84ba049689dfc79c2c7e5f384479c35c8 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mikado/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - mikado + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mikado/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mikado/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mikado/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mobivision-m/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mobivision-m/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..bfa87ff61c9158931c543ad5e8e51fdebeace593 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mobivision-m/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install mobivision-m via conda (e.g., from bioconda) +RUN conda install -c bioconda mobivision-m -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/mobivision-m_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/mobivision-m_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/mobivision-m_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mobivision-m/app/__pycache__/mobivision-m_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mobivision-m/app/__pycache__/mobivision-m_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9a593f356ab25de622a933bf0706ae65fa83140f Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mobivision-m/app/__pycache__/mobivision-m_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mobivision-m/app/mobivision-m_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mobivision-m/app/mobivision-m_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..446b3cf7d8ff482121ea24b264ac03601e83d320 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mobivision-m/app/mobivision-m_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mobivision-m/app/mobivision-m_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_mobivision_m' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mobivision-m/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mobivision-m/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mobivision-m/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mobivision-m/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mobivision-m/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..5ededa3eb14eef0acc4320e839bb1a3b34f259a2 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mobivision-m/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-mobivision-m: + build: . + image: mcp-mobivision-m:latest + container_name: mcp-mobivision-m + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=mobivision-m + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mobivision-m/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mobivision-m/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c87dc0b4136764921266497306cd47dbbcc7f495 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mobivision-m/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - mobivision-m + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mobivision-m/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mobivision-m/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mobivision-m/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_multiqc-xenium-extra/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_multiqc-xenium-extra/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e4129a2c36e0fe2ebc2fcdfdc4409cad110b5ef7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_multiqc-xenium-extra/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install multiqc-xenium-extra via conda (e.g., from bioconda) +RUN conda install -c bioconda multiqc-xenium-extra -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY multiqc-xenium-extra_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/multiqc-xenium-extra_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/multiqc-xenium-extra_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_multiqc-xenium-extra/app/__pycache__/multiqc-xenium-extra_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_multiqc-xenium-extra/app/__pycache__/multiqc-xenium-extra_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..6f32cec20c70b90faef18eae99618d75c74386cc Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_multiqc-xenium-extra/app/__pycache__/multiqc-xenium-extra_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_multiqc-xenium-extra/app/multiqc-xenium-extra_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_multiqc-xenium-extra/app/multiqc-xenium-extra_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8d4b5ff4a44712a80a4bd6ad08d2489f381b1a6f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_multiqc-xenium-extra/app/multiqc-xenium-extra_server.py @@ -0,0 +1,205 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, List +import tempfile + +# Configure logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# MCP decorator is assumed to be available in the execution environment. +# +# from mcp import mcp + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_multiqc_xenium_extra' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_multiqc_xenium( + analysis_dir: Path, + outdir: Optional[Path] = None, + force: bool = False, + title: Optional[str] = None, + filename: Optional[str] = None, + template: Optional[str] = None, + config_file: Optional[Path] = None, + dirs: bool = False, + dirs_depth: Optional[int] = None, + ignore: Optional[List[str]] = None, + file_list: Optional[Path] = None, + module: Optional[List[str]] = None, + exclude: Optional[List[str]] = None, + data_format: Optional[str] = None, + zip_data_dir: bool = False, + no_data_dir: bool = False, + export: bool = False, + pdf: bool = False, + flat: bool = False, + interactive: bool = True, + verbose: bool = False, + quiet: bool = False, +) -> dict: + """ + Runs MultiQC with the multiqc-xenium-extra plugin on a given analysis directory. + + This tool generates a comprehensive report from 10x Genomics Xenium output files + by leveraging the MultiQC framework and the specialized Xenium plugin. It wraps + the standard 'multiqc' command-line tool. + + Args: + analysis_dir: Path to the directory containing analysis results to be scanned. + outdir: Directory to write the MultiQC report to. If not provided, a temporary directory will be used. + force: If True, overwrite any existing reports. + title: Title for the MultiQC report. + filename: Name for the output report file. Defaults to 'multiqc_report.html'. + template: Name of a report template to use (e.g., 'default', 'simple'). + config_file: Path to a custom MultiQC configuration file in YAML or JSON format. + dirs: If True, search subdirectories of analysis_dir for analysis files. + dirs_depth: Limit the subdirectory search depth. Only used if `dirs` is True. + ignore: List of file/directory name patterns to ignore. Can be specified multiple times. + file_list: Path to a file containing a list of files to be searched, one per line. + module: List of specific MultiQC modules to run. Can be specified multiple times. + exclude: List of MultiQC modules to exclude from the report. Can be specified multiple times. + data_format: Format for the exported data ('tsv', 'yaml', 'json'). + zip_data_dir: If True, compress the multiqc_data directory into a zip file. + no_data_dir: If True, do not create the multiqc_data directory. + export: If True, export plots as static images. + pdf: If True, create a PDF version of the report. Requires external dependencies like LaTeX. + flat: If True, use a flat directory structure for exported plots. + interactive: If True (default), use interactive plots in the report. Set to False for static plots. + verbose: If True, increase the verbosity of the MultiQC output. + quiet: If True, suppress all console output from MultiQC. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not analysis_dir.is_dir(): + raise ValueError(f"Analysis directory not found: {analysis_dir}") + + if config_file and not config_file.is_file(): + raise ValueError(f"Config file not found: {config_file}") + + if file_list and not file_list.is_file(): + raise ValueError(f"File list not found: {file_list}") + + if data_format and data_format not in ["tsv", "yaml", "json"]: + raise ValueError(f"Invalid data_format: '{data_format}'. Must be one of 'tsv', 'yaml', 'json'.") + + if verbose and quiet: + raise ValueError("Cannot set both 'verbose' and 'quiet' to True.") + + # --- Command Construction --- + cmd = ["multiqc"] + + # Boolean flags + if force: cmd.append("--force") + if dirs: cmd.append("--dirs") + if zip_data_dir: cmd.append("--zip-data-dir") + if no_data_dir: cmd.append("--no-data-dir") + if export: cmd.append("--export") + if pdf: cmd.append("--pdf") + if flat: cmd.append("--flat") + if not interactive: cmd.append("--static") + if verbose: cmd.append("--verbose") + if quiet: cmd.append("--quiet") + + # Handle output directory + temp_dir_manager = None + if outdir: + outdir.mkdir(parents=True, exist_ok=True) + cmd.extend(["--outdir", str(outdir)]) + effective_outdir = outdir + else: + temp_dir_manager = tempfile.TemporaryDirectory() + effective_outdir = Path(temp_dir_manager.name) + cmd.extend(["--outdir", str(effective_outdir)]) + + # Arguments with values + if title: cmd.extend(["--title", title]) + if filename: cmd.extend(["--filename", filename]) + if template: cmd.extend(["--template", template]) + if config_file: cmd.extend(["--config", str(config_file)]) + if dirs_depth is not None: cmd.extend(["--dirs-depth", str(dirs_depth)]) + if data_format: cmd.extend(["--data-format", data_format]) + if file_list: cmd.extend(["--file-list", str(file_list)]) + + # List-based arguments + if ignore: + for pattern in ignore: cmd.extend(["--ignore", pattern]) + if module: + for mod in module: cmd.extend(["--module", mod]) + if exclude: + for ex in exclude: cmd.extend(["--exclude", ex]) + + # Positional argument + cmd.append(str(analysis_dir)) + + command_executed = " ".join(cmd) + logger.info(f"Executing command: {command_executed}") + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + # --- Output Handling --- + output_files = [] + report_name = filename if filename else "multiqc_report.html" + if not report_name.lower().endswith(('.html', '.htm')): + report_name += '.html' + + report_path = effective_outdir / report_name + if report_path.is_file(): + output_files.append(str(report_path)) + + data_dir_path = effective_outdir / "multiqc_data" + if data_dir_path.is_dir(): + output_files.append(str(data_dir_path)) + + zip_path = effective_outdir / "multiqc_data.zip" + if zip_data_dir and zip_path.is_file(): + output_files.append(str(zip_path)) + + pdf_path = report_path.with_suffix('.pdf') + if pdf and pdf_path.is_file(): + output_files.append(str(pdf_path)) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + + except FileNotFoundError: + error_msg = "Error: 'multiqc' command not found. Please ensure MultiQC is installed and in your system's PATH." + logger.error(error_msg) + return { + "command_executed": command_executed, + "stdout": "", + "stderr": error_msg, + "output_files": [], + } + except subprocess.CalledProcessError as e: + logger.error(f"MultiQC execution failed with exit code {e.returncode}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + finally: + # Clean up the temporary directory if it was created + if temp_dir_manager: + temp_dir_manager.cleanup() + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_multiqc-xenium-extra/app/multiqc-xenium-extra_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_multiqc-xenium-extra/app/multiqc-xenium-extra_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2356ba987ea742a3abc7520b176f4bb6a1172fdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_multiqc-xenium-extra/app/multiqc-xenium-extra_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_multiqc-xenium-extra/app/multiqc-xenium-extra_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_multiqc_xenium_extra' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_multiqc-xenium-extra/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_multiqc-xenium-extra/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b9e9c28a997ae1603cddda615e90ceceb650afb3 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_multiqc-xenium-extra/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-multiqc-xenium-extra: + build: . + image: mcp-multiqc-xenium-extra:latest + container_name: mcp-multiqc-xenium-extra + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=multiqc-xenium-extra + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_multiqc-xenium-extra/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_multiqc-xenium-extra/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5c7b2df0639ec4c3777a2fc7261d9fe8cceefa69 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_multiqc-xenium-extra/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - multiqc-xenium-extra + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_multiqc-xenium-extra/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_multiqc-xenium-extra/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_multiqc-xenium-extra/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mysql-connector-c/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mysql-connector-c/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1a00f9a2ad87d200ec204b40da9797c0f07ca2c1 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mysql-connector-c/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install mysql-connector-c via conda (e.g., from bioconda) +RUN conda install -c bioconda mysql-connector-c -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/mysql-connector-c_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/mysql-connector-c_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/mysql-connector-c_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mysql-connector-c/app/__pycache__/mysql-connector-c_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mysql-connector-c/app/__pycache__/mysql-connector-c_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..654c49a50e0ae43213fe55290d0fbc5a4e72e9ec Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mysql-connector-c/app/__pycache__/mysql-connector-c_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mysql-connector-c/app/mysql-connector-c_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mysql-connector-c/app/mysql-connector-c_server.py new file mode 100644 index 0000000000000000000000000000000000000000..94c1699c4ed12589a726dccc97e09be73f1fad47 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mysql-connector-c/app/mysql-connector-c_server.py @@ -0,0 +1,114 @@ +import logging +import subprocess +from pathlib import Path +from typing import Literal, Dict, List, Any + +# MCP decorator is not imported as per instructions +# from mcp import tool as mcp.tool + +# Configure logging +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') + +MysqlConfigOption = Literal[ + "cflags", + "cxxflags", + "include", + "libs", + "libs_r", + "socket", + "port", + "version", + "version-comment", + "version-extra", + "version-major", + "version-minor", + "version-patch", + "version-suffix", +] + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_mysql_connector_c' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def mysql_config( + option: MysqlConfigOption, +) -> Dict[str, Any]: + """ + Wraps the mysql_config utility to get compiler flags and other information for the MySQL C Connector. + + The mysql-connector-c package itself is a library. This tool provides an interface to the + `mysql_config` utility, which is used to obtain build-time information like compiler flags, + linker flags, and version details necessary for compiling applications against the connector. + + Args: + option: The information to retrieve. Each option provides a specific piece of data. + - cflags: C compiler flags to find include files and critical compiler flags. + - cxxflags: C++ compiler flags. + - include: C include server-version-specific file paths. + - libs: Libraries to link with. + - libs_r: Libraries to link with for thread-safe clients. + - socket: The default socket file path. + - port: The default TCP/IP port. + - version: The client library version. + - version-comment: The version comment. + - version-extra: Extra version information. + - version-major: The major version number. + - version-minor: The minor version number. + - version-patch: The patch level. + - version-suffix: The version suffix. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # Input validation is implicitly handled by the Literal type hint in a real MCP environment. + # No file paths to validate for this tool. + + command = ["mysql_config", f"--{option}"] + command_str = " ".join(command) + logging.info(f"Executing command: {command_str}") + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout.strip(), + "stderr": result.stderr.strip(), + "output_files": [], + } + except FileNotFoundError: + error_message = ( + "Error: 'mysql_config' command not found. " + "Please ensure mysql-connector-c or a similar MySQL development package is installed " + "and that 'mysql_config' is in the system's PATH." + ) + logging.error(error_message) + # In a real scenario, you might raise a specific exception. + # Here, we return a structured error as per requirements. + return { + "command_executed": command_str, + "stdout": "", + "stderr": error_message, + "output_files": [], + "error": "FileNotFoundError" + } + except subprocess.CalledProcessError as e: + logging.error(f"Command failed with exit code {e.returncode}") + logging.error(f"Stderr: {e.stderr.strip()}") + return { + "command_executed": command_str, + "stdout": e.stdout.strip(), + "stderr": e.stderr.strip(), + "output_files": [], + "error": "CalledProcessError", + "return_code": e.returncode + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mysql-connector-c/app/mysql-connector-c_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mysql-connector-c/app/mysql-connector-c_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..18e23895acacaf2611d1a981ec84143410a24480 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mysql-connector-c/app/mysql-connector-c_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mysql-connector-c/app/mysql-connector-c_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_mysql_connector_c' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mysql-connector-c/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mysql-connector-c/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mysql-connector-c/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mysql-connector-c/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mysql-connector-c/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..36aba86d4e1117b651e4d6a9a0f36c23e1d11cea --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mysql-connector-c/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-mysql-connector-c: + build: . + image: mcp-mysql-connector-c:latest + container_name: mcp-mysql-connector-c + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=mysql-connector-c + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mysql-connector-c/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mysql-connector-c/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eff1fc6f3cf3888cac196835b73dc651db394bd4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mysql-connector-c/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - mysql-connector-c + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mysql-connector-c/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mysql-connector-c/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mysql-connector-c/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mztosqlite/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mztosqlite/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d95d7d31ba8cbbaed7ed9e2e7d32a2beb7fb8724 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mztosqlite/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install mztosqlite via conda (e.g., from bioconda) +RUN conda install -c bioconda mztosqlite -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/mztosqlite_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/mztosqlite_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/mztosqlite_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mztosqlite/app/__pycache__/mztosqlite_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mztosqlite/app/__pycache__/mztosqlite_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17d553f49fa8a4180cf256db8f32bef7b20caf09 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mztosqlite/app/__pycache__/mztosqlite_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mztosqlite/app/mztosqlite_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mztosqlite/app/mztosqlite_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c42f0a627ad15441a7aeffccbfe4770b9bb3a6d6 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mztosqlite/app/mztosqlite_server.py @@ -0,0 +1,103 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict + +# MCP decorator would be here in a real scenario +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_mztosqlite' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def mztosqlite( + mzid: Path, + output_db: Path, + scan_files: Optional[List[Path]] = None, + scans_are_ms1: bool = False, + include_spectra: bool = False, + include_chromatograms: bool = False, +) -> Dict: + """ + Convert proteomics data files into a SQLite database. + + This tool extracts data from proteomics mzIdentML and mass spec scan files + (e.g., mzML, MGF) and stores it in a SQLite database. The resulting database + is intended to support interactive visualizations. + + Args: + mzid: Path to the input mzIdentML file. + output_db: Path for the output SQLite database file. + scan_files: Optional list of paths to mass spec scan files (e.g., mzML, MGF). + scans_are_ms1: Set to True if the scans are MS1 data, for example from + a metabolomics LC-MS analysis. Defaults to False. + include_spectra: Include MS/MS spectra in the database. This can make the + database file very large. Defaults to False. + include_chromatograms: Include chromatograms in the database. This can also + make the database file very large. Defaults to False. + + Returns: + A dictionary containing the execution details and output file path. + """ + # 1. Input Validation + if not mzid.is_file(): + raise FileNotFoundError(f"Input mzIdentML file not found: {mzid}") + + if scan_files: + for scan_file in scan_files: + if not scan_file.is_file(): + raise FileNotFoundError(f"Input scan file not found: {scan_file}") + + # Ensure output directory exists + output_db.parent.mkdir(parents=True, exist_ok=True) + + # 2. Command Construction + # The executable name 'mztosqlite' is a wrapper script provided by the Conda package. + cmd = [ + "mztosqlite", + str(output_db), + str(mzid), + ] + + if scan_files: + cmd.extend([str(sf) for sf in scan_files]) + + # Based on the Galaxy wrapper, this parameter is passed as --key=value + cmd.append(f"--scans_are_ms1={scans_are_ms1}") + + # These parameters are flags, present only if True + if include_spectra: + cmd.append("--include_spectra") + if include_chromatograms: + cmd.append("--include_chromatograms") + + # 3. Subprocess Execution + command_str = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + # 4. Structured Result Return (Success) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"output_db": str(output_db)} + } + except FileNotFoundError: + raise RuntimeError("mztosqlite executable not found. Please ensure it is installed and in your PATH.") + except subprocess.CalledProcessError as e: + # 4. Structured Result Return (Failure) + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"mztosqlite failed with return code {e.returncode}", + "return_code": e.returncode, + "output_files": {} + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mztosqlite/app/mztosqlite_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mztosqlite/app/mztosqlite_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ed9d3d7554c24b2801846e2d811a1e1490f8d8e1 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mztosqlite/app/mztosqlite_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mztosqlite/app/mztosqlite_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_mztosqlite' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mztosqlite/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mztosqlite/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mztosqlite/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mztosqlite/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mztosqlite/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..8bc30f004b7f293246c2cf00d53c19f8f5749ef6 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mztosqlite/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-mztosqlite: + build: . + image: mcp-mztosqlite:latest + container_name: mcp-mztosqlite + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=mztosqlite + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mztosqlite/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mztosqlite/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3d32504de88e7a30873a2aef67ed78043e8d62d7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mztosqlite/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - mztosqlite + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mztosqlite/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mztosqlite/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_mztosqlite/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanocomp/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanocomp/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e0f11962326698aa1529e7c89ffd83aa06de5bc3 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanocomp/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install nanocomp via conda (e.g., from bioconda) +RUN conda install -c bioconda nanocomp -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/nanocomp_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/nanocomp_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/nanocomp_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanocomp/app/__pycache__/nanocomp_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanocomp/app/__pycache__/nanocomp_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..befa8eced4f4a3d751b5ca20272ecb4276b56735 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanocomp/app/__pycache__/nanocomp_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanocomp/app/nanocomp_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanocomp/app/nanocomp_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5603e5dace82ded010c5ebe18fb33a14431b889f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanocomp/app/nanocomp_server.py @@ -0,0 +1,198 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Literal + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_nanocomp' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def nanocomp( + outdir: str, + fastq: Optional[List[str]] = None, + fasta: Optional[List[str]] = None, + summary: Optional[List[str]] = None, + bam: Optional[List[str]] = None, + threads: int = 1, + prefix: Optional[str] = None, + verbose: bool = False, + raw: bool = False, + readtype: Optional[Literal["1D", "2D", "1D2"]] = None, + barcoded: bool = False, + split_runs: Optional[str] = None, + format: Literal["png", "jpg", "jpeg", "webp", "svg", "pdf", "eps", "json"] = "png", + names: Optional[List[str]] = None, + colors: Optional[List[str]] = None, + plot: Literal["violin", "box", "ridge", "false"] = "violin", + title: Optional[str] = None, + minlength: int = 0, + maxlength: Optional[int] = None, + minqual: int = 0, +): + """ + Compares multiple runs of Oxford Nanopore sequencing data and alignments. + + Generates violin or box plots for length, quality, and percent identity, + as well as dynamic read length histograms and cumulative yield plots. + + Args: + outdir: Directory to save output files. + fastq: List of paths to fastq files. + fasta: List of paths to fasta files. + summary: List of paths to sequencing_summary files generated by albacore/guppy. + bam: List of paths to sorted bam files. + threads: Number of threads to use (default: 1). + prefix: Prefix for the output file names. + verbose: Increase verbosity. + raw: Store the statistical data in a tab-separated file. + readtype: Which read type to extract information about from summary files. + barcoded: Use if the summary file contains barcoded data. + split_runs: Path to a file to split the summary file by run_id. + format: Output format for the plots (default: png). + names: Names to use for the runs in the plots. + colors: Colors to use for the runs in the plots. + plot: Type of plot to generate (default: violin). + title: Title for the plots. + minlength: Filter reads shorter than this length (default: 0). + maxlength: Filter reads longer than this length. + minqual: Filter reads with a quality score lower than this (default: 0). + """ + # --- Input Validation --- + input_sources = [fastq, fasta, summary, bam] + active_sources = [s for s in input_sources if s is not None and len(s) > 0] + + if len(active_sources) != 1: + return { + "error": "Exactly one input data source type (fastq, fasta, summary, or bam) must be provided and cannot be empty.", + "command_executed": "" + } + + # Validate file existence + all_input_paths = [] + if fastq: all_input_paths.extend(fastq) + if fasta: all_input_paths.extend(fasta) + if summary: all_input_paths.extend(summary) + if bam: all_input_paths.extend(bam) + + for path_str in all_input_paths: + p = Path(path_str) + if not p.exists(): + return {"error": f"Input file not found: {path_str}", "command_executed": ""} + + if split_runs: + if not Path(split_runs).exists(): + return {"error": f"Split runs file not found: {split_runs}", "command_executed": ""} + + if threads < 1: + return {"error": "Threads must be at least 1.", "command_executed": ""} + + # Create output directory + out_path = Path(outdir) + out_path.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd = ["NanoComp"] + + # Add input files + if fastq: + cmd.extend(["--fastq"] + fastq) + elif fasta: + cmd.extend(["--fasta"] + fasta) + elif summary: + cmd.extend(["--summary"] + summary) + elif bam: + cmd.extend(["--bam"] + bam) + + # Add general options + cmd.extend(["-o", str(out_path)]) + cmd.extend(["-t", str(threads)]) + + if prefix: + cmd.extend(["-p", prefix]) + if verbose: + cmd.append("--verbose") + if raw: + cmd.append("--raw") + + # Add filtering/transforming options + if readtype: + cmd.extend(["--readtype", readtype]) + if barcoded: + cmd.append("--barcoded") + if split_runs: + cmd.extend(["--split_runs", split_runs]) + + cmd.extend(["--minlength", str(minlength)]) + if maxlength is not None: + cmd.extend(["--maxlength", str(maxlength)]) + cmd.extend(["--minqual", str(minqual)]) + + # Add plotting options + cmd.extend(["-f", format]) + if names: + cmd.extend(["-n"] + names) + if colors: + cmd.extend(["-c"] + colors) + cmd.extend(["--plot", plot]) + if title: + cmd.extend(["--title", title]) + + # --- Execution --- + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + # Collect output files + output_files = [str(p) for p in out_path.glob("**/*") if p.is_file()] + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except FileNotFoundError: + return { + "error": "NanoComp executable not found. Please ensure it is installed and in your PATH.", + "command_executed": " ".join(cmd) + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"NanoComp failed with return code {e.returncode}", + "output_files": [str(p) for p in out_path.glob("**/*") if p.is_file()] + } + +@mcp.tool() +def nanocomp_version(): + """ + Check the version of NanoComp installed. + """ + cmd = ["NanoComp", "--version"] + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout.strip(), + "stderr": result.stderr + } + except (FileNotFoundError, subprocess.CalledProcessError) as e: + return { + "error": "Could not retrieve NanoComp version.", + "details": str(e) + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanocomp/app/nanocomp_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanocomp/app/nanocomp_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f94715162d0165252510693e8dca4964a80f46f5 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanocomp/app/nanocomp_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_nanocomp/app/nanocomp_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_nanocomp' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanocomp/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanocomp/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanocomp/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanocomp/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanocomp/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..9f7291bd2446fd35b19fbf86967f026006d6eb9c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanocomp/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-nanocomp: + build: . + image: mcp-nanocomp:latest + container_name: mcp-nanocomp + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=nanocomp + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanocomp/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanocomp/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..18ac4c93aeb4b365d64ba1ec40d0dde7e53af274 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanocomp/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - nanocomp + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanocomp/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanocomp/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanocomp/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanoget/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanoget/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..78e1c63a171d1e1dc38d13e7aad3737788a16e2f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanoget/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-nanoget: + build: . + image: mcp-nanoget:latest + container_name: mcp-nanoget + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=nanoget + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanoget/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanoget/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..78369464ab60a2dd9eb3ce821c01e5d7ab4038b6 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanoget/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - nanoget + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanopolish/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanopolish/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1dac8c5f4e6733fee2674a17fb2862b4e359e189 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanopolish/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install nanopolish via conda (e.g., from bioconda) +RUN conda install -c bioconda nanopolish -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/nanopolish_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/nanopolish_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/nanopolish_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanopolish/app/__pycache__/nanopolish_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanopolish/app/__pycache__/nanopolish_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..caacdfa8754d2aef9a332e5cec68ff54f5fe14df Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanopolish/app/__pycache__/nanopolish_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanopolish/app/nanopolish_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanopolish/app/nanopolish_server.py new file mode 100644 index 0000000000000000000000000000000000000000..54deb1e71a3cfd9c69f3c703eb690c85435cedf5 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanopolish/app/nanopolish_server.py @@ -0,0 +1,417 @@ +import subprocess +from pathlib import Path +from typing import Optional, List + +# In a real MCP environment, you would import the decorator like this: +# from mcp import tool as mcp_tool +# For this exercise, we'll define a dummy decorator to make the code runnable. +class mcp: + def tool(func): + return func + +@mcp.tool +def nanopolish_index( + reads_file: Path, + directory: Optional[Path] = None, + sequencing_summary: Optional[Path] = None, + fast5_files: Optional[Path] = None, + verbose: bool = False, +): + """ + Builds an index mapping from basecalled reads to the signals in the FAST5 files. + This is a prerequisite for all other nanopolish modules. + """ + # Input validation + if not reads_file.is_file(): + raise FileNotFoundError(f"Reads file not found: {reads_file}") + + if not any([directory, sequencing_summary, fast5_files]): + raise ValueError("At least one of --directory, --sequencing-summary, or --fast5-files must be provided.") + + if directory and not directory.is_dir(): + raise NotADirectoryError(f"FAST5 directory not found: {directory}") + if sequencing_summary and not sequencing_summary.is_file(): + raise FileNotFoundError(f"Sequencing summary file not found: {sequencing_summary}") + if fast5_files and not fast5_files.is_file(): + raise FileNotFoundError(f"FAST5 files list not found: {fast5_files}") + + cmd = ["nanopolish", "index"] + if verbose: + cmd.append("-v") + if directory: + cmd.extend(["-d", str(directory)]) + if sequencing_summary: + cmd.extend(["-s", str(sequencing_summary)]) + if fast5_files: + cmd.extend(["-f", str(fast5_files)]) + + cmd.append(str(reads_file)) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + # nanopolish index creates these files based on the reads_file name + output_files = [ + f"{reads_file}.index", + f"{reads_file}.index.fai", + f"{reads_file}.index.gzi", + f"{reads_file}.index.readdb", + ] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(p) for p in output_files if Path(p).exists()], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Nanopolish index failed", + "return_code": e.returncode, + } + +@mcp.tool +def nanopolish_eventalign( + reads: Path, + bam: Path, + genome: Path, + summary: Optional[Path] = None, + threads: int = 1, + verbose: bool = False, + scale_events: bool = False, + max_reads: Optional[int] = None, + min_mapping_quality: int = 20, + models_fofn: Optional[Path] = None, + read_names: Optional[Path] = None, + samples: bool = False, +): + """ + Aligns nanopore events to a reference genome. + """ + # Input validation + if not reads.is_file(): + raise FileNotFoundError(f"Reads file not found: {reads}") + if not bam.is_file(): + raise FileNotFoundError(f"BAM file not found: {bam}") + if not genome.is_file(): + raise FileNotFoundError(f"Genome file not found: {genome}") + if models_fofn and not models_fofn.is_file(): + raise FileNotFoundError(f"Models file not found: {models_fofn}") + if read_names and not read_names.is_file(): + raise FileNotFoundError(f"Read names file not found: {read_names}") + if threads < 1: + raise ValueError("--threads must be a positive integer.") + + cmd = [ + "nanopolish", "eventalign", + "--reads", str(reads), + "--bam", str(bam), + "--genome", str(genome), + "--threads", str(threads), + "--min-mapping-quality", str(min_mapping_quality), + ] + + if verbose: + cmd.append("-v") + if scale_events: + cmd.append("--scale-events") + if samples: + cmd.append("--samples") + if summary: + cmd.extend(["--summary", str(summary)]) + if max_reads is not None: + cmd.extend(["--max-reads", str(max_reads)]) + if models_fofn: + cmd.extend(["--models-fofn", str(models_fofn)]) + if read_names: + cmd.extend(["--read-names", str(read_names)]) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + output_files = [str(summary)] if summary else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Nanopolish eventalign failed", + "return_code": e.returncode, + } + +@mcp.tool +def nanopolish_variants( + reads: Path, + bam: Path, + genome: Path, + consensus: Optional[Path] = None, + vcf: Optional[Path] = None, + threads: int = 1, + window: Optional[str] = None, + max_reads: Optional[int] = None, + min_candidate_frequency: float = 0.2, + min_candidate_depth: int = 20, + max_haplotypes: int = 500, + min_flanking_sequence: int = 30, + min_mapping_quality: int = 20, + models_fofn: Optional[Path] = None, + snvs: bool = False, + calculate_all_support: bool = False, + verbose: bool = False, +): + """ + Detects SNPs and indels from nanopore sequencing data. + """ + # Input validation + if not reads.is_file(): + raise FileNotFoundError(f"Reads file not found: {reads}") + if not bam.is_file(): + raise FileNotFoundError(f"BAM file not found: {bam}") + if not genome.is_file(): + raise FileNotFoundError(f"Genome file not found: {genome}") + if models_fofn and not models_fofn.is_file(): + raise FileNotFoundError(f"Models file not found: {models_fofn}") + if threads < 1: + raise ValueError("--threads must be a positive integer.") + + cmd = [ + "nanopolish", "variants", + "--reads", str(reads), + "--bam", str(bam), + "--genome", str(genome), + "--threads", str(threads), + "--min-candidate-frequency", str(min_candidate_frequency), + "--min-candidate-depth", str(min_candidate_depth), + "--max-haplotypes", str(max_haplotypes), + "--min-flanking-sequence", str(min_flanking_sequence), + "--min-mapping-quality", str(min_mapping_quality), + ] + + if verbose: + cmd.append("-v") + if snvs: + cmd.append("--snvs") + if calculate_all_support: + cmd.append("--calculate-all-support") + if consensus: + cmd.extend(["--consensus", str(consensus)]) + if vcf: + cmd.extend(["--vcf", str(vcf)]) + if window: + cmd.extend(["-w", window]) + if max_reads is not None: + cmd.extend(["--max-reads", str(max_reads)]) + if models_fofn: + cmd.extend(["--models-fofn", str(models_fofn)]) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + output_files = [] + if consensus: + output_files.append(str(consensus)) + if vcf: + output_files.append(str(vcf)) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Nanopolish variants failed", + "return_code": e.returncode, + } + +@mcp.tool +def nanopolish_call_methylation( + reads: Path, + bam: Path, + genome: Path, + methylation: str = "cpg", + call_threshold: float = 2.5, + verbose: bool = False, +): + """ + Predicts methylation status at specific sites. + """ + # Input validation + if not reads.is_file(): + raise FileNotFoundError(f"Reads file not found: {reads}") + if not bam.is_file(): + raise FileNotFoundError(f"BAM file not found: {bam}") + if not genome.is_file(): + raise FileNotFoundError(f"Genome file not found: {genome}") + + valid_methylation_types = ["cpg", "dam", "dcm"] + if methylation not in valid_methylation_types: + raise ValueError(f"--methylation must be one of {valid_methylation_types}") + + cmd = [ + "nanopolish", "call-methylation", + "-r", str(reads), + "-b", str(bam), + "-g", str(genome), + "-q", methylation, + "-c", str(call_threshold), + ] + if verbose: + cmd.append("-v") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Nanopolish call-methylation failed", + "return_code": e.returncode, + } + +@mcp.tool +def nanopolish_polya( + reads: Path, + bam: Path, + genome: Path, + threads: int = 1, +): + """ + Estimates the length of poly-A tails on native RNA reads. + """ + # Input validation + if not reads.is_file(): + raise FileNotFoundError(f"Reads file not found: {reads}") + if not bam.is_file(): + raise FileNotFoundError(f"BAM file not found: {bam}") + if not genome.is_file(): + raise FileNotFoundError(f"Genome file not found: {genome}") + if threads < 1: + raise ValueError("--threads must be a positive integer.") + + cmd = [ + "nanopolish", "polya", + "--reads", str(reads), + "--bam", str(bam), + "--genome", str(genome), + "--threads", str(threads), + ] + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Nanopolish polya failed", + "return_code": e.returncode, + } + +@mcp.tool +def nanopolish_phase_reads( + vcf: Path, + reads: Path, + bam: Path, + genome: Path, + threads: int = 1, + max_reads: Optional[int] = None, + max_haplotypes: int = 500, + min_mapping_quality: int = 20, +): + """ + Phases reads using heterozygous SNVs. + """ + # Input validation + if not vcf.is_file(): + raise FileNotFoundError(f"VCF file not found: {vcf}") + if not reads.is_file(): + raise FileNotFoundError(f"Reads file not found: {reads}") + if not bam.is_file(): + raise FileNotFoundError(f"BAM file not found: {bam}") + if not genome.is_file(): + raise FileNotFoundError(f"Genome file not found: {genome}") + if threads < 1: + raise ValueError("--threads must be a positive integer.") + + cmd = [ + "nanopolish", "phase-reads", + "-v", str(vcf), + "--reads", str(reads), + "--bam", str(bam), + "--genome", str(genome), + "--threads", str(threads), + "--max-haplotypes", str(max_haplotypes), + "--min-mapping-quality", str(min_mapping_quality), + ] + + if max_reads is not None: + cmd.extend(["--max-reads", str(max_reads)]) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Nanopolish phase-reads failed", + "return_code": e.returncode, + } \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanopolish/app/nanopolish_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanopolish/app/nanopolish_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..cffcc82ffbb789c2f58bcc478441cfe5dd72f6be --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanopolish/app/nanopolish_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_nanopolish/app/nanopolish_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_nanopolish' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanopolish/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanopolish/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanopolish/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanopolish/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanopolish/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..8728245ef707d084102038dcdb4ea2aec3648b43 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanopolish/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-nanopolish: + build: . + image: mcp-nanopolish:latest + container_name: mcp-nanopolish + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=nanopolish + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanopolish/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanopolish/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d4405c723ab75a9bb8997cd8c875245bcf8a7f2e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanopolish/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - nanopolish + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanopolish/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanopolish/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nanopolish/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-datasets-pylib/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-datasets-pylib/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce8b230d94e2716cc7b591799c4821ca3164e83b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-datasets-pylib/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install ncbi-datasets-pylib via conda (e.g., from bioconda) +RUN conda install -c bioconda ncbi-datasets-pylib -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/ncbi-datasets-pylib_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/ncbi-datasets-pylib_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/ncbi-datasets-pylib_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-datasets-pylib/app/__pycache__/ncbi-datasets-pylib_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-datasets-pylib/app/__pycache__/ncbi-datasets-pylib_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ccef66ac863c3f4ccd76e92380af7d3feae28b60 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-datasets-pylib/app/__pycache__/ncbi-datasets-pylib_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-datasets-pylib/app/ncbi-datasets-pylib_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-datasets-pylib/app/ncbi-datasets-pylib_server.py new file mode 100644 index 0000000000000000000000000000000000000000..13b3d77e0a2c14e2acae8d0ca7f00b0068478788 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-datasets-pylib/app/ncbi-datasets-pylib_server.py @@ -0,0 +1,452 @@ +import subprocess +import os +from pathlib import Path +from typing import List, Optional, Union + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_ncbi_datasets_pylib' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def datasets_download_genome_taxon( + taxon: str, + reference: bool = False, + annotated: bool = False, + assembly_level: str = "any", + dehydrated: bool = False, + filename: str = "genome_dataset.zip", + api_key: Optional[str] = None, +): + """ + Download a genome data package by taxon name or ID. + + :param taxon: Taxon name or ID (e.g., 'human' or 9606) + :param reference: Limit to reference genomes only + :param annotated: Limit to genomes with annotation + :param assembly_level: Assembly level (any, complete, chromosome, scaffold, contig) + :param dehydrated: Download a dehydrated zip archive (requires rehydration later) + :param filename: Output filename for the zip archive + :param api_key: NCBI API Key for higher rate limits + """ + # Input validation + valid_levels = ["any", "complete", "chromosome", "scaffold", "contig"] + if assembly_level not in valid_levels: + raise ValueError(f"assembly_level must be one of {valid_levels}") + + output_path = Path(filename) + if not output_path.parent.exists(): + raise ValueError(f"Directory {output_path.parent} does not exist") + + cmd = ["datasets", "download", "genome", "taxon", taxon] + if reference: + cmd.append("--reference") + if annotated: + cmd.append("--annotated") + if assembly_level != "any": + cmd.extend(["--assembly-level", assembly_level]) + if dehydrated: + cmd.append("--dehydrated") + cmd.extend(["--filename", filename]) + + env = os.environ.copy() + if api_key: + env["NCBI_API_KEY"] = api_key + + try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True, env=env) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path.absolute())] if output_path.exists() else [] + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": " ".join(cmd) + } + +@mcp.tool() +def datasets_download_genome_accession( + accessions: List[str], + dehydrated: bool = False, + filename: str = "genome_dataset.zip", + api_key: Optional[str] = None, +): + """ + Download a genome data package by assembly accession(s). + + :param accessions: List of NCBI assembly accessions (e.g., ['GCF_000001405.40']) + :param dehydrated: Download a dehydrated zip archive + :param filename: Output filename for the zip archive + :param api_key: NCBI API Key + """ + if not accessions: + raise ValueError("At least one accession must be provided") + + output_path = Path(filename) + cmd = ["datasets", "download", "genome", "accession"] + cmd.extend(accessions) + + if dehydrated: + cmd.append("--dehydrated") + cmd.extend(["--filename", filename]) + + env = os.environ.copy() + if api_key: + env["NCBI_API_KEY"] = api_key + + try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True, env=env) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path.absolute())] if output_path.exists() else [] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stdout": e.stdout, "stderr": e.stderr} + +@mcp.tool() +def datasets_download_gene_id( + gene_ids: List[int], + filename: str = "gene_dataset.zip", + api_key: Optional[str] = None, +): + """ + Download a gene data package by NCBI Gene ID(s). + + :param gene_ids: List of NCBI Gene IDs + :param filename: Output filename for the zip archive + :param api_key: NCBI API Key + """ + if not gene_ids: + raise ValueError("At least one Gene ID must be provided") + + output_path = Path(filename) + cmd = ["datasets", "download", "gene", "gene-id"] + cmd.extend([str(gid) for gid in gene_ids]) + cmd.extend(["--filename", filename]) + + env = os.environ.copy() + if api_key: + env["NCBI_API_KEY"] = api_key + + try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True, env=env) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path.absolute())] if output_path.exists() else [] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stdout": e.stdout, "stderr": e.stderr} + +@mcp.tool() +def datasets_download_gene_symbol( + symbols: List[str], + taxon: str = "human", + filename: str = "gene_dataset.zip", + api_key: Optional[str] = None, +): + """ + Download a gene data package by gene symbol(s) and taxon. + + :param symbols: List of gene symbols (e.g., ['BRCA1', 'TP53']) + :param taxon: Taxon name or ID + :param filename: Output filename + :param api_key: NCBI API Key + """ + if not symbols: + raise ValueError("At least one symbol must be provided") + + output_path = Path(filename) + cmd = ["datasets", "download", "gene", "symbol"] + cmd.extend(symbols) + cmd.extend(["--taxon", taxon, "--filename", filename]) + + env = os.environ.copy() + if api_key: + env["NCBI_API_KEY"] = api_key + + try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True, env=env) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path.absolute())] if output_path.exists() else [] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stdout": e.stdout, "stderr": e.stderr} + +@mcp.tool() +def datasets_download_virus_genome( + taxon: str, + filename: str = "virus_dataset.zip", + api_key: Optional[str] = None, +): + """ + Download a virus data package (genome) by taxon. + + :param taxon: Virus taxon name or ID (e.g., 'SARS-CoV-2') + :param filename: Output filename + :param api_key: NCBI API Key + """ + output_path = Path(filename) + cmd = ["datasets", "download", "virus", "genome", "taxon", taxon, "--filename", filename] + + env = os.environ.copy() + if api_key: + env["NCBI_API_KEY"] = api_key + + try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True, env=env) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path.absolute())] if output_path.exists() else [] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stdout": e.stdout, "stderr": e.stderr} + +@mcp.tool() +def datasets_download_taxonomy_taxon( + taxons: List[str], + filename: str = "taxonomy_dataset.zip", + api_key: Optional[str] = None, +): + """ + Download a taxonomy data package by taxon name(s) or ID(s). + + :param taxons: List of taxon names or IDs + :param filename: Output filename + :param api_key: NCBI API Key + """ + if not taxons: + raise ValueError("At least one taxon must be provided") + + output_path = Path(filename) + cmd = ["datasets", "download", "taxonomy", "taxon"] + cmd.extend(taxons) + cmd.extend(["--filename", filename]) + + env = os.environ.copy() + if api_key: + env["NCBI_API_KEY"] = api_key + + try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True, env=env) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_path.absolute())] if output_path.exists() else [] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stdout": e.stdout, "stderr": e.stderr} + +@mcp.tool() +def datasets_rehydrate( + directory: str, + api_key: Optional[str] = None, +): + """ + Rehydrate a dehydrated NCBI Datasets data package. + + :param directory: Directory containing the unzipped dehydrated package + :param api_key: NCBI API Key + """ + dir_path = Path(directory) + if not dir_path.is_dir(): + raise ValueError(f"Directory {directory} does not exist or is not a directory") + + cmd = ["datasets", "rehydrate", "--directory", directory] + + env = os.environ.copy() + if api_key: + env["NCBI_API_KEY"] = api_key + + try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True, env=env) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stdout": e.stdout, "stderr": e.stderr} + +@mcp.tool() +def datasets_summary_genome_taxon( + taxon: str, + api_key: Optional[str] = None, +): + """ + Get a summary of genome data for a taxon. + + :param taxon: Taxon name or ID + :param api_key: NCBI API Key + """ + cmd = ["datasets", "summary", "genome", "taxon", taxon] + + env = os.environ.copy() + if api_key: + env["NCBI_API_KEY"] = api_key + + try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True, env=env) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stdout": e.stdout, "stderr": e.stderr} + +@mcp.tool() +def datasets_summary_genome_accession( + accessions: List[str], + api_key: Optional[str] = None, +): + """ + Get a summary of genome data for assembly accession(s). + + :param accessions: List of assembly accessions + :param api_key: NCBI API Key + """ + if not accessions: + raise ValueError("At least one accession must be provided") + + cmd = ["datasets", "summary", "genome", "accession"] + cmd.extend(accessions) + + env = os.environ.copy() + if api_key: + env["NCBI_API_KEY"] = api_key + + try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True, env=env) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stdout": e.stdout, "stderr": e.stderr} + +@mcp.tool() +def dataformat_tsv_genome( + package: str, + fields: List[str] = ["organism-name", "assminfo-name", "accession", "assminfo-submitter"], + output_file: Optional[str] = None, +): + """ + Convert genome metadata from a data package to TSV format. + + :param package: Path to the downloaded zip data package + :param fields: List of fields to include in the TSV + :param output_file: Optional path to save the TSV output + """ + package_path = Path(package) + if not package_path.exists(): + raise ValueError(f"Package file {package} not found") + + cmd = ["dataformat", "tsv", "genome", "--package", package, "--fields", ",".join(fields)] + + try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True) + + if output_file: + with open(output_file, "w") as f: + f.write(result.stdout) + return { + "command_executed": " ".join(cmd), + "stdout": "Output written to " + output_file, + "output_files": [str(Path(output_file).absolute())] + } + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stdout": e.stdout, "stderr": e.stderr} + +@mcp.tool() +def dataformat_tsv_gene( + package: str, + fields: List[str] = ["gene-id", "symbol", "description", "tax-name"], + output_file: Optional[str] = None, +): + """ + Convert gene metadata from a data package to TSV format. + + :param package: Path to the downloaded zip data package + :param fields: List of fields to include in the TSV + :param output_file: Optional path to save the TSV output + """ + package_path = Path(package) + if not package_path.exists(): + raise ValueError(f"Package file {package} not found") + + cmd = ["dataformat", "tsv", "gene", "--package", package, "--fields", ",".join(fields)] + + try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True) + + if output_file: + with open(output_file, "w") as f: + f.write(result.stdout) + return { + "command_executed": " ".join(cmd), + "stdout": "Output written to " + output_file, + "output_files": [str(Path(output_file).absolute())] + } + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stdout": e.stdout, "stderr": e.stderr} + +@mcp.tool() +def dataformat_excel_genome( + package: str, + fields: List[str] = ["organism-name", "assminfo-name", "accession"], + output_file: str = "genome_metadata.xlsx", +): + """ + Convert genome metadata from a data package to Excel format. + + :param package: Path to the downloaded zip data package + :param fields: List of fields to include + :param output_file: Path to save the Excel file + """ + package_path = Path(package) + if not package_path.exists(): + raise ValueError(f"Package file {package} not found") + + cmd = ["dataformat", "excel", "genome", "--package", package, "--fields", ",".join(fields), "--output", output_file] + + try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(Path(output_file).absolute())] if Path(output_file).exists() else [] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stdout": e.stdout, "stderr": e.stderr} + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-datasets-pylib/app/ncbi-datasets-pylib_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-datasets-pylib/app/ncbi-datasets-pylib_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ff3f62d989b91683298e2416b53ffc8439a064da --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-datasets-pylib/app/ncbi-datasets-pylib_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ncbi-datasets-pylib/app/ncbi-datasets-pylib_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_ncbi_datasets_pylib' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-datasets-pylib/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-datasets-pylib/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-datasets-pylib/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-datasets-pylib/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-datasets-pylib/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..3894a0fa81f53872fad1798a3f898d746337fc18 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-datasets-pylib/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-ncbi-datasets-pylib: + build: . + image: mcp-ncbi-datasets-pylib:latest + container_name: mcp-ncbi-datasets-pylib + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=ncbi-datasets-pylib + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-datasets-pylib/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-datasets-pylib/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..db87810912b20bc4ffc51566911e96378dbbe71c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-datasets-pylib/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - ncbi-datasets-pylib + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-datasets-pylib/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-datasets-pylib/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ncbi-datasets-pylib/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nextclade/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nextclade/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3ad2d8b5d28d8cc55f2604f8811e4a9a1189bc40 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nextclade/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install nextclade via conda (e.g., from bioconda) +RUN conda install -c bioconda nextclade -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/nextclade_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/nextclade_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/nextclade_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nextclade/app/__pycache__/nextclade_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nextclade/app/__pycache__/nextclade_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a4886db0a0f5e6d47400e33ad128cfa5ffae25c3 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nextclade/app/__pycache__/nextclade_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nextclade/app/nextclade_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nextclade/app/nextclade_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f66faff8ec9728f206335e7db2b92c45b1034ee0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nextclade/app/nextclade_server.py @@ -0,0 +1,366 @@ +import subprocess +from pathlib import Path +from typing import List, Dict, Union, Optional, Literal + +# Helper function to execute commands +def _execute_command(cmd: List[str]) -> Dict[str, Union[str, List[str]]]: + """Helper function to execute a command and return structured output.""" + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "returncode": e.returncode, + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": "Error: nextclade command not found. Please ensure it is installed and in your PATH.", + "error": "nextclade command not found", + "returncode": 127, + "output_files": [], + } + +# Helper function to build common nextclade options +def _build_nextclade_base_command( + verbosity: Optional[Literal["off", "error", "warn", "info", "debug", "trace"]] = None, + silent: bool = False, + verbose_level: int = 0, + quiet_level: int = 0, + color: Optional[Literal["auto", "always", "never"]] = None, + no_color: bool = False, +) -> List[str]: + """Builds the common part of the nextclade command with global options.""" + cmd = ["nextclade"] + + # Handle verbosity and silent. --silent is equivalent to --verbosity=off and takes precedence. + if silent: + cmd.append("--silent") + elif verbosity: + cmd.extend(["--verbosity", verbosity]) + + # Verbose/quiet levels + if verbose_level > 0: + cmd.extend(["-v"] * verbose_level) + if quiet_level > 0: + cmd.extend(["-q"] * quiet_level) + + # Color options: --no-color takes precedence if both are provided (last one takes effect). + if no_color: + cmd.append("--no-color") + elif color: + cmd.extend(["--color", color]) + + return cmd + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_nextclade' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def completions( + shell: Literal["bash", "elvish", "fish", "powershell", "zsh"], + verbosity: Optional[Literal["off", "error", "warn", "info", "debug", "trace"]] = None, + silent: bool = False, + verbose_level: int = 0, + quiet_level: int = 0, + color: Optional[Literal["auto", "always", "never"]] = None, + no_color: bool = False, +) -> Dict[str, Union[str, List[str]]]: + """ + Generate shell completions for nextclade. + + Args: + shell: The shell for which to generate completions. Must be one of 'bash', 'elvish', 'fish', 'powershell', 'zsh'. + verbosity: Set verbosity level of console output. + silent: Disable all console output. Same as `--verbosity=off`. + verbose_level: Make console output more verbose. Add multiple occurrences to increase verbosity further. + quiet_level: Make console output more quiet. Add multiple occurrences to make output even more quiet. + color: Control when to use colored output. + no_color: Disable colored output (shorthand for --color=never). + """ + if not isinstance(shell, str) or shell not in ["bash", "elvish", "fish", "powershell", "zsh"]: + raise ValueError(f"Invalid shell: {shell}. Must be one of 'bash', 'elvish', 'fish', 'powershell', 'zsh'.") + if verbose_level < 0: + raise ValueError("verbose_level cannot be negative.") + if quiet_level < 0: + raise ValueError("quiet_level cannot be negative.") + + cmd = _build_nextclade_base_command( + verbosity=verbosity, + silent=silent, + verbose_level=verbose_level, + quiet_level=quiet_level, + color=color, + no_color=no_color, + ) + cmd.extend(["completions", shell]) + return _execute_command(cmd) + +@mcp.tool() +def run( + # NOTE: Parameters for 'nextclade run' are not provided in the documentation. + # This function serves as a placeholder. + # Please consult 'nextclade run --help' for actual parameters. + verbosity: Optional[Literal["off", "error", "warn", "info", "debug", "trace"]] = None, + silent: bool = False, + verbose_level: int = 0, + quiet_level: int = 0, + color: Optional[Literal["auto", "always", "never"]] = None, + no_color: bool = False, + # Placeholder for actual run parameters. Example: + # input_sequences: Path, + # reference_sequence: Path, + # output_dir: Path, + # ... +) -> Dict[str, Union[str, List[str]]]: + """ + Run sequence analysis: alignment, mutation calling, clade assignment, quality checks and phylogenetic placement. + NOTE: Parameters for 'nextclade run' are not provided in the documentation. + This function serves as a placeholder. Please consult 'nextclade run --help' for actual parameters. + + Args: + verbosity: Set verbosity level of console output. + silent: Disable all console output. Same as `--verbosity=off`. + verbose_level: Make console output more verbose. Add multiple occurrences to increase verbosity further. + quiet_level: Make console output more quiet. Add multiple occurrences to make output even more quiet. + color: Control when to use colored output. + no_color: Disable colored output (shorthand for --color=never). + """ + if verbose_level < 0: + raise ValueError("verbose_level cannot be negative.") + if quiet_level < 0: + raise ValueError("quiet_level cannot be negative.") + + cmd = _build_nextclade_base_command( + verbosity=verbosity, + silent=silent, + verbose_level=verbose_level, + quiet_level=quiet_level, + color=color, + no_color=no_color, + ) + cmd.append("run") + # If there were required parameters for 'run', they would be added here. + # Running 'nextclade run' without specific arguments might print its help or error. + return _execute_command(cmd) + +@mcp.tool() +def dataset( + # NOTE: Parameters for 'nextclade dataset' are not provided in the documentation. + # This function serves as a placeholder. + # Please consult 'nextclade dataset --help' for actual parameters. + verbosity: Optional[Literal["off", "error", "warn", "info", "debug", "trace"]] = None, + silent: bool = False, + verbose_level: int = 0, + quiet_level: int = 0, + color: Optional[Literal["auto", "always", "never"]] = None, + no_color: bool = False, +) -> Dict[str, Union[str, List[str]]]: + """ + List and download available Nextclade datasets (pathogens). + NOTE: Parameters for 'nextclade dataset' are not provided in the documentation. + This function serves as a placeholder. Please consult 'nextclade dataset --help' for actual parameters. + + Args: + verbosity: Set verbosity level of console output. + silent: Disable all console output. Same as `--verbosity=off`. + verbose_level: Make console output more verbose. Add multiple occurrences to increase verbosity further. + quiet_level: Make console output more quiet. Add multiple occurrences to make output even more quiet. + color: Control when to use colored output. + no_color: Disable colored output (shorthand for --color=never). + """ + if verbose_level < 0: + raise ValueError("verbose_level cannot be negative.") + if quiet_level < 0: + raise ValueError("quiet_level cannot be negative.") + + cmd = _build_nextclade_base_command( + verbosity=verbosity, + silent=silent, + verbose_level=verbose_level, + quiet_level=quiet_level, + color=color, + no_color=no_color, + ) + cmd.append("dataset") + return _execute_command(cmd) + +@mcp.tool() +def sort( + # NOTE: Parameters for 'nextclade sort' are not provided in the documentation. + # This function serves as a placeholder. + # Please consult 'nextclade sort --help' for actual parameters. + verbosity: Optional[Literal["off", "error", "warn", "info", "debug", "trace"]] = None, + silent: bool = False, + verbose_level: int = 0, + quiet_level: int = 0, + color: Optional[Literal["auto", "always", "never"]] = None, + no_color: bool = False, +) -> Dict[str, Union[str, List[str]]]: + """ + Sort sequences according to the inferred Nextclade dataset (pathogen). + NOTE: Parameters for 'nextclade sort' are not provided in the documentation. + This function serves as a placeholder. Please consult 'nextclade sort --help' for actual parameters. + + Args: + verbosity: Set verbosity level of console output. + silent: Disable all console output. Same as `--verbosity=off`. + verbose_level: Make console output more verbose. Add multiple occurrences to increase verbosity further. + quiet_level: Make console output more quiet. Add multiple occurrences to make output even more quiet. + color: Control when to use colored output. + no_color: Disable colored output (shorthand for --color=never). + """ + if verbose_level < 0: + raise ValueError("verbose_level cannot be negative.") + if quiet_level < 0: + raise ValueError("quiet_level cannot be negative.") + + cmd = _build_nextclade_base_command( + verbosity=verbosity, + silent=silent, + verbose_level=verbose_level, + quiet_level=quiet_level, + color=color, + no_color=no_color, + ) + cmd.append("sort") + return _execute_command(cmd) + +@mcp.tool() +def read_annotation( + # NOTE: Parameters for 'nextclade read-annotation' are not provided in the documentation. + # This function serves as a placeholder. + # Please consult 'nextclade read-annotation --help' for actual parameters. + verbosity: Optional[Literal["off", "error", "warn", "info", "debug", "trace"]] = None, + silent: bool = False, + verbose_level: int = 0, + quiet_level: int = 0, + color: Optional[Literal["auto", "always", "never"]] = None, + no_color: bool = False, +) -> Dict[str, Union[str, List[str]]]: + """ + Read genome annotation and present it in Nextclade's internal formats. + NOTE: Parameters for 'nextclade read-annotation' are not provided in the documentation. + This function serves as a placeholder. Please consult 'nextclade read-annotation --help' for actual parameters. + + Args: + verbosity: Set verbosity level of console output. + silent: Disable all console output. Same as `--verbosity=off`. + verbose_level: Make console output more verbose. Add multiple occurrences to increase verbosity further. + quiet_level: Make console output more quiet. Add multiple occurrences to make output even more quiet. + color: Control when to use colored output. + no_color: Disable colored output (shorthand for --color=never). + """ + if verbose_level < 0: + raise ValueError("verbose_level cannot be negative.") + if quiet_level < 0: + raise ValueError("quiet_level cannot be negative.") + + cmd = _build_nextclade_base_command( + verbosity=verbosity, + silent=silent, + verbose_level=verbose_level, + quiet_level=quiet_level, + color=color, + no_color=no_color, + ) + cmd.append("read-annotation") + return _execute_command(cmd) + +@mcp.tool() +def schema( + # NOTE: Parameters for 'nextclade schema' are not provided in the documentation. + # This function serves as a placeholder. + # Please consult 'nextclade schema --help' for actual parameters. + verbosity: Optional[Literal["off", "error", "warn", "info", "debug", "trace"]] = None, + silent: bool = False, + verbose_level: int = 0, + quiet_level: int = 0, + color: Optional[Literal["auto", "always", "never"]] = None, + no_color: bool = False, +) -> Dict[str, Union[str, List[str]]]: + """ + Write JSON schema definitions for Nextclade file formats. + NOTE: Parameters for 'nextclade schema' are not provided in the documentation. + This function serves as a placeholder. Please consult 'nextclade schema --help' for actual parameters. + + Args: + verbosity: Set verbosity level of console output. + silent: Disable all console output. Same as `--verbosity=off`. + verbose_level: Make console output more verbose. Add multiple occurrences to increase verbosity further. + quiet_level: Make console output more quiet. Add multiple occurrences to make output even more quiet. + color: Control when to use colored output. + no_color: Disable colored output (shorthand for --color=never). + """ + if verbose_level < 0: + raise ValueError("verbose_level cannot be negative.") + if quiet_level < 0: + raise ValueError("quiet_level cannot be negative.") + + cmd = _build_nextclade_base_command( + verbosity=verbosity, + silent=silent, + verbose_level=verbose_level, + quiet_level=quiet_level, + color=color, + no_color=no_color, + ) + cmd.append("schema") + return _execute_command(cmd) + +@mcp.tool() +def help_markdown( + verbosity: Optional[Literal["off", "error", "warn", "info", "debug", "trace"]] = None, + silent: bool = False, + verbose_level: int = 0, + quiet_level: int = 0, + color: Optional[Literal["auto", "always", "never"]] = None, + no_color: bool = False, +) -> Dict[str, Union[str, List[str]]]: + """ + Print command-line reference documentation in Markdown format. + + Args: + verbosity: Set verbosity level of console output. + silent: Disable all console output. Same as `--verbosity=off`. + verbose_level: Make console output more verbose. Add multiple occurrences to increase verbosity further. + quiet_level: Make console output more quiet. Add multiple occurrences to make output even more quiet. + color: Control when to use colored output. + no_color: Disable colored output (shorthand for --color=never). + """ + if verbose_level < 0: + raise ValueError("verbose_level cannot be negative.") + if quiet_level < 0: + raise ValueError("quiet_level cannot be negative.") + + cmd = _build_nextclade_base_command( + verbosity=verbosity, + silent=silent, + verbose_level=verbose_level, + quiet_level=quiet_level, + color=color, + no_color=no_color, + ) + cmd.append("help-markdown") + return _execute_command(cmd) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nextclade/app/nextclade_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nextclade/app/nextclade_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..754b12bf93847c8ba36d4e8762fb70caa3b562b5 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nextclade/app/nextclade_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_nextclade/app/nextclade_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_nextclade' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nextclade/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nextclade/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nextclade/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nextclade/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nextclade/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c385ef4a2a15c189839bb56afce3a993a98d05c1 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nextclade/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-nextclade: + build: . + image: mcp-nextclade:latest + container_name: mcp-nextclade + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=nextclade + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nextclade/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nextclade/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..dbec6b04c45d8c8dca0370cb783db2c0540ffc12 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nextclade/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - nextclade + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nextclade/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nextclade/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_nextclade/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_paste-bio/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_paste-bio/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..49241ee0954fe79a3b6562f5069f9380d2a431dc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_paste-bio/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install paste-bio via conda (e.g., from bioconda) +RUN conda install -c bioconda paste-bio -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY paste-bio_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/paste-bio_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/paste-bio_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_paste-bio/app/__pycache__/paste-bio_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_paste-bio/app/__pycache__/paste-bio_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..143f29853e3702f84404291b7858e75321f4d1c8 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_paste-bio/app/__pycache__/paste-bio_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_paste-bio/app/paste-bio_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_paste-bio/app/paste-bio_server.py new file mode 100644 index 0000000000000000000000000000000000000000..870ac251d75d070522563fe5e9d7896467156d08 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_paste-bio/app/paste-bio_server.py @@ -0,0 +1,178 @@ +import subprocess +from pathlib import Path +from typing import List, Optional + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_paste_bio' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def paste_pairwise_align( + files: List[str], + output_dir: str = ".", + alpha: float = 0.1, + cost: str = "kl", + output_coordinates: bool = False, + weights: Optional[List[str]] = None, + start_alignments: Optional[List[str]] = None, +): + """ + Align spots across pairwise slices using PASTE. + + PASTE (Probabilistic Alignment of Spatial Transcriptomics Experiments) leverages both + gene expression similarity and spatial distances between spots to align spatial transcriptomics data. + Pairwise alignment returns a mapping of spots between each consecutive pair of slices. + + Args: + files: List of paths to data files (.csv). Must provide two files per slice: + gene expression followed by spatial coordinates (e.g., [s1_exp, s1_coord, s2_exp, s2_coord]). + output_dir: Directory to store output files. + alpha: Alpha parameter for PASTE (trade-off between expression and spatial distance). + cost: Expression dissimilarity cost ('kl' or 'Euclidean'). + output_coordinates: If True, output new coordinates. + weights: Optional list of paths to weights files of spots in each slice (.csv). + start_alignments: Optional list of paths to initial alignments for OT (.csv). + """ + # Input validation + if len(files) % 2 != 0: + return {"error": "Files list must contain pairs of (expression.csv, coordinates.csv) for each slice."} + + for f in files: + if not Path(f).exists(): + return {"error": f"File not found: {f}"} + + if cost not in ["kl", "Euclidean"]: + return {"error": "Cost must be either 'kl' or 'Euclidean'."} + + # Construct command + cmd = ["python", "paste-cmd-line.py", "-m", "pairwise", "-f"] + cmd.extend(files) + + cmd.extend(["-d", output_dir]) + cmd.extend(["-a", str(alpha)]) + cmd.extend(["-c", cost]) + + if output_coordinates: + cmd.append("-x") + + if weights: + cmd.append("-w") + cmd.extend(weights) + + if start_alignments: + cmd.append("-s") + cmd.extend(start_alignments) + + 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": list(Path(output_dir).glob("*.csv")) + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def paste_center_align( + files: List[str], + output_dir: str = ".", + alpha: float = 0.1, + cost: str = "kl", + n_components: int = 15, + lmbda: Optional[List[float]] = None, + initial_slice_index: int = 1, + threshold: float = 0.001, + output_coordinates: bool = False, + weights: Optional[List[str]] = None, + start_alignments: Optional[List[str]] = None, +): + """ + Integrate multiple spatial transcriptomics slices into one center slice using PASTE. + + Center alignment outputs the low dimensional representation (NMF decomposition) of the + center slice gene expression and mappings between the center slice and each input slice. + + Args: + files: List of paths to data files (.csv). Must provide two files per slice: + gene expression followed by spatial coordinates (e.g., [s1_exp, s1_coord, s2_exp, s2_coord]). + output_dir: Directory to store output files. + alpha: Alpha parameter for PASTE. + cost: Expression dissimilarity cost ('kl' or 'Euclidean'). + n_components: Number of components for the NMF step in center_align. + lmbda: Lambda parameter (floats). A probability vector of length n (number of slices). + initial_slice_index: Specify which slice (1-indexed) is the initial coordinate reference. + threshold: Convergence threshold for center_align. + output_coordinates: If True, output new coordinates. + weights: Optional list of paths to weights files of spots in each slice (.csv). + start_alignments: Optional list of paths to initial alignments for OT (.csv). + """ + # Input validation + if len(files) % 2 != 0: + return {"error": "Files list must contain pairs of (expression.csv, coordinates.csv) for each slice."} + + num_slices = len(files) // 2 + + for f in files: + if not Path(f).exists(): + return {"error": f"File not found: {f}"} + + if cost not in ["kl", "Euclidean"]: + return {"error": "Cost must be either 'kl' or 'Euclidean'."} + + if initial_slice_index < 1 or initial_slice_index > num_slices: + return {"error": f"initial_slice_index must be between 1 and {num_slices}."} + + # Construct command + cmd = ["python", "paste-cmd-line.py", "-m", "center", "-f"] + cmd.extend(files) + + cmd.extend(["-d", output_dir]) + cmd.extend(["-a", str(alpha)]) + cmd.extend(["-c", cost]) + cmd.extend(["-p", str(n_components)]) + cmd.extend(["-i", str(initial_slice_index)]) + cmd.extend(["-t", str(threshold)]) + + if lmbda: + if len(lmbda) != num_slices: + return {"error": f"lmbda must have length {num_slices}."} + cmd.append("-l") + cmd.extend([str(l) for l in lmbda]) + + if output_coordinates: + cmd.append("-x") + + if weights: + cmd.append("-w") + cmd.extend(weights) + + if start_alignments: + cmd.append("-s") + cmd.extend(start_alignments) + + 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": list(Path(output_dir).glob("*.csv")) + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_paste-bio/app/paste-bio_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_paste-bio/app/paste-bio_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4d70e368ae9398901e5b14f7d7e642e5e80a6845 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_paste-bio/app/paste-bio_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_paste-bio/app/paste-bio_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_paste_bio' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_paste-bio/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_paste-bio/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..caad11f45d84ef4967add43d6f94293a581118ab --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_paste-bio/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-paste-bio: + build: . + image: mcp-paste-bio:latest + container_name: mcp-paste-bio + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=paste-bio + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_paste-bio/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_paste-bio/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..65185f3bf3b4ffd5d47c646a619be616cd9967ff --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_paste-bio/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - paste-bio + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_paste-bio/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_paste-bio/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_paste-bio/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_peptide-shaker/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_peptide-shaker/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d305279877e92a2190f533f5e730714ffc279d56 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_peptide-shaker/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install peptide-shaker via conda (e.g., from bioconda) +RUN conda install -c bioconda peptide-shaker -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY peptide-shaker_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/peptide-shaker_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/peptide-shaker_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_peptide-shaker/app/__pycache__/peptide-shaker_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_peptide-shaker/app/__pycache__/peptide-shaker_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..2292d02bc1bb908867bd60d5a9e177137c5e2564 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_peptide-shaker/app/__pycache__/peptide-shaker_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_peptide-shaker/app/peptide-shaker_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_peptide-shaker/app/peptide-shaker_server.py new file mode 100644 index 0000000000000000000000000000000000000000..15a9ed74f3dff57b230e291d97d02c312fe5bd4f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_peptide-shaker/app/peptide-shaker_server.py @@ -0,0 +1,340 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Literal + +# MCP decorator is commented out as per instructions +# from mcp import tool as mcp + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_peptide_shaker' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def peptide_shaker_run( + peptide_shaker_jar: Path, + identification_files: List[Path], + spectrum_files: List[Path], + fasta_file: Path, + output_psdb: Path, + id_params: Path, + config_folder: Optional[Path] = None, + threads: int = 4, + species: Optional[str] = None, + species_type: Optional[str] = None, + zip_output: Optional[Path] = None, + path_settings: Optional[str] = None, +): + """ + Runs the main PeptideShaker processing pipeline from identification and spectrum files. + + This is the primary tool for a de novo analysis, creating a PeptideShaker project + database (.psdb) from search engine results. + """ + # --- Input Validation --- + if not peptide_shaker_jar.is_file(): + raise FileNotFoundError(f"PeptideShaker JAR not found at: {peptide_shaker_jar}") + for f in identification_files: + if not f.is_file(): + raise FileNotFoundError(f"Identification file not found: {f}") + for f in spectrum_files: + if not f.is_file(): + raise FileNotFoundError(f"Spectrum file not found: {f}") + if not fasta_file.is_file(): + raise FileNotFoundError(f"FASTA file not found: {fasta_file}") + if not id_params.is_file(): + raise FileNotFoundError(f"Identification parameters file not found: {id_params}") + if config_folder and not config_folder.is_dir(): + raise NotADirectoryError(f"Config folder not found or is not a directory: {config_folder}") + if threads <= 0: + raise ValueError("Number of threads must be a positive integer.") + + # --- Command Construction --- + cmd = [ + "java", "-cp", str(peptide_shaker_jar), + "eu.isas.peptideshaker.cmd.PeptideShakerCLI", + "-identification_files", ",".join(map(str, identification_files)), + "-spectrum_files", ",".join(map(str, spectrum_files)), + "-fasta_file", str(fasta_file), + "-output", str(output_psdb), + "-id_params", str(id_params), + "-threads", str(threads), + ] + + if config_folder: + cmd.extend(["-config_folder", str(config_folder)]) + if species: + cmd.extend(["-species", species]) + if species_type: + cmd.extend(["-species_type", species_type]) + if zip_output: + cmd.extend(["-zip", str(zip_output)]) + if path_settings: + cmd.extend(["-path", path_settings]) + + # --- Subprocess Execution --- + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + output_files = [str(output_psdb)] + if zip_output: + output_files.append(str(zip_output)) + + 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": "PeptideShakerCLI failed", + } + +@mcp.tool() +def peptide_shaker_report( + peptide_shaker_jar: Path, + input_psdb: Path, + output_folder: Path, + reports: List[int], + documentation_folder: Optional[Path] = None, +): + """ + Exports reports from an existing PeptideShaker project file (.psdb). + """ + # --- Input Validation --- + if not peptide_shaker_jar.is_file(): + raise FileNotFoundError(f"PeptideShaker JAR not found at: {peptide_shaker_jar}") + if not input_psdb.is_file(): + raise FileNotFoundError(f"Input PeptideShaker project file not found: {input_psdb}") + if not reports: + raise ValueError("At least one report index must be provided.") + for report_index in reports: + if not isinstance(report_index, int) or report_index <= 0: + raise ValueError(f"Report index '{report_index}' is invalid; indices must be positive integers.") + + # --- File Path Handling --- + output_folder.mkdir(parents=True, exist_ok=True) + if documentation_folder: + documentation_folder.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd = [ + "java", "-cp", str(peptide_shaker_jar), + "eu.isas.peptideshaker.cmd.ReportCLI", + "-in", str(input_psdb), + "-out_reports", str(output_folder), + "-reports", ",".join(map(str, reports)), + ] + + if documentation_folder: + cmd.extend(["-documentation", str(documentation_folder)]) + + # --- Subprocess Execution --- + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + # Return the directories as output, as file names are generated by the tool + output_locations = [str(output_folder)] + if documentation_folder: + output_locations.append(str(documentation_folder)) + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_locations, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "ReportCLI failed", + } + +@mcp.tool() +def peptide_shaker_follow_up( + peptide_shaker_jar: Path, + input_psdb: Path, + output_psdb: Path, + contact: Optional[str] = None, + description: Optional[str] = None, + gene_mapping: bool = False, + go_analysis: bool = False, + validation_level: Optional[Literal["protein", "peptide", "psm"]] = None, + output_reports_folder: Optional[Path] = None, + reports: Optional[List[int]] = None, + documentation_folder: Optional[Path] = None, + zip_output: Optional[Path] = None, +): + """ + Performs follow-up analysis (e.g., gene mapping) on an existing PeptideShaker project. + """ + # --- Input Validation --- + if not peptide_shaker_jar.is_file(): + raise FileNotFoundError(f"PeptideShaker JAR not found at: {peptide_shaker_jar}") + if not input_psdb.is_file(): + raise FileNotFoundError(f"Input PeptideShaker project file not found: {input_psdb}") + if reports and not output_reports_folder: + raise ValueError("The 'reports' parameter requires 'output_reports_folder' to be set.") + + # --- File Path Handling --- + if output_reports_folder: + output_reports_folder.mkdir(parents=True, exist_ok=True) + if documentation_folder: + documentation_folder.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd = [ + "java", "-cp", str(peptide_shaker_jar), + "eu.isas.peptideshaker.cmd.FollowUpCLI", + "-in", str(input_psdb), + "-output", str(output_psdb), + ] + + if contact: + cmd.extend(["-contact", contact]) + if description: + cmd.extend(["-description", description]) + if gene_mapping: + cmd.append("-gene") + if go_analysis: + cmd.append("-go") + if validation_level: + cmd.extend(["-validation_level", validation_level]) + if output_reports_folder: + cmd.extend(["-out_reports", str(output_reports_folder)]) + if reports: + cmd.extend(["-reports", ",".join(map(str, reports))]) + if documentation_folder: + cmd.extend(["-documentation", str(documentation_folder)]) + if zip_output: + cmd.extend(["-zip", str(zip_output)]) + + # --- Subprocess Execution --- + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + output_files = [str(output_psdb)] + if zip_output: + output_files.append(str(zip_output)) + if output_reports_folder: + output_files.append(str(output_reports_folder)) + if documentation_folder: + output_files.append(str(documentation_folder)) + + 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": "FollowUpCLI failed", + } + +@mcp.tool() +def peptide_shaker_mzid( + peptide_shaker_jar: Path, + input_psdb: Path, + output_mzid: Path, + contact_first_name: Optional[str] = None, + contact_last_name: Optional[str] = None, + contact_email: Optional[str] = None, + contact_address: Optional[str] = None, + contact_url: Optional[str] = None, + organization_name: Optional[str] = None, + organization_email: Optional[str] = None, + organization_address: Optional[str] = None, + organization_url: Optional[str] = None, + include_protein_sequences: bool = False, + gzip: bool = False, +): + """ + Exports a PeptideShaker project to the mzIdentML (.mzid) format. + """ + # --- Input Validation --- + if not peptide_shaker_jar.is_file(): + raise FileNotFoundError(f"PeptideShaker JAR not found at: {peptide_shaker_jar}") + if not input_psdb.is_file(): + raise FileNotFoundError(f"Input PeptideShaker project file not found: {input_psdb}") + + # --- Command Construction --- + cmd = [ + "java", "-cp", str(peptide_shaker_jar), + "eu.isas.peptideshaker.cmd.MzidCLI", + "-in", str(input_psdb), + "-output_file", str(output_mzid), + ] + + # Add contact and organization details if provided + contact_details = { + "-contact_first_name": contact_first_name, + "-contact_last_name": contact_last_name, + "-contact_email": contact_email, + "-contact_address": contact_address, + "-contact_url": contact_url, + } + org_details = { + "-organization_name": organization_name, + "-organization_email": organization_email, + "-organization_address": organization_address, + "-organization_url": organization_url, + } + for flag, value in {**contact_details, **org_details}.items(): + if value: + cmd.extend([flag, value]) + + if include_protein_sequences: + cmd.append("-include_protein_sequences") + if gzip: + cmd.append("-gzip") + + # --- Subprocess Execution --- + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + output_file_path = str(output_mzid) + if gzip: + output_file_path += ".gz" + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [output_file_path], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "MzidCLI failed", + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_peptide-shaker/app/peptide-shaker_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_peptide-shaker/app/peptide-shaker_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3a503d4886a5cd6a73b07a1fb0aac41759942185 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_peptide-shaker/app/peptide-shaker_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_peptide-shaker/app/peptide-shaker_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_peptide_shaker' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_peptide-shaker/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_peptide-shaker/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..0ea6b2d3c35625a373b36a54ced23734c0dcf8d0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_peptide-shaker/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-peptide-shaker: + build: . + image: mcp-peptide-shaker:latest + container_name: mcp-peptide-shaker + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=peptide-shaker + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_peptide-shaker/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_peptide-shaker/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d1e4c8c4259d63b89c1caceb0d821e17e2b375ad --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_peptide-shaker/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - peptide-shaker + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_peptide-shaker/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_peptide-shaker/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_peptide-shaker/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-autoloader/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-autoloader/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..74ae8666d5c7394f3595b3403e3e4aa1d6a46f24 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-autoloader/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-autoloader via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-autoloader -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-autoloader_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-autoloader_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-autoloader_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-autoloader/app/__pycache__/perl-autoloader_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-autoloader/app/__pycache__/perl-autoloader_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f06c811da2dad3f985f34dd4ffd9a9d97cade5f Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-autoloader/app/__pycache__/perl-autoloader_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-autoloader/app/perl-autoloader_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-autoloader/app/perl-autoloader_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0ac2ce6249d2bed01f4dd3e9ebff3d96810a04a7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-autoloader/app/perl-autoloader_server.py @@ -0,0 +1,197 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +# In a real MCP environment, the mcp package would be imported. +# from mcp import tool +# For demonstration purposes, a dummy decorator is used. +def tool(*args, **kwargs): + def decorator(func): + # In a real scenario, this decorator would register the function with the MCP server. + # Here, it just returns the function as is. + return func + return decorator + +mcp = type("mcp", (), {"tool": tool}) + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_autoloader' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def perl_run( + programfile: Optional[Path] = None, + arguments: Optional[List[str]] = None, + program_line: Optional[List[str]] = None, + program_line_extended: Optional[List[str]] = None, + record_separator_octal: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + run_under_debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + edit_in_place: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_ending_processing: Optional[str] = None, + use_module: Optional[List[str]] = None, + use_module_no_import: Optional[List[str]] = None, + no_module: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + parse_switches: bool = False, + search_path: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core: bool = False, + unsafe_operations: bool = False, + print_version: bool = False, + print_config: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_pre_hashbang_text: bool = False, + cd_to_directory: Optional[Path] = None, + disable_all_warnings: bool = False, +) -> Dict[str, Any]: + """ + Executes the Perl interpreter with specified switches, program file, and arguments. + + This tool serves as a wrapper for the `perl` command-line interpreter. It allows + for executing Perl code from a file or directly from the command line, and supports + a wide range of Perl's command-line switches. + + Args: + programfile: Path to the Perl program file to execute. + arguments: A list of arguments to pass to the program file. + program_line: One or more lines of a program for execution (-e). + program_line_extended: Like -e, but enables all optional features (-E). + record_separator_octal: Specify record separator as an octal value (-0). + autosplit: Enable autosplit mode with -n or -p (-a). + unicode_features: Enable listed Unicode features (-C). + check_syntax_only: Check syntax only; does not execute the program (-c). + run_under_debugger: Run the program under the debugger (-d). Can specify a debugger. + debugging_flags: Set debugging flags (-D). + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup (-f). + split_pattern: Specify the split() pattern for the -a switch (-F). + edit_in_place: Edit <> files in place. Provide an extension for backups (-i). + include_directories: Specify @INC/#include directories (-I). + line_ending_processing: Enable line ending processing (-l). + use_module: Execute "use module..." before the program (-M). + use_module_no_import: Execute "use module ()..." before the program (-m). + no_module: Execute "no module..." before the program (-M-module). + loop_around_program: Assume a "while (<>) { ... }" loop around the program (-n). + loop_and_print: Assume a loop like -n but also print the line (-p). + parse_switches: Enable rudimentary parsing for switches after the program file (-s). + search_path: Look for the program file using the PATH environment variable (-S). + tainting_warnings: Enable tainting warnings (-t). + tainting_checks: Enable tainting checks (-T). + dump_core: Dump core after parsing the program (-u). + unsafe_operations: Allow unsafe operations (-U). + print_version: Print version, patchlevel, and license (-v). + print_config: Print configuration summary or a single variable (-V). + enable_warnings: Enable many useful warnings (-w). + enable_all_warnings: Enable all warnings (-W). + ignore_pre_hashbang_text: Ignore text before #!perl line (-x). + cd_to_directory: Optionally cd to this directory when using -x. + disable_all_warnings: Disable all warnings (-X). + + Returns: + A dictionary containing the command executed, stdout, stderr, return code, + and a list of output files (if any). + """ + # --- Input Validation --- + if not any([programfile, program_line, program_line_extended, print_version, print_config is not None]): + raise ValueError("Either 'programfile', 'program_line', 'program_line_extended', 'print_version', or 'print_config' must be provided.") + + if programfile and (program_line or program_line_extended): + raise ValueError("'programfile' cannot be used with 'program_line' or 'program_line_extended'.") + + if programfile and not programfile.is_file(): + raise FileNotFoundError(f"The program file '{programfile}' does not exist.") + + if include_directories: + for directory in include_directories: + if not directory.is_dir(): + raise NotADirectoryError(f"The include directory '{directory}' does not exist.") + + if cd_to_directory: + if not ignore_pre_hashbang_text: + raise ValueError("The 'ignore_pre_hashbang_text' (-x) flag must be enabled to use 'cd_to_directory'.") + if not cd_to_directory.is_dir(): + raise NotADirectoryError(f"The directory for -x option '{cd_to_directory}' does not exist.") + + # --- Command Construction --- + cmd: List[str] = ["perl"] + + if record_separator_octal is not None: cmd.append(f"-0{record_separator_octal}") + if autosplit: cmd.append("-a") + if unicode_features is not None: cmd.append(f"-C{unicode_features}") + if check_syntax_only: cmd.append("-c") + if run_under_debugger is not None: cmd.append(f"-d:{run_under_debugger}" if run_under_debugger else "-d") + if debugging_flags is not None: cmd.append(f"-D{debugging_flags}") + if program_line: + for line in program_line: cmd.extend(["-e", line]) + if program_line_extended: + for line in program_line_extended: cmd.extend(["-E", line]) + if no_sitecustomize: cmd.append("-f") + if split_pattern is not None: cmd.append(f"-F{split_pattern}") + if edit_in_place is not None: cmd.append(f"-i{edit_in_place}") + if include_directories: + for directory in include_directories: cmd.extend(["-I", str(directory)]) + if line_ending_processing is not None: cmd.append(f"-l{line_ending_processing}") + if use_module: + for module in use_module: cmd.append(f"-M{module}") + if use_module_no_import: + for module in use_module_no_import: cmd.append(f"-m{module}") + if no_module: + for module in no_module: cmd.append(f"-M-{module}") + if loop_around_program: cmd.append("-n") + if loop_and_print: cmd.append("-p") + if parse_switches: cmd.append("-s") + if search_path: cmd.append("-S") + if tainting_warnings: cmd.append("-t") + if tainting_checks: cmd.append("-T") + if dump_core: cmd.append("-u") + if unsafe_operations: cmd.append("-U") + if print_version: cmd.append("-v") + if print_config is not None: cmd.append(f"-V:{print_config}" if print_config else "-V") + if enable_warnings: cmd.append("-w") + if enable_all_warnings: cmd.append("-W") + if ignore_pre_hashbang_text: + cmd.append(f"-x{cd_to_directory}" if cd_to_directory else "-x") + if disable_all_warnings: cmd.append("-X") + + if programfile: cmd.append(str(programfile)) + if arguments: cmd.extend(arguments) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=False) + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and in your PATH.", + "output_files": [], + "return_code": -1, + } + + # --- Structured Result Return --- + output_files = [] + if edit_in_place is not None and programfile: + output_files.append(str(programfile)) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + "return_code": result.returncode, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-autoloader/app/perl-autoloader_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-autoloader/app/perl-autoloader_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b893a6bf0f7b165a647220353a75b3eb9aac022e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-autoloader/app/perl-autoloader_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-autoloader/app/perl-autoloader_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_autoloader' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-autoloader/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-autoloader/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-autoloader/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-autoloader/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-autoloader/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..cc08066524cf1bf3e4fc5446d0bf4f4805c38016 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-autoloader/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-autoloader: + build: . + image: mcp-perl-autoloader:latest + container_name: mcp-perl-autoloader + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-autoloader + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-autoloader/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-autoloader/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9c57f295c9e858ca9bb7b57a8cca027f99ee58ce --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-autoloader/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-autoloader + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-autoloader/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-autoloader/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-autoloader/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-samtools/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-samtools/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e5d92854dd966f31a37af991d15205448a5d2360 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-samtools/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-bio-samtools via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-bio-samtools -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-bio-samtools_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-bio-samtools_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-bio-samtools_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-samtools/app/__pycache__/perl-bio-samtools_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-samtools/app/__pycache__/perl-bio-samtools_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb5bddb1d5077ecad89d7e06c0317071b702247a Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-samtools/app/__pycache__/perl-bio-samtools_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-samtools/app/perl-bio-samtools_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-samtools/app/perl-bio-samtools_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6c9cd2ce113b53fc14b595161ea8150770418761 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-samtools/app/perl-bio-samtools_server.py @@ -0,0 +1,236 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict, Any, Union + +# NO NEED to import mcp as per instructions + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_bio_samtools' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_perl_script( + program_file: Optional[Path] = None, + program_arguments: List[str] = [], + program_lines: List[str] = [], + program_lines_extended: List[str] = [], + record_separator: Optional[str] = None, + autosplit_mode: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + edit_in_place_extension: Optional[str] = None, + include_directories: List[Path] = [], + line_ending_terminator: Optional[str] = None, + use_modules_m: List[str] = [], + use_modules_M: List[str] = [], + no_modules_M: List[str] = [], + loop_around_program: bool = False, + loop_and_print: bool = False, + rudimentary_switch_parsing: bool = False, + search_path_for_program: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core: bool = False, + allow_unsafe_operations: bool = False, + print_version: bool = False, + print_config_summary: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_text_directory: Optional[Path] = None, + disable_all_warnings: bool = False, +) -> Dict[str, Any]: + """ + Executes a Perl script or program lines with various Perl interpreter options. + + This tool wraps the 'perl' interpreter, allowing users to run Perl scripts + or one-liners. It provides access to all standard Perl command-line switches. + If the execution environment includes 'perl-bio-samtools', Perl scripts + can utilize the Bio::SamTools module. + + Args: + program_file: Path to the Perl script file to execute. Required if no program_lines are provided. + program_arguments: Arguments to pass to the Perl script. + program_lines: One or more lines of Perl program code to execute (like -e). + Can be specified multiple times. + program_lines_extended: One or more lines of Perl program code to execute, + like -e, but enables all optional features (like -E). + Can be specified multiple times. + record_separator: Specify record separator (e.g., '0' for NUL, '0777' for paragraph mode). + If an empty string is provided, it uses '\0'. + autosplit_mode: Enable autosplit mode with -n or -p (splits $_ into @F). + unicode_features: Enables listed Unicode features (e.g., 'all', 'say'). + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks). + debugger: Run program under debugger. Optionally specify debugger (e.g., 'MyDebugger'). + If an empty string is provided, it enables the default debugger. + debugging_flags: Set debugging flags (argument is a bit mask or alphabets). + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup. + split_pattern: split() pattern for -a switch (e.g., '/\\s+/'). + edit_in_place_extension: Edit <> files in place. Makes backup if extension supplied (e.g., '.bak'). + If an empty string is provided, it edits in place without making a backup. + include_directories: Specify @INC/#include directory (can be specified multiple times). + line_ending_terminator: Enable line ending processing, specifies line terminator (e.g., '0777'). + If an empty string is provided, it enables processing with the default terminator. + use_modules_m: List of modules to 'use' before executing program (like -m). + use_modules_M: List of modules to 'use' with 'import' before executing program (like -M). + no_modules_M: List of modules to 'no' before executing program (like -M-). + loop_around_program: Assume "while (<>) { ... }" loop around program (like -n). + loop_and_print: Assume loop like -n but print line also, like sed (like -p). + rudimentary_switch_parsing: Enable rudimentary parsing for switches after programfile (like -s). + search_path_for_program: Look for programfile using PATH environment variable (like -S). + tainting_warnings: Enable tainting warnings (like -t). + tainting_checks: Enable tainting checks (like -T). + dump_core: Dump core after parsing program (like -u). + allow_unsafe_operations: Allow unsafe operations (like -U). + print_version: Print version, patchlevel and license (like -v). + print_config_summary: Print configuration summary. Optionally specify a single Config.pm variable (like -V:variable). + If an empty string is provided, it prints the full summary. + enable_warnings: Enable many useful warnings (like -w). + enable_all_warnings: Enable all warnings (like -W). + ignore_text_directory: Ignore text before #!perl line. Optionally cd to directory (like -x). + If an empty string is provided, it ignores text without changing directory. + disable_all_warnings: Disable all warnings (like -X). + """ + # Input validation + if not program_file and not (program_lines or program_lines_extended): + raise ValueError( + "Either 'program_file' or at least one of 'program_lines' or 'program_lines_extended' must be provided." + ) + + if program_file: + if not program_file.is_file(): + raise FileNotFoundError(f"Program file not found: {program_file}") + + for d in include_directories: + if not d.is_dir(): + raise NotADirectoryError(f"Include directory not found or not a directory: {d}") + + if ignore_text_directory: + if not ignore_text_directory.is_dir(): + raise NotADirectoryError(f"Ignore text directory not found or not a directory: {ignore_text_directory}") + + # Mutually exclusive options + if loop_around_program and loop_and_print: + raise ValueError("Options 'loop_around_program' (-n) and 'loop_and_print' (-p) are mutually exclusive.") + + warning_options_count = sum([enable_warnings, enable_all_warnings, disable_all_warnings]) + if warning_options_count > 1: + raise ValueError( + "Only one of 'enable_warnings' (-w), 'enable_all_warnings' (-W), or 'disable_all_warnings' (-X) can be true." + ) + + command: List[str] = ["perl"] + + # Add switches + if record_separator is not None: + command.append(f"-0{record_separator}") + if autosplit_mode: + command.append("-a") + if unicode_features: + command.append(f"-C{unicode_features}") + if check_syntax_only: + command.append("-c") + if debugger is not None: + command.append(f"-d{':' + debugger if debugger else ''}") + if debugging_flags: + command.append(f"-D{debugging_flags}") + for line in program_lines: + command.extend(["-e", line]) + for line in program_lines_extended: + command.extend(["-E", line]) + if no_sitecustomize: + command.append("-f") + if split_pattern: + command.append(f"-F{split_pattern}") + if edit_in_place_extension is not None: + command.append(f"-i{edit_in_place_extension}") + for d in include_directories: + command.extend(["-I", str(d)]) + if line_ending_terminator is not None: + command.append(f"-l{line_ending_terminator}") + for m in use_modules_m: + command.extend(["-m", m]) + for m in use_modules_M: + command.extend(["-M", m]) + for m in no_modules_M: + command.extend(["-M-", m]) + if loop_around_program: + command.append("-n") + if loop_and_print: + command.append("-p") + if rudimentary_switch_parsing: + command.append("-s") + if search_path_for_program: + command.append("-S") + if tainting_warnings: + command.append("-t") + if tainting_checks: + command.append("-T") + if dump_core: + command.append("-u") + if allow_unsafe_operations: + command.append("-U") + if print_version: + command.append("-v") + if print_config_summary is not None: + command.append(f"-V{':' + print_config_summary if print_config_summary else ''}") + if enable_warnings: + command.append("-w") + if enable_all_warnings: + command.append("-W") + if ignore_text_directory is not None: + command.append(f"-x{str(ignore_text_directory) if ignore_text_directory else ''}") + if disable_all_warnings: + command.append("-X") + + # Add program file and its arguments + if program_file: + command.append(str(program_file)) + command.extend(program_arguments) + + command_executed = " ".join(str(arg) for arg in command) + stdout = "" + stderr = "" + output_files: List[Path] = [] + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "returncode": e.returncode, + "output_files": output_files, + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: Perl executable not found. Ensure Perl is installed and in your PATH.", + "error": "Perl executable not found.", + "returncode": 127, + "output_files": output_files, + } + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-samtools/app/perl-bio-samtools_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-samtools/app/perl-bio-samtools_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..bc6cacc0febfa603ac812a6bfdac3ebaa3752d0e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-samtools/app/perl-bio-samtools_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-bio-samtools/app/perl-bio-samtools_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_bio_samtools' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-samtools/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-samtools/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-samtools/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-samtools/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-samtools/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..937bf65745e4825484c3bb95398404113772cf87 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-samtools/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-bio-samtools: + build: . + image: mcp-perl-bio-samtools:latest + container_name: mcp-perl-bio-samtools + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-bio-samtools + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-samtools/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-samtools/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d8784daee314a4c90b9e29192e2d045412aa48a5 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-samtools/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-bio-samtools + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-samtools/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-samtools/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-samtools/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-searchio-hmmer/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-searchio-hmmer/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ff4c85c245cdc2fdaa10c116403fcd4626bdc79a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-searchio-hmmer/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-bio-searchio-hmmer via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-bio-searchio-hmmer -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-bio-searchio-hmmer_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-bio-searchio-hmmer_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-bio-searchio-hmmer_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-searchio-hmmer/app/__pycache__/perl-bio-searchio-hmmer_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-searchio-hmmer/app/__pycache__/perl-bio-searchio-hmmer_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1aa3959fb26bf41e01f69f9f4d1fc758e325407b Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-searchio-hmmer/app/__pycache__/perl-bio-searchio-hmmer_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-searchio-hmmer/app/perl-bio-searchio-hmmer_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-searchio-hmmer/app/perl-bio-searchio-hmmer_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8bacf9f444ac0f5e725fea2c8ded86ce0b766dc9 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-searchio-hmmer/app/perl-bio-searchio-hmmer_server.py @@ -0,0 +1,192 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Literal, Dict, Any + +# The MCP decorator is assumed to be available in the execution environment. +# from mcp import tool as mcp_tool + +# For local testing, you can use a placeholder decorator: +def mcp_tool_placeholder(*args, **kwargs): + def decorator(func): + return func + return decorator + +mcp = type('mcp', (), {'tool': mcp_tool_placeholder}) + + +# The self-contained Perl script that uses the Bio::SearchIO::hmmer module. +# Dollar signs and at-signs are escaped for use in Python strings. +PERL_PARSER_SCRIPT = r""" +#!/usr/bin/env perl +use strict; +use warnings; +use Getopt::Long; +use Bio::SearchIO; +use JSON; + +# --- Command line arguments --- +my $input_file = ''; +my $format = 'tsv'; # Default format +GetOptions( + 'input=s' => \$input_file, + 'format=s' => \$format, +) or die "Error in command line arguments\n"; + +die "Usage: $0 --input --format [tsv|json]\n" unless $input_file; +die "Input file not found: $input_file\n" unless -e $input_file; +die "Invalid format: $format. Choose 'tsv' or 'json'.\n" unless $format eq 'tsv' or $format eq 'json'; + +# --- Main parsing logic --- +# The format 'hmmer' in Bio::SearchIO handles both HMMER2 and HMMER3 +my $searchio = Bio::SearchIO->new(-file => $input_file, -format => 'hmmer'); + +my @results_data; + +while (my $result = $searchio->next_result) { + # Skip if no hits + next unless $result->num_hits > 0; + + while (my $hit = $result->next_hit) { + while (my $hsp = $hit->next_hsp) { + # Use placeholders for potentially missing values to avoid errors + my $query_name = $result->query_name // 'N/A'; + my $query_len = $result->query_length // 0; + my $hit_name = $hit->name // 'N/A'; + my $hit_acc = $hit->accession // 'N/A'; + my $hit_desc = $hit->description // 'N/A'; + my $hit_len = $hit->length // 0; + my $evalue = $hit->significance // 'N/A'; + my $bits = $hsp->bits // 0; + + push @results_data, { + query_name => $query_name, + query_length => $query_len, + hit_name => $hit_name, + hit_accession => $hit_acc, + hit_description => $hit_desc, + hit_length => $hit_len, + significance => $evalue, + bits => $bits, + hsp_start_query => $hsp->start('query'), + hsp_end_query => $hsp->end('query'), + hsp_start_hit => $hsp->start('hit'), + hsp_end_hit => $hsp->end('hit'), + hsp_strand_query => $hsp->strand('query'), + hsp_strand_hit => $hsp->strand('hit'), + }; + } + } +} + +# --- Output generation --- +if ($format eq 'json') { + print to_json(\@results_data, { pretty => 1 }); +} else { # tsv + # Print header + my @headers = qw(query_name query_length hit_name hit_accession hit_description hit_length significance bits hsp_start_query hsp_end_query hsp_start_hit hsp_end_hit hsp_strand_query hsp_strand_hit); + print join("\t", @headers), "\n"; + # Print data + for my $data (@results_data) { + # Ensure all values are defined to avoid warnings + my @values = map { defined $_ ? $_ : '' } @{$data}{@headers}; + print join("\t", @values), "\n"; + } +} +""" + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_bio_searchio_hmmer' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def perl_bio_searchio_hmmer( + hmmer_file: Path, + output_file: Path, + output_format: Literal["tsv", "json"] = "tsv", +) -> Dict[str, Any]: + """ + Parses HMMER2/HMMER3 output files using the Bio::SearchIO::hmmer Perl module. + + This tool acts as a command-line wrapper for the `perl-bio-searchio-hmmer` + library. It takes a standard HMMER output file (from hmmscan, hmmsearch, etc.) + and converts it into a structured format, either Tab-Separated Values (TSV) + or JSON, saving the result to a specified output file. + + Args: + hmmer_file: Path to the input HMMER output file. + output_file: Path to save the parsed results. + output_format: The desired format for the output file ('tsv' or 'json'). + Defaults to 'tsv'. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a + list with the path to the generated output file. + """ + # Input validation + if not hmmer_file.exists(): + raise FileNotFoundError(f"Input file not found: {hmmer_file}") + if not hmmer_file.is_file(): + raise ValueError(f"Input path is not a file: {hmmer_file}") + if output_file.is_dir(): + raise ValueError(f"Output path cannot be a directory: {output_file}") + + # Create a temporary file for the Perl script + temp_script_path = None + try: + with tempfile.NamedTemporaryFile( + mode='w', delete=False, suffix=".pl", encoding='utf-8' + ) as temp_script: + temp_script.write(PERL_PARSER_SCRIPT) + temp_script_path = Path(temp_script.name) + + cmd = [ + "perl", + str(temp_script_path), + "--input", + str(hmmer_file), + "--format", + output_format, + ] + command_executed = " ".join(cmd) + + # Execute the command and write output directly to the specified file + with open(output_file, "w", encoding='utf-8') as f_out: + result = subprocess.run( + cmd, + stdout=f_out, + stderr=subprocess.PIPE, + text=True, + check=True, + encoding='utf-8' + ) + + stderr_content = result.stderr + + return { + "command_executed": command_executed, + "stdout": f"Output successfully written to {output_file}", + "stderr": stderr_content, + "output_files": [str(output_file)], + } + + except FileNotFoundError: + # This happens if 'perl' is not in the system's PATH + raise RuntimeError("Perl executable not found. Please ensure Perl and the required modules (Bio::SearchIO) are installed and in your PATH.") + except subprocess.CalledProcessError as e: + # The Perl script writes its own errors to stderr, which is captured here. + return { + "command_executed": command_executed, + "stdout": e.stdout or "", + "stderr": e.stderr or "Perl script failed with an unknown error.", + "output_files": [], + "error": f"Process failed with exit code {e.returncode}" + } + finally: + # Always clean up the temporary script + if temp_script_path and temp_script_path.exists(): + temp_script_path.unlink() + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-searchio-hmmer/app/perl-bio-searchio-hmmer_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-searchio-hmmer/app/perl-bio-searchio-hmmer_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..75f34d76f0b185ca646cf2eb1e9de6d54b93640d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-searchio-hmmer/app/perl-bio-searchio-hmmer_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-bio-searchio-hmmer/app/perl-bio-searchio-hmmer_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_bio_searchio_hmmer' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-searchio-hmmer/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-searchio-hmmer/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-searchio-hmmer/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-searchio-hmmer/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-searchio-hmmer/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..022502e983ce32be8d3fdccba9d07621a6d8042a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-searchio-hmmer/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-bio-searchio-hmmer: + build: . + image: mcp-perl-bio-searchio-hmmer:latest + container_name: mcp-perl-bio-searchio-hmmer + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-bio-searchio-hmmer + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-searchio-hmmer/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-searchio-hmmer/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8e1545c2a159727a8767c8db73031f6d3857cad6 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-searchio-hmmer/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-bio-searchio-hmmer + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-searchio-hmmer/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-searchio-hmmer/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-bio-searchio-hmmer/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-business-isbn/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-business-isbn/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..bb12af3b2b44d90d74dd0621c6de023b369a1b04 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-business-isbn/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-business-isbn via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-business-isbn -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-business-isbn_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-business-isbn_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-business-isbn_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-business-isbn/app/__pycache__/perl-business-isbn_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-business-isbn/app/__pycache__/perl-business-isbn_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e0ecae159e9820339b08400c060e7f9bbb741fa3 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-business-isbn/app/__pycache__/perl-business-isbn_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-business-isbn/app/perl-business-isbn_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-business-isbn/app/perl-business-isbn_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8c20149a0ad8cb9cf8a08fa66162c5a1db35a367 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-business-isbn/app/perl-business-isbn_server.py @@ -0,0 +1,299 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +# This is a placeholder for the actual decorator. +# The user specified "NO NEED to import mcp". +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +def _run_isbn_tool( + action_flag: str, + isbns: Optional[List[str]] = None, + input_file: Optional[Path] = None, + output_file: Optional[Path] = None, + separator: Optional[str] = None, + data_file: Optional[Path] = None, + debug: bool = False, +) -> Dict[str, Any]: + """ + Internal helper function to build and execute isbn_tool.pl commands. + + This function handles parameter validation, command construction, subprocess execution, + and result formatting. + """ + # Input validation: Ensure either ISBNs are provided directly or via a file. + if not isbns and not input_file: + raise ValueError("Either a list of ISBNs (`isbns`) or an input file (`input_file`) must be provided.") + if isbns and input_file: + raise ValueError("Provide either a list of ISBNs (`isbns`) or an input file (`input_file`), not both.") + + # Base command for the perl script + cmd = ["isbn_tool.pl", action_flag] + + if debug: + cmd.append("--debug") + + if separator: + cmd.extend(["--separator", separator]) + + if data_file: + if not data_file.is_file(): + raise FileNotFoundError(f"The specified data file does not exist: {data_file}") + cmd.extend(["--data", str(data_file)]) + + if output_file: + # Ensure parent directory exists for the output file + output_file.parent.mkdir(parents=True, exist_ok=True) + cmd.extend(["--output", str(output_file)]) + + if input_file: + if not input_file.is_file(): + raise FileNotFoundError(f"The specified input file does not exist: {input_file}") + cmd.extend(["--input", str(input_file)]) + + if isbns: + cmd.extend(isbns) + + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + output_files_list = [str(output_file)] if output_file else [] + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files_list, + } + except FileNotFoundError: + raise RuntimeError("`isbn_tool.pl` not found. Is the Business::ISBN Perl module installed and in your system's PATH?") + except subprocess.CalledProcessError as e: + # Return a structured error if the command fails + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Command failed with exit code {e.returncode}", + "output_files": [], + } + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_business_isbn' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def check_isbn( + isbns: Optional[List[str]] = None, + input_file: Optional[Path] = None, + output_file: Optional[Path] = None, + separator: Optional[str] = None, + data_file: Optional[Path] = None, + debug: bool = False, +) -> Dict[str, Any]: + """ + Checks the validity of one or more ISBNs. + + Args: + isbns: A list of ISBN strings to check. + input_file: Path to a file containing ISBNs, one per line. + output_file: Path to a file to write the output to. + separator: Separator for output fields (default is a tab). + data_file: Path to the RangeMessage.xml file for publisher data. + debug: If True, turn on debugging information. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + return _run_isbn_tool( + action_flag="--check", + isbns=isbns, + input_file=input_file, + output_file=output_file, + separator=separator, + data_file=data_file, + debug=debug, + ) + +@mcp.tool() +def to_isbn13( + isbns: Optional[List[str]] = None, + input_file: Optional[Path] = None, + output_file: Optional[Path] = None, + separator: Optional[str] = None, + data_file: Optional[Path] = None, + debug: bool = False, +) -> Dict[str, Any]: + """ + Converts one or more ISBN-10s to ISBN-13s. + + Args: + isbns: A list of ISBN-10 strings to convert. + input_file: Path to a file containing ISBN-10s, one per line. + output_file: Path to a file to write the output to. + separator: Separator for output fields (default is a tab). + data_file: Path to the RangeMessage.xml file. + debug: If True, turn on debugging information. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + return _run_isbn_tool( + action_flag="--to-isbn13", + isbns=isbns, + input_file=input_file, + output_file=output_file, + separator=separator, + data_file=data_file, + debug=debug, + ) + +@mcp.tool() +def to_isbn10( + isbns: Optional[List[str]] = None, + input_file: Optional[Path] = None, + output_file: Optional[Path] = None, + separator: Optional[str] = None, + data_file: Optional[Path] = None, + debug: bool = False, +) -> Dict[str, Any]: + """ + Converts one or more ISBN-13s to ISBN-10s. + + Args: + isbns: A list of ISBN-13 strings to convert. + input_file: Path to a file containing ISBN-13s, one per line. + output_file: Path to a file to write the output to. + separator: Separator for output fields (default is a tab). + data_file: Path to the RangeMessage.xml file. + debug: If True, turn on debugging information. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + return _run_isbn_tool( + action_flag="--to-isbn10", + isbns=isbns, + input_file=input_file, + output_file=output_file, + separator=separator, + data_file=data_file, + debug=debug, + ) + +@mcp.tool() +def get_publisher_data( + isbns: Optional[List[str]] = None, + input_file: Optional[Path] = None, + output_file: Optional[Path] = None, + separator: Optional[str] = None, + data_file: Optional[Path] = None, + debug: bool = False, +) -> Dict[str, Any]: + """ + Retrieves publisher data for one or more ISBNs. Requires the RangeMessage.xml data file. + + Args: + isbns: A list of ISBN strings to query. + input_file: Path to a file containing ISBNs, one per line. + output_file: Path to a file to write the output to. + separator: Separator for output fields (default is a tab). + data_file: Path to the RangeMessage.xml file. This is required for this function. + debug: If True, turn on debugging information. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + if not data_file: + raise ValueError("The `data_file` parameter pointing to RangeMessage.xml is required for getting publisher data.") + + return _run_isbn_tool( + action_flag="--publisher", + isbns=isbns, + input_file=input_file, + output_file=output_file, + separator=separator, + data_file=data_file, + debug=debug, + ) + +@mcp.tool() +def fix_isbn( + isbns: Optional[List[str]] = None, + input_file: Optional[Path] = None, + output_file: Optional[Path] = None, + separator: Optional[str] = None, + data_file: Optional[Path] = None, + debug: bool = False, +) -> Dict[str, Any]: + """ + Attempts to fix a mangled ISBN, typically by correcting the checksum. + + Args: + isbns: A list of mangled ISBN strings to fix. + input_file: Path to a file containing mangled ISBNs, one per line. + output_file: Path to a file to write the output to. + separator: Separator for output fields (default is a tab). + data_file: Path to the RangeMessage.xml file. + debug: If True, turn on debugging information. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + return _run_isbn_tool( + action_flag="--fix", + isbns=isbns, + input_file=input_file, + output_file=output_file, + separator=separator, + data_file=data_file, + debug=debug, + ) + +@mcp.tool() +def format_isbn( + isbns: Optional[List[str]] = None, + input_file: Optional[Path] = None, + output_file: Optional[Path] = None, + separator: Optional[str] = None, + data_file: Optional[Path] = None, + debug: bool = False, +) -> Dict[str, Any]: + """ + Formats an ISBN in a standard way, typically by adding hyphens. + + Args: + isbns: A list of ISBN strings to format. + input_file: Path to a file containing ISBNs, one per line. + output_file: Path to a file to write the output to. + separator: Separator for output fields (default is a tab). + data_file: Path to the RangeMessage.xml file. + debug: If True, turn on debugging information. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + return _run_isbn_tool( + action_flag="--format", + isbns=isbns, + input_file=input_file, + output_file=output_file, + separator=separator, + data_file=data_file, + debug=debug, + ) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-business-isbn/app/perl-business-isbn_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-business-isbn/app/perl-business-isbn_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b9c20199a999eac33a6254afc3432652f32bc4ce --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-business-isbn/app/perl-business-isbn_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-business-isbn/app/perl-business-isbn_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_business_isbn' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-business-isbn/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-business-isbn/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-business-isbn/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-business-isbn/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-business-isbn/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..fdfe55ce28efcfea8f9d43b6620771d781e3ab95 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-business-isbn/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-business-isbn: + build: . + image: mcp-perl-business-isbn:latest + container_name: mcp-perl-business-isbn + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-business-isbn + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-business-isbn/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-business-isbn/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b4b0dbb93f6a6f383c3ff481a1c2e1d78720641e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-business-isbn/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-business-isbn + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-business-isbn/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-business-isbn/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-business-isbn/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-convert-binhex/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-convert-binhex/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..657dc336c93bb774b897cc78a2c50963f0b7a627 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-convert-binhex/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-convert-binhex via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-convert-binhex -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-convert-binhex_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-convert-binhex_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-convert-binhex_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-convert-binhex/app/__pycache__/perl-convert-binhex_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-convert-binhex/app/__pycache__/perl-convert-binhex_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cbce14956a21d43b9607f4b797c2bc10d0045b14 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-convert-binhex/app/__pycache__/perl-convert-binhex_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-convert-binhex/app/perl-convert-binhex_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-convert-binhex/app/perl-convert-binhex_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6f7efaefefe966b90f8e899e2f4b35ac4cfc9813 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-convert-binhex/app/perl-convert-binhex_server.py @@ -0,0 +1,212 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any + +# No need to import mcp, as per instructions. + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_convert_binhex' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_perl_script( + program_file: Optional[Path] = None, + program_arguments: Optional[List[str]] = None, + record_separator_octal: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + debugger: Optional[str] = None, + debug_flags: Optional[str] = None, + program_one_liner: Optional[List[str]] = None, + program_one_liner_extended: Optional[List[str]] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + edit_in_place_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_ending_processing_terminator: Optional[str] = None, + module_options: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + rudimentary_switch_parsing: bool = False, + search_programfile_in_path: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core_after_parsing: bool = False, + allow_unsafe_operations: bool = False, + print_version: bool = False, + print_config_summary: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_text_before_shebang_dir: Optional[Path] = None, + disable_all_warnings: bool = False, +) -> Dict[str, Any]: + """ + Executes a Perl script or one-liner using the Perl interpreter. + + This tool provides access to the command-line switches of the `perl` interpreter. + It can be used to run any Perl script, including those that utilize modules like + `Convert::BinHex` for specific tasks (e.g., `perl -MConvert::BinHex -e '...'`). + + Args: + program_file: Path to the Perl program file to execute. + program_arguments: Arguments to pass to the Perl program. + record_separator_octal: Specify record separator (e.g., '0' for null, '0777' for paragraph mode). + autosplit: Enable autosplit mode with -n or -p (splits $_ into @F). + unicode_features: Enables listed Unicode features (e.g., 'all', 'say'). + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks). + debugger: Run program under debugger (e.g., 'MyDebugger'). + debug_flags: Set debugging flags (argument is a bit mask or alphabets). + program_one_liner: One line of program (can be specified multiple times). + program_one_liner_extended: Like -e, but enables all optional features (can be specified multiple times). + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup. + split_pattern: split() pattern for -a switch (e.g., '/\s+/'). + edit_in_place_extension: Edit <> files in place (makes backup if extension supplied, e.g., '.bak'). + include_directories: Specify @INC/#include directory (can be specified multiple times). + line_ending_processing_terminator: Enable line ending processing, specifies line terminator (e.g., '0' for newline). + module_options: Execute "use/no module..." before executing program (e.g., 'MConvert::BinHex', 'm-strict'). + loop_around_program: Assume "while (<>) { ... }" loop around program. + loop_and_print: Assume loop like -n but print line also, like sed. + rudimentary_switch_parsing: Enable rudimentary parsing for switches after programfile. + search_programfile_in_path: Look for programfile using PATH environment variable. + tainting_warnings: Enable tainting warnings. + tainting_checks: Enable tainting checks. + dump_core_after_parsing: Dump core after parsing program. + allow_unsafe_operations: Allow unsafe operations. + print_version: Print version, patchlevel and license. + print_config_summary: Print configuration summary (or a single Config.pm variable, e.g., 'archname'). + enable_warnings: Enable many useful warnings. + enable_all_warnings: Enable all warnings. + ignore_text_before_shebang_dir: Ignore text before #!perl line (optionally cd to directory). + disable_all_warnings: Disable all warnings. + """ + cmd = ["perl"] + output_files: List[Path] = [] + + # Input validation and command construction + if program_file and not program_file.is_file(): + raise FileNotFoundError(f"Program file not found: {program_file}") + + if program_one_liner and program_file: + raise ValueError("Cannot specify both 'program_one_liner' and 'program_file'. Use one or the other.") + if program_one_liner_extended and program_file: + raise ValueError("Cannot specify both 'program_one_liner_extended' and 'program_file'. Use one or the other.") + if program_one_liner and program_one_liner_extended: + raise ValueError("Cannot specify both '-e' and '-E' program one-liners.") + + if loop_around_program and loop_and_print: + raise ValueError("Cannot specify both 'loop_around_program' (-n) and 'loop_and_print' (-p). They are mutually exclusive.") + + if record_separator_octal is not None: + cmd.append(f"-0{record_separator_octal}") + if autosplit: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if debugger is not None: + cmd.append(f"-d:{debugger}" if debugger else "-d") + if debug_flags is not None: + cmd.append(f"-D{debug_flags}") + if program_one_liner: + for line in program_one_liner: + cmd.extend(["-e", line]) + if program_one_liner_extended: + for line in program_one_liner_extended: + cmd.extend(["-E", line]) + if no_sitecustomize: + cmd.append("-f") + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + if edit_in_place_extension is not None: + cmd.append(f"-i{edit_in_place_extension}") + if include_directories: + for d in include_directories: + if not d.is_dir(): + raise NotADirectoryError(f"Include directory not found: {d}") + cmd.extend(["-I", str(d)]) + if line_ending_processing_terminator is not None: + cmd.append(f"-l{line_ending_processing_terminator}") + if module_options: + for mod_opt in module_options: + # Validate module_options format if possible, but perl handles it. + # Example: -MConvert::BinHex, -mstrict, -m-warnings + if not (mod_opt.startswith("M") or mod_opt.startswith("m")): + raise ValueError(f"Invalid module option format: {mod_opt}. Must start with 'M' or 'm'.") + cmd.append(f"-{mod_opt}") + if loop_around_program: + cmd.append("-n") + if loop_and_print: + cmd.append("-p") + if rudimentary_switch_parsing: + cmd.append("-s") + if search_programfile_in_path: + cmd.append("-S") + if tainting_warnings: + cmd.append("-t") + if tainting_checks: + cmd.append("-T") + if dump_core_after_parsing: + cmd.append("-u") + if allow_unsafe_operations: + cmd.append("-U") + if print_version: + cmd.append("-v") + if print_config_summary is not None: + cmd.append(f"-V:{print_config_summary}" if print_config_summary else "-V") + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if ignore_text_before_shebang_dir is not None: + if ignore_text_before_shebang_dir and not ignore_text_before_shebang_dir.is_dir(): + raise NotADirectoryError(f"Directory for -x option not found: {ignore_text_before_shebang_dir}") + cmd.append(f"-x{ignore_text_before_shebang_dir}" if ignore_text_before_shebang_dir else "-x") + if disable_all_warnings: + cmd.append("-X") + + if program_file: + cmd.append(str(program_file)) + + if program_arguments: + cmd.extend(program_arguments) + + # Execute the command + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl execution failed with exit code {e.returncode}", + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": "Error: 'perl' command not found. Ensure Perl is installed and in your PATH.", + "error": "Perl executable not found.", + "output_files": [], + } + + return { + "command_executed": " ".join(cmd), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-convert-binhex/app/perl-convert-binhex_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-convert-binhex/app/perl-convert-binhex_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..abfd39a9efc0acd1c034764fb8e9cb0b4a8fbde1 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-convert-binhex/app/perl-convert-binhex_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-convert-binhex/app/perl-convert-binhex_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_convert_binhex' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-convert-binhex/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-convert-binhex/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-convert-binhex/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-convert-binhex/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-convert-binhex/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..0ac31b04628529979dfe0b7fa7240b8d88137623 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-convert-binhex/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-convert-binhex: + build: . + image: mcp-perl-convert-binhex:latest + container_name: mcp-perl-convert-binhex + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-convert-binhex + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-convert-binhex/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-convert-binhex/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7a6e762d244f6941c0966dddbac77d8ed360f2ca --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-convert-binhex/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-convert-binhex + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-convert-binhex/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-convert-binhex/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-convert-binhex/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-cpan-meta-requirements/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-cpan-meta-requirements/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..dc43e5287f8699dca5cecd622f5fb69a1c7daec5 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-cpan-meta-requirements/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-cpan-meta-requirements via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-cpan-meta-requirements -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-cpan-meta-requirements_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-cpan-meta-requirements_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-cpan-meta-requirements_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-cpan-meta-requirements/app/__pycache__/perl-cpan-meta-requirements_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-cpan-meta-requirements/app/__pycache__/perl-cpan-meta-requirements_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..05212f9d6864c4af3151591dc9dfc6e4df43a1cd Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-cpan-meta-requirements/app/__pycache__/perl-cpan-meta-requirements_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-cpan-meta-requirements/app/perl-cpan-meta-requirements_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-cpan-meta-requirements/app/perl-cpan-meta-requirements_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1f8fa3479bba179e8b04931f0458236074274689 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-cpan-meta-requirements/app/perl-cpan-meta-requirements_server.py @@ -0,0 +1,224 @@ +import subprocess +import json +from typing import Optional, Dict, List +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_cpan_meta_requirements' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def check_version_satisfaction( + module: str, + requirement_string: str, + version_to_check: str, +) -> Dict: + """ + Checks if a specific version of a Perl module satisfies a given requirement string. + + Args: + module: The name of the Perl module (e.g., 'CPAN::Meta'). + requirement_string: The version requirement (e.g., '>= 1.20, != 1.25', '0'). + version_to_check: The version string to validate (e.g., '1.21'). + """ + # Input validation + if not module or not requirement_string or not version_to_check: + return {"error": "Module, requirement_string, and version_to_check are all required."} + + # Perl script to use the library + perl_code = f""" + use CPAN::Meta::Requirements; + my $req = CPAN::Meta::Requirements->new; + eval {{ + $req->add_string_requirement('{module}', '{requirement_string}'); + my $result = $req->accepts_module('{module}', '{version_to_check}'); + print $result ? "true" : "false"; + }}; + if ($@) {{ + die "Error processing requirements: $@"; + }} + """ + + try: + process = subprocess.run( + ["perl", "-e", perl_code], + capture_output=True, + text=True, + check=True + ) + + is_satisfied = process.stdout.strip() == "true" + + return { + "command_executed": f"perl -MCPAN::Meta::Requirements ...", + "module": module, + "requirement": requirement_string, + "version_checked": version_to_check, + "is_satisfied": is_satisfied, + "stdout": process.stdout, + "stderr": process.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "Perl execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd + } + +@mcp.tool() +def merge_requirement_sets( + set_1: Dict[str, str], + set_2: Dict[str, str], +) -> Dict: + """ + Merges two sets of CPAN module requirements. If both sets have requirements for the + same module, they are combined (intersected) to satisfy both. + + Args: + set_1: A dictionary where keys are module names and values are requirement strings. + set_2: A second dictionary of module requirements to merge with the first. + """ + # Convert dicts to JSON for safe passing to Perl + json_1 = json.dumps(set_1) + json_2 = json.dumps(set_2) + + perl_code = """ + use CPAN::Meta::Requirements; + use JSON::PP; + + my $json = JSON::PP->new; + my $data1 = $json->decode($ARGV[0]); + my $data2 = $json->decode($ARGV[1]); + + my $req1 = CPAN::Meta::Requirements->from_string_hash($data1); + my $req2 = CPAN::Meta::Requirements->from_string_hash($data2); + + $req1->add_requirements($req2); + + print $json->encode($req1->as_string_hash); + """ + + try: + process = subprocess.run( + ["perl", "-MJSON::PP", "-MCPAN::Meta::Requirements", "-e", perl_code, json_1, json_2], + capture_output=True, + text=True, + check=True + ) + + merged_requirements = json.loads(process.stdout) + + return { + "command_executed": "perl -MCPAN::Meta::Requirements -MJSON::PP ...", + "merged_requirements": merged_requirements, + "stdout": process.stdout, + "stderr": process.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to merge requirements", + "stderr": e.stderr + } + except json.JSONDecodeError: + return { + "error": "Failed to parse Perl output as JSON", + "stdout": process.stdout + } + +@mcp.tool() +def validate_requirement_string( + requirement_string: str, +) -> Dict: + """ + Validates if a version requirement string is syntactically correct according to CPAN standards. + + Args: + requirement_string: The version requirement string to validate (e.g., '>= 1.0, < 2.0'). + """ + perl_code = f""" + use CPAN::Meta::Requirements; + eval {{ + my $req = CPAN::Meta::Requirements->new; + $req->add_string_requirement('Dummy::Module', '{requirement_string}'); + print "valid"; + }}; + if ($@) {{ + print "invalid: $@"; + }} + """ + + try: + process = subprocess.run( + ["perl", "-e", perl_code], + capture_output=True, + text=True, + check=True + ) + + output = process.stdout.strip() + is_valid = output == "valid" + + return { + "requirement": requirement_string, + "is_valid": is_valid, + "error_message": None if is_valid else output.replace("invalid: ", ""), + "stdout": process.stdout, + "stderr": process.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "Execution failed", + "stderr": e.stderr + } + +@mcp.tool() +def simplify_requirements( + requirements: Dict[str, str], +) -> Dict: + """ + Simplifies a set of requirements to their most concise form. + + Args: + requirements: A dictionary of module names and their requirement strings. + """ + req_json = json.dumps(requirements) + + perl_code = """ + use CPAN::Meta::Requirements; + use JSON::PP; + + my $json = JSON::PP->new; + my $data = $json->decode($ARGV[0]); + + my $req = CPAN::Meta::Requirements->from_string_hash($data); + # finalize() returns a new object with requirements simplified + my $final = $req->finalize; + + print $json->encode($final->as_string_hash); + """ + + try: + process = subprocess.run( + ["perl", "-MJSON::PP", "-MCPAN::Meta::Requirements", "-e", perl_code, req_json], + capture_output=True, + text=True, + check=True + ) + + simplified = json.loads(process.stdout) + + return { + "original": requirements, + "simplified": simplified, + "stdout": process.stdout + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to simplify requirements", + "stderr": e.stderr + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-cpan-meta-requirements/app/perl-cpan-meta-requirements_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-cpan-meta-requirements/app/perl-cpan-meta-requirements_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6a7bee56dc470e20f9ed7ae291b5c5fa7b0a40dc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-cpan-meta-requirements/app/perl-cpan-meta-requirements_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-cpan-meta-requirements/app/perl-cpan-meta-requirements_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_cpan_meta_requirements' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-cpan-meta-requirements/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-cpan-meta-requirements/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-cpan-meta-requirements/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-cpan-meta-requirements/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-cpan-meta-requirements/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d902f67eec6fd1e13587b4a161ebf7748a93518a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-cpan-meta-requirements/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-cpan-meta-requirements + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-cpan-meta-requirements/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-cpan-meta-requirements/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-cpan-meta-requirements/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-dbi/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-dbi/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c4d599e42fd91f8926aa73f890e810124c40d319 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-dbi/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-dbi via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-dbi -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-dbi_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-dbi_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-dbi_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-dbi/app/__pycache__/perl-dbi_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-dbi/app/__pycache__/perl-dbi_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7c3e80ba15c0283df4652d258e883fd79f3799b4 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-dbi/app/__pycache__/perl-dbi_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-dbi/app/perl-dbi_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-dbi/app/perl-dbi_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4b45d090cd8475ef2dda849d17a9237fcc1f39d2 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-dbi/app/perl-dbi_server.py @@ -0,0 +1,254 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, List, Dict + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_dbi' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_perl_script( + programfile: Optional[str] = None, + arguments: Optional[List[str]] = None, + execute_program: Optional[List[str]] = None, + execute_program_extended: Optional[List[str]] = None, + check_syntax_only: bool = False, + print_version: bool = False, + print_config: Optional[str] = None, + record_separator: Optional[str] = None, + autosplit: bool = False, + autosplit_pattern: Optional[str] = None, + unicode_features: Optional[str] = None, + debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + no_sitecustomize: bool = False, + in_place_edit: Optional[str] = None, + include_directories: Optional[List[str]] = None, + use_modules: Optional[List[str]] = None, + no_modules: Optional[List[str]] = None, + use_modules_no_import: Optional[List[str]] = None, + no_modules_no_import: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + parse_switches: bool = False, + search_path: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core: bool = False, + allow_unsafe: bool = False, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + disable_all_warnings: bool = False, + extract_script_and_cd: Optional[str] = None, + line_ending_processing: Optional[str] = None, +) -> Dict: + """ + Executes a Perl script or one-liner using the Perl interpreter. + Useful for running DBI-related scripts (ensure 'DBI' is in use_modules or the script). + + Args: + programfile: Path to the Perl program file to execute. + arguments: Arguments passed to the script (stored in @ARGV). + execute_program: One line of program. Can be used multiple times. (-e) + execute_program_extended: Like -e, but enables all optional features. (-E) + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks). (-c) + print_version: Print version, patchlevel, and license. (-v) + print_config: Print configuration summary. Provide variable name or empty string. (-V) + record_separator: Specify record separator (octal). (-0) + autosplit: Enable autosplit mode with -n or -p. (-a) + autosplit_pattern: Specify the split() pattern for -a. (-F) + unicode_features: Enable listed Unicode features. (-C) + debugger: Run program under the debugger. (-d) + debugging_flags: Set debugging flags. (-D) + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup. (-f) + in_place_edit: Edit files in place (provide extension for backup). (-i) + include_directories: Directories to search for modules. (-I) + use_modules: Execute 'use module...' before program. (-M) + no_modules: Execute 'no module...' before program. (-M-) + use_modules_no_import: Execute 'use module ()' before program. (-m) + no_modules_no_import: Execute 'no module ()' before program. (-m-) + loop_around_program: Assume 'while (<>) { ... }' loop. (-n) + loop_and_print: Assume loop like -n but print line. (-p) + parse_switches: Enable rudimentary parsing for switches after program file. (-s) + search_path: Look for program file using PATH environment variable. (-S) + tainting_warnings: Enable tainting warnings. (-t) + tainting_checks: Enable tainting checks. (-T) + dump_core: Dump core after parsing program. (-u) + allow_unsafe: Allow unsafe operations. (-U) + enable_warnings: Enable many useful warnings. (-w) + enable_all_warnings: Enable all warnings. (-W) + disable_all_warnings: Disable all warnings. (-X) + extract_script_and_cd: Ignore text before #!perl line and optionally cd. (-x) + line_ending_processing: Enable line ending processing. (-l) + """ + # 1. Input Validation + sources = [programfile, execute_program, execute_program_extended, print_version, print_config is not None] + if sum(1 for s in sources if s) == 0: + return {"error": "A program source (file, -e, -E, -v, or -V) must be provided."} + + cmd = ["perl"] + + # 2. Flag Construction + if record_separator is not None: cmd.append(f"-0{record_separator}") + if autosplit: cmd.append("-a") + if unicode_features is not None: cmd.append(f"-C{unicode_features}") + if check_syntax_only: cmd.append("-c") + if debugger is not None: cmd.append(f"-d{debugger}" if debugger else "-d") + if debugging_flags is not None: cmd.append(f"-D{debugging_flags}") + if no_sitecustomize: cmd.append("-f") + if autosplit_pattern is not None: cmd.append(f"-F{autosplit_pattern}") + if in_place_edit is not None: cmd.append(f"-i{in_place_edit}") + + if include_directories: + for d in include_directories: + path_d = Path(d) + if not path_d.is_dir(): + return {"error": f"Include directory not found: {d}"} + cmd.extend(["-I", str(path_d)]) + + if line_ending_processing is not None: cmd.append(f"-l{line_ending_processing}") + + if use_modules: + for m in use_modules: cmd.append(f"-M{m}") + if no_modules: + for m in no_modules: cmd.append(f"-M-{m}") + if use_modules_no_import: + for m in use_modules_no_import: cmd.append(f"-m{m}") + if no_modules_no_import: + for m in no_modules_no_import: cmd.append(f"-m-{m}") + + if loop_around_program: cmd.append("-n") + if loop_and_print: cmd.append("-p") + if parse_switches: cmd.append("-s") + if search_path: cmd.append("-S") + if tainting_warnings: cmd.append("-t") + if tainting_checks: cmd.append("-T") + if dump_core: cmd.append("-u") + if allow_unsafe: cmd.append("-U") + if print_version: cmd.append("-v") + if print_config is not None: cmd.append(f"-V:{print_config}" if print_config else "-V") + if enable_warnings: cmd.append("-w") + if enable_all_warnings: cmd.append("-W") + if extract_script_and_cd is not None: cmd.append(f"-x{extract_script_and_cd}") + if disable_all_warnings: cmd.append("-X") + + if execute_program: + for e in execute_program: cmd.extend(["-e", e]) + if execute_program_extended: + for e in execute_program_extended: cmd.extend(["-E", e]) + + if programfile: + p = Path(programfile) + if not p.exists(): + return {"error": f"Program file not found: {programfile}"} + cmd.append(str(p)) + + if arguments: + cmd.extend(arguments) + + # 3. Execution + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl execution failed with exit code {e.returncode}" + } + +@mcp.tool() +def dbish( + dsn: Optional[str] = None, + user: Optional[str] = None, + password: Optional[str] = None, + batch: bool = False, + format: Optional[str] = None, + command: Optional[str] = None, +) -> Dict: + """ + Runs the DBI Shell (dbish), an interactive or batch interface to DBI. + + Args: + dsn: Data Source Name (e.g., dbi:SQLite:dbname=test.db). + user: Database user. + password: Database password. + batch: Run in batch mode (no prompts). + format: Output format (e.g., 'csv', 'html', 'neat'). + command: A single command to execute in dbish before exiting. + """ + cmd = ["dbish"] + + if batch: + cmd.append("--batch") + if format: + cmd.extend(["--format", format]) + + # Positional arguments for dbish + if dsn: + cmd.append(dsn) + if user: + cmd.append(user) + if password: + cmd.append(password) + + # If a single command is provided, we can pipe it to stdin + input_data = command if command else None + + try: + result = subprocess.run( + cmd, + input=input_data, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"dbish failed with exit code {e.returncode}" + } + +@mcp.tool() +def check_dbi_drivers() -> Dict: + """ + Lists all available DBI drivers installed in the current Perl environment. + """ + perl_code = "use DBI; print join('\\n', DBI->available_drivers);" + cmd = ["perl", "-e", perl_code] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + drivers = result.stdout.strip().split('\n') + return { + "command_executed": " ".join(cmd), + "available_drivers": drivers, + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to list DBI drivers." + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-dbi/app/perl-dbi_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-dbi/app/perl-dbi_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5c924ff21bbef67f38b4c87ed2e5380114511e61 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-dbi/app/perl-dbi_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-dbi/app/perl-dbi_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_dbi' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-dbi/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-dbi/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-dbi/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-dbi/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-dbi/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..4d94c8d9623d1df15976a3a489535c06cfefd002 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-dbi/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-dbi: + build: . + image: mcp-perl-dbi:latest + container_name: mcp-perl-dbi + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-dbi + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-dbi/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-dbi/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..86cc1b5e65573bee0e1fb73616747b4b70a418bb --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-dbi/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-dbi + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-dbi/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-dbi/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-dbi/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-perl-md5/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-perl-md5/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..09c5b8f98a626790361eacfdbea5c9df8f3efc29 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-perl-md5/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-digest-perl-md5 via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-digest-perl-md5 -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-digest-perl-md5_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-digest-perl-md5_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-digest-perl-md5_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-perl-md5/app/__pycache__/perl-digest-perl-md5_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-perl-md5/app/__pycache__/perl-digest-perl-md5_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c890ea570e5757808ff9580c14cdbb09fc7ebdf7 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-perl-md5/app/__pycache__/perl-digest-perl-md5_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-perl-md5/app/perl-digest-perl-md5_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-perl-md5/app/perl-digest-perl-md5_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2cec6b5165dbd4ee01d47c31afbd3fd97ea0b3bd --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-perl-md5/app/perl-digest-perl-md5_server.py @@ -0,0 +1,137 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Dict, Any + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided by the MCP framework. +def tool(func): + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + return wrapper + +mcp = type("mcp", (), {"tool": tool}) + +@mcp.tool +def digest_perl_md5( + input_file: Optional[Path] = None, + input_string: Optional[str] = None, + output_format: str = "hex", +) -> Dict[str, Any]: + """ + Calculates the MD5 hash of a file or a string using the Digest::Perl::MD5 module. + + This tool provides a command-line interface to the perl-digest-perl-md5 library, + which itself does not expose a direct executable. The function constructs a Perl + one-liner to compute the MD5 digest. + + Args: + input_file: Path to the input file to be hashed. + input_string: A string to be hashed. Provide either input_file or input_string, not both. + output_format: The format for the output digest. Must be one of 'hex', 'base64', or 'binary'. + + Returns: + A dictionary containing the command executed, stdout (the MD5 digest), + stderr, and a list of output files (none in this case). + """ + # Input validation + if not (input_file or input_string): + raise ValueError("Either 'input_file' or 'input_string' must be provided.") + if input_file and input_string: + raise ValueError("'input_file' and 'input_string' are mutually exclusive.") + + if input_file: + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if not input_file.is_file(): + raise ValueError(f"Input path is not a file: {input_file}") + + valid_formats = ["hex", "base64", "binary"] + if output_format not in valid_formats: + raise ValueError(f"Invalid output_format '{output_format}'. Must be one of {valid_formats}.") + + # Determine the Perl digest method based on the output format + digest_method_map = { + "hex": "hexdigest", + "base64": "b64digest", + "binary": "digest", + } + digest_method = digest_method_map[output_format] + + # Construct the Perl command + cmd: List[str] = [] + run_kwargs = { + "capture_output": True, + "check": True, + } + + if input_file: + perl_script = ( + f"use Digest::Perl::MD5; " + f"my $md5 = Digest::Perl::MD5->new; " + f"$md5->addfile(shift @ARGV); " + f"print $md5->{digest_method};" + ) + cmd = ["perl", "-e", perl_script, str(input_file)] + if output_format == "binary": + # Binary output should not be decoded as text + run_kwargs["text"] = False + else: + run_kwargs["text"] = True + + elif input_string is not None: + perl_script = ( + f"use Digest::Perl::MD5; " + f"my $md5 = Digest::Perl::MD5->new; " + f"$md5->add(); " + f"print $md5->{digest_method};" + ) + cmd = ["perl", "-e", perl_script] + if output_format == "binary": + run_kwargs["input"] = input_string.encode('utf-8') + run_kwargs["text"] = False + else: + run_kwargs["input"] = input_string + run_kwargs["text"] = True + + command_executed = " ".join(cmd) + + try: + result = subprocess.run(cmd, **run_kwargs) + + stdout_content = result.stdout + stderr_content = result.stderr + + # Decode if necessary + if isinstance(stdout_content, bytes) and run_kwargs.get("text") is not True: + # For binary output, we can't represent it as a simple string. + # We'll return it as a hex representation for display purposes. + stdout_str = stdout_content.hex() + else: + stdout_str = stdout_content + + if isinstance(stderr_content, bytes): + stderr_str = stderr_content.decode('utf-8', errors='ignore') + else: + stderr_str = stderr_content + + return { + "command_executed": command_executed, + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'perl' command not found. Is Perl installed and in your PATH?", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout.decode('utf-8', errors='ignore') if e.stdout else "", + "stderr": e.stderr.decode('utf-8', errors='ignore') if e.stderr else "", + "output_files": [] + } diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-perl-md5/app/perl-digest-perl-md5_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-perl-md5/app/perl-digest-perl-md5_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b7fb767c67b1bbb12aa63522ab6791bad27eb464 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-perl-md5/app/perl-digest-perl-md5_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-digest-perl-md5/app/perl-digest-perl-md5_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_digest_perl_md5' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-perl-md5/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-perl-md5/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-perl-md5/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-perl-md5/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-perl-md5/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..8212a7978cbe7ba961855e7bb0b28c4daffd1911 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-perl-md5/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-digest-perl-md5: + build: . + image: mcp-perl-digest-perl-md5:latest + container_name: mcp-perl-digest-perl-md5 + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-digest-perl-md5 + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-perl-md5/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-perl-md5/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ac01cd79770f06499ebeb1ee8746173e1dc9184f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-perl-md5/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-digest-perl-md5 + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-perl-md5/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-perl-md5/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-perl-md5/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-sha1/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-sha1/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..972c6938bfcdef4e96eece897756470eb824988e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-sha1/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-digest-sha1 via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-digest-sha1 -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-digest-sha1_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-digest-sha1_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-digest-sha1_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-sha1/app/__pycache__/perl-digest-sha1_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-sha1/app/__pycache__/perl-digest-sha1_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7ef08152b719fa58744184e78fbf1618961e204b Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-sha1/app/__pycache__/perl-digest-sha1_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-sha1/app/perl-digest-sha1_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-sha1/app/perl-digest-sha1_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e2d5be5a8bf0d8adce01a7f34dee08947847298f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-sha1/app/perl-digest-sha1_server.py @@ -0,0 +1,270 @@ +import subprocess +from pathlib import Path +from typing import Optional, Dict, Any + +# In a real MCP environment, this would be provided by the MCP framework. +# This is a placeholder for the purpose of this example. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_digest_sha1' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def sha1( + input_data: Optional[str] = None, + input_file: Optional[Path] = None +) -> Dict[str, Any]: + """ + Calculates the SHA-1 digest of a file or string and returns it in binary format. + + The Digest::SHA1 module allows you to use the NIST SHA-1 message digest + algorithm. The algorithm takes as input a message of arbitrary length and + produces as output a 160-bit "fingerprint" or "message digest" of the input. + This function returns the 20-byte binary digest. + + Args: + input_data: The string data to be hashed. Provide either this or input_file. + input_file: The path to the file to be hashed. Provide either this or input_data. + + Returns: + A dictionary containing the command executed, stdout (the binary digest), + stderr, and the digest itself. The binary digest is returned as a string + using 'latin-1' encoding to preserve all byte values. + """ + if not (input_data is None) ^ (input_file is None): + raise ValueError("Exactly one of 'input_data' or 'input_file' must be provided.") + + # This Perl script reads from a file if a command-line argument is given, + # otherwise it reads from STDIN. It calculates the binary SHA-1 digest. + perl_script = """ + use strict; + use warnings; + use Digest::SHA1; + my $sha1 = Digest::SHA1->new; + if (@ARGV) { + my $file = shift @ARGV; + open my $fh, '<:raw', $file or die "Cannot open '$file': $!"; + $sha1->addfile($fh); + close $fh; + } else { + my $data = do { local $/; <> }; + $sha1->add($data); + } + binmode(STDOUT); + print $sha1->digest; + """ + + cmd = ["perl", "-e", perl_script] + input_bytes = None + + if input_file: + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + cmd.append(str(input_file.resolve())) + else: + # Pass data via stdin to avoid command line length limits and quoting issues + if input_data is not None: + input_bytes = input_data.encode('utf-8') + + try: + # Capture output as bytes because the result is binary + process = subprocess.run( + cmd, + input=input_bytes, + capture_output=True, + check=True + ) + # Use latin-1 to safely decode any byte sequence into a string for JSON compatibility + stdout_str = process.stdout.decode('latin-1') + stderr_str = process.stderr.decode('latin-1') + + return { + "command_executed": " ".join(cmd), + "digest": stdout_str, + "stdout": stdout_str, + "stderr": stderr_str, + } + except FileNotFoundError: + raise RuntimeError("Perl is not installed or not in the system's PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": "Tool execution failed.", + "stdout": e.stdout.decode('latin-1', errors='ignore'), + "stderr": e.stderr.decode('latin-1', errors='ignore'), + "return_code": e.returncode + } + +@mcp.tool() +def sha1_hex( + input_data: Optional[str] = None, + input_file: Optional[Path] = None +) -> Dict[str, Any]: + """ + Calculates the SHA-1 digest of a file or string and returns it in hexadecimal format. + + This function is the same as sha1(), but returns the digest in hexadecimal form. + The length of the returned string will be 40 and it will only contain + characters from the set: '0'..'9' and 'a'..'f'. + + Args: + input_data: The string data to be hashed. Provide either this or input_file. + input_file: The path to the file to be hashed. Provide either this or input_data. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the + hexadecimal digest. + """ + if not (input_data is None) ^ (input_file is None): + raise ValueError("Exactly one of 'input_data' or 'input_file' must be provided.") + + # This Perl script reads from a file if a command-line argument is given, + # otherwise it reads from STDIN. It calculates the hexadecimal SHA-1 digest. + perl_script = """ + use strict; + use warnings; + use Digest::SHA1; + my $sha1 = Digest::SHA1->new; + if (@ARGV) { + my $file = shift @ARGV; + open my $fh, '<:raw', $file or die "Cannot open '$file': $!"; + $sha1->addfile($fh); + close $fh; + } else { + my $data = do { local $/; <> }; + $sha1->add($data); + } + print $sha1->hexdigest; + """ + + cmd = ["perl", "-e", perl_script] + input_bytes = None + + if input_file: + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + cmd.append(str(input_file.resolve())) + else: + if input_data is not None: + input_bytes = input_data.encode('utf-8') + + try: + process = subprocess.run( + cmd, + input=input_bytes, + capture_output=True, + check=True, + text=True + ) + digest = process.stdout.strip() + + return { + "command_executed": " ".join(cmd), + "digest": digest, + "stdout": process.stdout, + "stderr": process.stderr, + } + except FileNotFoundError: + raise RuntimeError("Perl is not installed or not in the system's PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": "Tool execution failed.", + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode + } + +@mcp.tool() +def sha1_base64( + input_data: Optional[str] = None, + input_file: Optional[Path] = None, + pad: bool = False +) -> Dict[str, Any]: + """ + Calculates the SHA-1 digest of a file or string and returns it as a base64 encoded string. + + The length of the returned string will be 27 (unpadded). If padding is enabled, + it will be 28 characters, ending with '='. + + Args: + input_data: The string data to be hashed. Provide either this or input_file. + input_file: The path to the file to be hashed. Provide either this or input_data. + pad: If True, appends '=' to the result for interoperability. Defaults to False. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the + base64 digest. + """ + if not (input_data is None) ^ (input_file is None): + raise ValueError("Exactly one of 'input_data' or 'input_file' must be provided.") + + # This Perl script reads from a file if a command-line argument is given, + # otherwise it reads from STDIN. It calculates the base64 SHA-1 digest. + perl_script = """ + use strict; + use warnings; + use Digest::SHA1; + my $sha1 = Digest::SHA1->new; + if (@ARGV) { + my $file = shift @ARGV; + open my $fh, '<:raw', $file or die "Cannot open '$file': $!"; + $sha1->addfile($fh); + close $fh; + } else { + my $data = do { local $/; <> }; + $sha1->add($data); + } + print $sha1->b64digest; + """ + + cmd = ["perl", "-e", perl_script] + input_bytes = None + + if input_file: + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + cmd.append(str(input_file.resolve())) + else: + if input_data is not None: + input_bytes = input_data.encode('utf-8') + + try: + process = subprocess.run( + cmd, + input=input_bytes, + capture_output=True, + check=True, + text=True + ) + digest = process.stdout.strip() + + if pad and len(digest) == 27: + digest += "=" + + return { + "command_executed": " ".join(cmd), + "digest": digest, + "stdout": process.stdout, + "stderr": process.stderr, + } + except FileNotFoundError: + raise RuntimeError("Perl is not installed or not in the system's PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": "Tool execution failed.", + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-sha1/app/perl-digest-sha1_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-sha1/app/perl-digest-sha1_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..365a044e8c30fcefb89133375ec3aedf70644e52 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-sha1/app/perl-digest-sha1_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-digest-sha1/app/perl-digest-sha1_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_digest_sha1' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-sha1/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-sha1/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-sha1/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-sha1/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-sha1/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..3bafde5f57deaf8763a66b31ad278087fe19eb33 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-sha1/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-digest-sha1: + build: . + image: mcp-perl-digest-sha1:latest + container_name: mcp-perl-digest-sha1 + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-digest-sha1 + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-sha1/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-sha1/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..09898fcb46d09478ec4a4ff1d9a33ee5a025dcb0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-sha1/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-digest-sha1 + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-sha1/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-sha1/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-digest-sha1/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-sort/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-sort/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9814ea7fb2e9be9a39d16250334326aef70a45d5 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-sort/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-file-sort via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-file-sort -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-file-sort_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-file-sort_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-file-sort_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-sort/app/__pycache__/perl-file-sort_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-sort/app/__pycache__/perl-file-sort_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9171bb3587a313899fcb9e630bb7c32ccac007f5 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-sort/app/__pycache__/perl-file-sort_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-sort/app/perl-file-sort_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-sort/app/perl-file-sort_server.py new file mode 100644 index 0000000000000000000000000000000000000000..dcbabe4e5c76b4d77112a481da0406352bb6d795 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-sort/app/perl-file-sort_server.py @@ -0,0 +1,147 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be imported. +def tool(func): + """A dummy decorator to mimic @mcp.tool() for standalone execution.""" + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + return wrapper + +mcp = type('mcp', (), {'tool': tool}) + + +@mcp.tool +def file_sort( + input_files: List[Path], + output_file: Path, + check: bool = False, + merge: bool = False, + unique: bool = False, + reverse: bool = False, + numeric_sort: bool = False, + ignore_case: bool = False, + key: Optional[str] = None, + field_separator: Optional[str] = None, + temporary_directory: Optional[Path] = None, + buffer_size: Optional[str] = None, + batch_size: Optional[int] = None, + parallel: Optional[int] = None, + sort_program: Optional[str] = None, +) -> Dict[str, Any]: + """ + Sorts or merges one or more files using the Perl File::Sort module. + + This tool provides a powerful interface to sort text files, similar to the + GNU sort utility, by leveraging the File::Sort Perl module. It can handle + large files by using temporary disk space. + + Args: + input_files: A list of one or more input files to sort or merge. + output_file: The path to the output file where the sorted result will be stored. + check: Check if the given files are already sorted; don't sort. + merge: Merge already sorted files; do not sort. + unique: With -c, check for strict ordering. Without -c, output only the first of an equal run. + reverse: Reverse the result of comparisons. + numeric_sort: Compare according to string numerical value. + ignore_case: Fold lower case to upper case characters. + key: Sort via a key; see sort(1) documentation for KEYDEF format. + field_separator: Use the specified separator for fields. + temporary_directory: Use a specified directory for temporary files. + buffer_size: Use a specified amount of main memory (e.g., '1G', '256M'). + batch_size: Merge a specified number of files at once. + parallel: Change the number of sorts run concurrently. + sort_program: Use a specified external program for sorting. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not input_files: + raise ValueError("At least one input file must be provided.") + + for file_path in input_files: + if not file_path.is_file(): + raise FileNotFoundError(f"Input file not found: {file_path}") + + if output_file.is_dir(): + raise IsADirectoryError(f"The output path {output_file} is a directory.") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + if temporary_directory and not temporary_directory.is_dir(): + raise NotADirectoryError(f"Temporary directory not found: {temporary_directory}") + + if batch_size is not None and batch_size <= 0: + raise ValueError("batch_size must be a positive integer.") + + if parallel is not None and parallel <= 0: + raise ValueError("parallel must be a positive integer.") + + # --- Command Construction --- + # We use a Perl one-liner to invoke the File::Sort::fsort function. + # The function is designed to parse command-line style arguments from @ARGV. + cmd = ["perl", "-MFile::Sort", "-e", "File::Sort::fsort(@ARGV)"] + + if check: + cmd.append("--check") + if merge: + cmd.append("--merge") + if unique: + cmd.append("--unique") + if reverse: + cmd.append("--reverse") + if numeric_sort: + cmd.append("--numeric-sort") + if ignore_case: + cmd.append("--ignore-case") + if key: + cmd.extend(["--key", key]) + if field_separator: + cmd.extend(["--field-separator", field_separator]) + if temporary_directory: + cmd.extend(["--temporary-directory", str(temporary_directory)]) + if buffer_size: + cmd.extend(["--buffer-size", buffer_size]) + if batch_size: + cmd.extend(["--batch-size", str(batch_size)]) + if parallel: + cmd.extend(["--parallel", str(parallel)]) + if sort_program: + cmd.extend(["--sort-program", sort_program]) + + # Add input and output files to the command + cmd.extend([str(p) for p in input_files]) + cmd.extend(["--output", str(output_file)]) + + command_executed = " ".join(cmd) + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file)] + } + except FileNotFoundError: + # This error occurs if 'perl' is not in the system's PATH + raise RuntimeError("Perl executable not found. Please ensure Perl is installed and in your PATH.") + except subprocess.CalledProcessError as e: + # This error occurs if the Perl script returns a non-zero exit code + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"File::Sort execution failed with exit code {e.returncode}", + "output_files": [] + } diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-sort/app/perl-file-sort_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-sort/app/perl-file-sort_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..61bb82cb6a68234501d25ad43d42612196633945 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-sort/app/perl-file-sort_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-file-sort/app/perl-file-sort_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_file_sort' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-sort/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-sort/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-sort/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-sort/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-sort/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..3a0bf86562c078a368cb53e9f10c93338ad7bbf0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-sort/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-file-sort: + build: . + image: mcp-perl-file-sort:latest + container_name: mcp-perl-file-sort + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-file-sort + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-sort/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-sort/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2c892091202b26e73d8c5cf80c6e2b96a840901b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-sort/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-file-sort + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-sort/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-sort/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-sort/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-which/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-which/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..bda809908ef2253ea8b8387b19c1100f8ef31f90 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-which/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-file-which via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-file-which -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-file-which_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-file-which_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-file-which_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-which/app/__pycache__/perl-file-which_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-which/app/__pycache__/perl-file-which_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08b7cd615316a7ee7ee2f725fcfcaba6f3a4f6c0 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-which/app/__pycache__/perl-file-which_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-which/app/perl-file-which_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-which/app/perl-file-which_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8db4d92968291682e10c7cae230581f096e17eba --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-which/app/perl-file-which_server.py @@ -0,0 +1,165 @@ +import subprocess +import shlex +from pathlib import Path +from typing import List, Optional, Dict, Any + +# Note: mcp is not imported as per instructions. + +def _execute_perl_script( + perl_script_content: str, + program_name: str, + implicit_current_dir: Optional[bool] = None, +) -> Dict[str, Any]: + """ + Helper function to execute a Perl script that uses the File::Which module. + + Args: + perl_script_content: The Perl code snippet to execute. + program_name: The executable name to search for, passed as $ARGV[0] to the Perl script. + implicit_current_dir: If True, sets $File::Which::IMPLICIT_CURRENT_DIR to 1. + If False, sets $File::Which::IMPLICIT_CURRENT_DIR to 0. + If None, the variable is not explicitly set, and File::Which + uses its default platform-specific behavior. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + cmd = ["perl", "-MFile::Which"] + + # Handle IMPLICIT_CURRENT_DIR if specified. + # The BEGIN block ensures the variable is set before File::Which functions are called. + if implicit_current_dir is not None: + implicit_val = "1" if implicit_current_dir else "0" + # Prepend the BEGIN block to the script content + perl_script_content = f"BEGIN {{ local $File::Which::IMPLICIT_CURRENT_DIR = {implicit_val}; }}; {perl_script_content}" + + cmd.extend(["-e", perl_script_content, "--", program_name]) + + # Construct the command string for logging, ensuring proper quoting + command_executed = " ".join(shlex.quote(arg) for arg in cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, # Decode stdout/stderr as text + check=True, # Raise CalledProcessError for non-zero exit codes + ) + stdout = result.stdout.strip() + stderr = result.stderr.strip() + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [], # File::Which does not produce output files + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout.strip(), + "stderr": e.stderr.strip(), + "error": f"Perl command failed with exit code {e.returncode}. " + f"Command: {command_executed}", + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and in your system's PATH.", + "error": "Perl executable not found.", + "output_files": [], + } + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_file_which' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def perl_which( + program_name: str, + implicit_current_dir: Optional[bool] = None, +) -> Dict[str, Any]: + """ + Finds the full or relative path to the first executable program on the system + using Perl's File::Which module. + + This function mimics the behavior of the standard 'which' utility by searching + the directories specified in the user's PATH environment variable. It returns + only the first match found. + + Args: + program_name: The name of the executable program to search for (e.g., 'perl', 'ls', 'python'). + This parameter is required. + implicit_current_dir: Controls whether the current directory is implicitly included in the search path. + - If True, the current directory is searched even if not explicitly in PATH. + - If False, the current directory is NOT searched unless explicitly in PATH. + - If None (default), File::Which uses its default platform-specific behavior + for searching the current directory (e.g., often True on Windows for older shells, + False on Unix-like systems). + + Returns: + A dictionary containing: + - "command_executed": The exact command string executed. + - "stdout": The path to the first found executable, or an empty string if not found. + - "stderr": Any error messages or warnings from the Perl execution. + - "output_files": An empty list, as this tool does not generate files. + - "error": An error message if the command failed or 'perl' was not found. + + Raises: + ValueError: If `program_name` is an empty string. + """ + if not program_name: + raise ValueError("program_name cannot be empty.") + + # Perl script to call which() in scalar context and print the result if defined + perl_script_content = "my $path = which($ARGV[0]); print $path if defined $path;" + + return _execute_perl_script(perl_script_content, program_name, implicit_current_dir) + + +@mcp.tool() +def perl_where( + program_name: str, + implicit_current_dir: Optional[bool] = None, +) -> Dict[str, Any]: + """ + Finds all full or relative paths to executable programs on the system + using Perl's File::Which module. + + This function mimics the behavior of 'which -a' or 'where' commands, + returning all matches found in the user's PATH environment variable. + + Args: + program_name: The name of the executable program to search for (e.g., 'perl', 'ls', 'python'). + This parameter is required. + implicit_current_dir: Controls whether the current directory is implicitly included in the search path. + - If True, the current directory is searched even if not explicitly in PATH. + - If False, the current directory is NOT searched unless explicitly in PATH. + - If None (default), File::Which uses its default platform-specific behavior + for searching the current directory (e.g., often True on Windows for older shells, + False on Unix-like systems). + + Returns: + A dictionary containing: + - "command_executed": The exact command string executed. + - "stdout": Newline-separated paths to all found executables, or an empty string if none are found. + - "stderr": Any error messages or warnings from the Perl execution. + - "output_files": An empty list, as this tool does not generate files. + - "error": An error message if the command failed or 'perl' was not found. + + Raises: + ValueError: If `program_name` is an empty string. + """ + if not program_name: + raise ValueError("program_name cannot be empty.") + + # Perl script to call where() in list context and print each result on a new line + perl_script_content = "my @paths = where($ARGV[0]); print join(\"\\n\", @paths);" + + return _execute_perl_script(perl_script_content, program_name, implicit_current_dir) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-which/app/perl-file-which_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-which/app/perl-file-which_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..232e91efff7cbd12cc820914d427b17a1afeb676 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-which/app/perl-file-which_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-file-which/app/perl-file-which_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_file_which' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-which/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-which/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-which/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-which/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-which/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..43a21e5e7f7b28799b835beae9f78e5f1b8e974c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-which/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-file-which: + build: . + image: mcp-perl-file-which:latest + container_name: mcp-perl-file-which + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-file-which + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-which/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-which/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d15ab30e812c932b4ae3ee4568067475725b70e5 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-which/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-file-which + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-which/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-which/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-file-which/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-html-formatter/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-html-formatter/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..75edbc5feff5bd62b8f13bd2a0314db8747d7410 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-html-formatter/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-html-formatter via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-html-formatter -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-html-formatter_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-html-formatter_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-html-formatter_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-html-formatter/app/__pycache__/perl-html-formatter_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-html-formatter/app/__pycache__/perl-html-formatter_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f766e8fcdf15ea8886495d0f008dd05efc0bc58c Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-html-formatter/app/__pycache__/perl-html-formatter_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-html-formatter/app/perl-html-formatter_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-html-formatter/app/perl-html-formatter_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b27ed003e6c581dd18b68818a95a13e70c355da8 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-html-formatter/app/perl-html-formatter_server.py @@ -0,0 +1,215 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# In a real MCP environment, this would be imported. +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def perl( + programfile: Optional[Path] = None, + arguments: Optional[List[str]] = None, + execute_program: Optional[List[str]] = None, + execute_program_features: Optional[List[str]] = None, + check_syntax_only: bool = False, + print_version: bool = False, + print_config: Optional[str] = None, + record_separator: Optional[str] = None, + autosplit: bool = False, + split_pattern: Optional[str] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + line_ending_processing: Optional[str] = None, + in_place_edit: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + use_module: Optional[List[str]] = None, + no_module: Optional[List[str]] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + disable_all_warnings: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + unicode_features: Optional[str] = None, + run_under_debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + no_sitecustomize: bool = False, + parse_switches: bool = False, + search_path: bool = False, + dump_core: bool = False, + unsafe_operations: bool = False, + ignore_text_before_shebang: Optional[Path] = None, +) -> dict: + """ + Executes the Perl interpreter. This tool can run Perl scripts that may utilize + modules like HTML::Formatter, which is provided by the perl-html-formatter package. + + Args: + programfile: The Perl script file to execute. + arguments: A list of arguments to pass to the programfile. + execute_program: One or more lines of a program to execute directly from the command line. + execute_program_features: Like -e, but enables all optional features. + check_syntax_only: Checks syntax only, running BEGIN and CHECK blocks. Corresponds to -c. + print_version: Prints the version, patchlevel, and license of Perl. Corresponds to -v. + print_config: Prints configuration summary or a single Config.pm variable. Corresponds to -V[:variable]. + record_separator: Specifies the record separator character (octal or literal). Corresponds to -0. + autosplit: Enables autosplit mode with -n or -p, splitting $_ into @F. Corresponds to -a. + split_pattern: Specifies the split() pattern for the -a switch. Corresponds to -F. + loop_around_program: Assumes a "while (<>) { ... }" loop around the program. Corresponds to -n. + loop_and_print: Assumes a loop like -n but also prints the line. Corresponds to -p. + line_ending_processing: Enables line ending processing and specifies the terminator. Corresponds to -l. + in_place_edit: Edits files in place, creating a backup if an extension is supplied. Corresponds to -i. + include_directories: Specifies directories to add to @INC. Corresponds to -I. + use_module: Executes "use module..." before the program. Corresponds to -M. + no_module: Executes "no module..." before the program. Corresponds to -m. + enable_warnings: Enables many useful warnings. Corresponds to -w. + enable_all_warnings: Enables all warnings. Corresponds to -W. + disable_all_warnings: Disables all warnings. Corresponds to -X. + tainting_warnings: Enables tainting warnings. Corresponds to -t. + tainting_checks: Enables tainting checks. Corresponds to -T. + unicode_features: Enables listed Unicode features. Corresponds to -C. + run_under_debugger: Runs the program under a specified debugger. Corresponds to -d. + debugging_flags: Sets debugging flags. Corresponds to -D. + no_sitecustomize: Prevents running $sitelib/sitecustomize.pl at startup. Corresponds to -f. + parse_switches: Enables rudimentary parsing for switches after the programfile. Corresponds to -s. + search_path: Looks for the programfile using the PATH environment variable. Corresponds to -S. + dump_core: Dumps core after parsing the program. Corresponds to -u. + unsafe_operations: Allows unsafe operations. Corresponds to -U. + ignore_text_before_shebang: Ignores text before #!perl line, optionally changing to a directory. Corresponds to -x. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # --- Input Validation --- + if not any([programfile, execute_program, execute_program_features, print_version, print_config is not None]): + raise ValueError("You must specify a program to run via 'programfile', 'execute_program', or 'execute_program_features', or an action like 'print_version' or 'print_config'.") + + if programfile and not programfile.is_file(): + raise FileNotFoundError(f"The specified program file does not exist: {programfile}") + + if include_directories: + for directory in include_directories: + if not directory.is_dir(): + raise NotADirectoryError(f"The include directory does not exist: {directory}") + + # --- Command Construction --- + cmd = ["perl"] + + if record_separator is not None: + cmd.append(f"-0{record_separator}") + if autosplit: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if run_under_debugger is not None: + cmd.append(f"-d:{run_under_debugger}" if run_under_debugger else "-d") + if debugging_flags is not None: + cmd.append(f"-D{debugging_flags}") + if execute_program: + for prog_line in execute_program: + cmd.extend(["-e", prog_line]) + if execute_program_features: + for prog_line in execute_program_features: + cmd.extend(["-E", prog_line]) + if no_sitecustomize: + cmd.append("-f") + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + if in_place_edit is not None: + cmd.append(f"-i{in_place_edit}") + if include_directories: + for directory in include_directories: + cmd.extend(["-I", str(directory)]) + if line_ending_processing is not None: + cmd.append(f"-l{line_ending_processing}") + if use_module: + for mod in use_module: + cmd.extend(["-M", mod]) + if no_module: + for mod in no_module: + cmd.extend(["-m", mod]) + if loop_around_program: + cmd.append("-n") + if loop_and_print: + cmd.append("-p") + if parse_switches: + cmd.append("-s") + if search_path: + cmd.append("-S") + if tainting_warnings: + cmd.append("-t") + if tainting_checks: + cmd.append("-T") + if dump_core: + cmd.append("-u") + if unsafe_operations: + cmd.append("-U") + if print_version: + cmd.append("-v") + if print_config is not None: + cmd.append(f"-V:{print_config}" if print_config else "-V") + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if ignore_text_before_shebang is not None: + cmd.append(f"-x{str(ignore_text_before_shebang)}" if ignore_text_before_shebang.name else "-x") + if disable_all_warnings: + cmd.append("-X") + + if programfile: + cmd.append(str(programfile)) + + if arguments: + cmd.extend(arguments) + + # --- Identify Output Files --- + output_files_list = [] + if in_place_edit is not None and arguments: + # When using in-place edit (-i), the files listed in arguments are modified. + # We'll treat any argument that is an existing file as an output file. + for arg in arguments: + try: + p = Path(arg) + if p.is_file(): + output_files_list.append(str(p.resolve())) + except (TypeError, ValueError): + # Argument is not a valid path, ignore it. + pass + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + stdout = result.stdout + stderr = result.stderr + except FileNotFoundError: + # This error is raised if the 'perl' command is not found. + raise RuntimeError("Perl executable not found. Please ensure Perl is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + # This error is raised for non-zero exit codes. + return { + "error": f"Perl execution failed with return code {e.returncode}.", + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + } + + # --- Structured Result Return --- + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files_list + } \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-html-formatter/app/perl-html-formatter_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-html-formatter/app/perl-html-formatter_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..952a6791d1dc34648079a534b81c2c06ff32cdd8 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-html-formatter/app/perl-html-formatter_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-html-formatter/app/perl-html-formatter_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_html_formatter' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-html-formatter/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-html-formatter/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-html-formatter/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-html-formatter/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-html-formatter/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..daa22304a23dd01b3087bd2ee6fa9c2cb22f1512 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-html-formatter/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-html-formatter: + build: . + image: mcp-perl-html-formatter:latest + container_name: mcp-perl-html-formatter + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-html-formatter + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-html-formatter/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-html-formatter/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7209a1152f51da34009009ac349755c0787607ef --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-html-formatter/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-html-formatter + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-html-formatter/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-html-formatter/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-html-formatter/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-compress/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-compress/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d8711dd8bd631915008f7a7fa77f05f19914ce98 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-compress/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-io-compress via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-io-compress -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-io-compress_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-io-compress_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-io-compress_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-compress/app/__pycache__/perl-io-compress_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-compress/app/__pycache__/perl-io-compress_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bc76462755a8c976cbe97128e07052a0d9b8b070 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-compress/app/__pycache__/perl-io-compress_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-compress/app/perl-io-compress_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-compress/app/perl-io-compress_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8163c5e73182313ff7b9cd2e757b03899ecf7332 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-compress/app/perl-io-compress_server.py @@ -0,0 +1,233 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Dict, Union + +# This is a placeholder for the actual decorator. +# In a real MCP environment, you would use: +# from mcp import tool as mcp_tool +def mcp_tool_placeholder(): + def decorator(f): + return f + return decorator + +mcp = type("MCP", (), {"tool": mcp_tool_placeholder}) + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_io_compress' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_perl( + programfile: Optional[Path] = None, + arguments: Optional[List[str]] = None, + program: Optional[str] = None, + program_e_features: Optional[str] = None, + check_syntax_only: bool = False, + print_version: bool = False, + print_config: Optional[str] = None, + record_separator: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + in_place_edit: Optional[str] = None, + include_dirs: Optional[List[Path]] = None, + line_ending_processing: Optional[str] = None, + use_module: Optional[List[str]] = None, + no_module: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + parse_switches: bool = False, + search_path: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core: bool = False, + unsafe_operations: bool = False, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + disable_all_warnings: bool = False, + ignore_text_before_hashbang: Optional[Path] = None, +) -> Dict[str, Union[str, List[str]]]: + """ + Executes a Perl program using an environment that includes the IO::Compress library. + + This tool is a wrapper for the Perl interpreter. It allows you to run Perl scripts + or one-liners, leveraging the installed Perl modules like IO::Compress for tasks + such as file compression and decompression. + + Args: + programfile: Path to the Perl program file to execute. + arguments: A list of arguments to pass to the program file. + program: A one-liner program string to execute (equivalent to -e). + program_e_features: Like 'program', but enables all optional features (-E). + check_syntax_only: Check syntax only; runs BEGIN and CHECK blocks (-c). + print_version: Print Perl version, patchlevel, and license (-v). + print_config: Print configuration summary or a single variable (-V[:variable]). + record_separator: Specify record separator, e.g., '0777' for slurp mode (-0). + autosplit: Enable autosplit mode with -n or -p (splits $_ into @F) (-a). + unicode_features: Enable listed Unicode features (-C). + debugger: Run the program under the specified debugger (-d[:debugger]). + debugging_flags: Set debugging flags (-D). + no_sitecustomize: Don't run $sitelib/sitecustomize.pl at startup (-f). + split_pattern: Specify the split() pattern for the -a switch (-F). + in_place_edit: Edit files in place. Provide an extension for backup (-i). + include_dirs: List of directories to add to @INC (-I). + line_ending_processing: Enable line ending processing (-l). + use_module: Execute 'use module...' before the program (-M). + no_module: Execute 'no module...' before the program (-m). + loop_around_program: Assume 'while (<>) { ... }' loop around the program (-n). + loop_and_print: Like -n, but also prints the line (-p). + parse_switches: Enable rudimentary parsing for switches after programfile (-s). + search_path: Look for programfile using the PATH environment variable (-S). + tainting_warnings: Enable tainting warnings (-t). + tainting_checks: Enable tainting checks (-T). + dump_core: Dump core after parsing the program (-u). + unsafe_operations: Allow unsafe operations (-U). + enable_warnings: Enable many useful warnings (-w). + enable_all_warnings: Enable all warnings (-W). + disable_all_warnings: Disable all warnings (-X). + ignore_text_before_hashbang: Ignore text before #!perl line and optionally cd (-x). + + Returns: + A dictionary containing the executed command, stdout, stderr, and output files. + """ + # --- Input Validation --- + program_sources = [programfile, program, program_e_features] + if sum(p is not None for p in program_sources) > 1: + raise ValueError("Only one of 'programfile', 'program', or 'program_e_features' can be specified.") + + is_action = any([ + programfile, + program, + program_e_features, + check_syntax_only, + print_version, + print_config is not None + ]) + if not is_action: + raise ValueError("No action specified. Provide a script, or set an action like 'check_syntax_only' or 'print_version'.") + + warning_flags = [enable_warnings, enable_all_warnings, disable_all_warnings] + if sum(warning_flags) > 1: + raise ValueError("The warning flags -w, -W, and -X are mutually exclusive.") + + if programfile and not programfile.is_file(): + raise FileNotFoundError(f"Program file not found: {programfile}") + + if include_dirs: + for directory in include_dirs: + if not directory.is_dir(): + raise NotADirectoryError(f"Include directory not found: {directory}") + + # --- Command Construction --- + cmd = ["perl"] + + if record_separator is not None: + cmd.append(f"-0{record_separator}") + if autosplit: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if debugger is not None: + cmd.append(f"-d{debugger}") + if debugging_flags is not None: + cmd.append(f"-D{debugging_flags}") + if program: + cmd.extend(["-e", program]) + if program_e_features: + cmd.extend(["-E", program_e_features]) + if no_sitecustomize: + cmd.append("-f") + if split_pattern is not None: + cmd.extend(["-F", split_pattern]) + if in_place_edit is not None: + cmd.append(f"-i{in_place_edit}") + if include_dirs: + for directory in include_dirs: + cmd.extend(["-I", str(directory)]) + if line_ending_processing is not None: + cmd.append(f"-l{line_ending_processing}") + if use_module: + for mod in use_module: + cmd.extend(["-M", mod]) + if no_module: + for mod in no_module: + cmd.extend(["-m", mod]) + if loop_around_program: + cmd.append("-n") + if loop_and_print: + cmd.append("-p") + if parse_switches: + cmd.append("-s") + if search_path: + cmd.append("-S") + if tainting_warnings: + cmd.append("-t") + if tainting_checks: + cmd.append("-T") + if dump_core: + cmd.append("-u") + if unsafe_operations: + cmd.append("-U") + if print_version: + cmd.append("-v") + if print_config is not None: + cmd.append(f"-V{print_config}") + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if ignore_text_before_hashbang: + cmd.extend(["-x", str(ignore_text_before_hashbang)]) + if disable_all_warnings: + cmd.append("-X") + + if programfile: + cmd.append(str(programfile)) + + if arguments: + cmd.extend(arguments) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + stdout = result.stdout + stderr = result.stderr + except FileNotFoundError: + return { + "error": "Perl executable not found. Please ensure it is in your PATH.", + "command_executed": command_executed, + "stdout": "", + "stderr": "", + } + except subprocess.CalledProcessError as e: + return { + "error": "Perl script execution failed.", + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + } + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [] # This tool primarily operates on stdout/stderr + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-compress/app/perl-io-compress_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-compress/app/perl-io-compress_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4f4cd6c7a2a25ebc56c0e5fcc712bbe6808a73dc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-compress/app/perl-io-compress_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-compress/app/perl-io-compress_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_io_compress' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-compress/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-compress/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-compress/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-compress/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-compress/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..71acefbee1b4cd952c256b97fcb42ad88c57a27f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-compress/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-io-compress: + build: . + image: mcp-perl-io-compress:latest + container_name: mcp-perl-io-compress + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-io-compress + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-compress/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-compress/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ec64a2665abe6dae6725c976c0ecf9c8d492fffe --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-compress/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-io-compress + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-compress/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-compress/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-compress/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-tty/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-tty/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..027925733250192911345e302f7353c5f931c04c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-tty/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-io-tty via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-io-tty -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-io-tty_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-io-tty_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-io-tty_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-tty/app/__pycache__/perl-io-tty_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-tty/app/__pycache__/perl-io-tty_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e4793d8f923e20e2fff2c1d934468964da747cdd Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-tty/app/__pycache__/perl-io-tty_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-tty/app/perl-io-tty_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-tty/app/perl-io-tty_server.py new file mode 100644 index 0000000000000000000000000000000000000000..22cee56f208a793c2baec3d444f3fef663523e16 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-tty/app/perl-io-tty_server.py @@ -0,0 +1,205 @@ +import subprocess +import shlex +from pathlib import Path +from typing import Optional, List, Dict, Any + +# This is a placeholder for the mcp.tool decorator. +# In a real MCP environment, you would import it. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_io_tty' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_perl( + programfile: Optional[Path] = None, + arguments: Optional[List[str]] = None, + execute_line: Optional[List[str]] = None, + execute_line_with_features: Optional[List[str]] = None, + record_separator_octal: Optional[str] = None, + autosplit: bool = False, + autosplit_pattern: Optional[str] = None, + assume_while_loop: bool = False, + assume_print_loop: bool = False, + enable_line_ending_processing: Optional[str] = None, + edit_in_place_backup_ext: Optional[str] = None, + add_include_directory: Optional[List[Path]] = None, + use_module: Optional[List[str]] = None, + check_syntax_only: bool = False, + run_under_debugger: Optional[str] = None, + set_debugging_flags: Optional[str] = None, + no_sitecustomize: bool = False, + enable_switch_parsing: bool = False, + search_program_in_path: bool = False, + enable_taint_warnings: bool = False, + enable_taint_checks: bool = False, + dump_core_after_parse: bool = False, + allow_unsafe_ops: bool = False, + print_version_info: bool = False, + print_config_variable: Optional[str] = None, + enable_many_warnings: bool = False, + enable_all_warnings_W: bool = False, + disable_all_warnings_X: bool = False, + extract_script_from_message: bool = False, + extract_script_cd_dir: Optional[Path] = None, + enable_unicode_features: Optional[str] = None, +) -> Dict[str, Any]: + """ + Executes a script using the Perl interpreter. + + This tool wraps the `perl` command-line interpreter. The original request was for `perl-io-tty`, + which is a Perl module and does not have its own command-line interface. This tool therefore + exposes the functionality of the `perl` executable itself, allowing for the execution of + Perl scripts and one-liners. + """ + # --- Input Validation --- + if programfile and (execute_line or execute_line_with_features): + raise ValueError("Cannot specify 'programfile' with 'execute_line' or 'execute_line_with_features'.") + if not programfile and not execute_line and not execute_line_with_features and not print_version_info and print_config_variable is None: + raise ValueError("Either 'programfile', 'execute_line', 'execute_line_with_features', 'print_version_info', or 'print_config_variable' must be provided.") + + if programfile and not programfile.is_file(): + raise FileNotFoundError(f"Program file not found: {programfile}") + + if add_include_directory: + for directory in add_include_directory: + if not directory.is_dir(): + raise FileNotFoundError(f"Include directory not found: {directory}") + + if autosplit_pattern and not (assume_while_loop or assume_print_loop): + raise ValueError("'autosplit_pattern' (-F) requires 'assume_while_loop' (-n) or 'assume_print_loop' (-p).") + + if extract_script_cd_dir and not extract_script_from_message: + raise ValueError("'extract_script_cd_dir' can only be used when 'extract_script_from_message' is True.") + + # --- Command Construction --- + cmd = ["perl"] + + if record_separator_octal is not None: + cmd.append(f"-0{record_separator_octal}") + if autosplit: + cmd.append("-a") + if enable_unicode_features is not None: + cmd.append(f"-C{enable_unicode_features}") + if check_syntax_only: + cmd.append("-c") + if run_under_debugger is not None: + cmd.append(f"-d{run_under_debugger}") + if set_debugging_flags is not None: + cmd.append(f"-D{set_debugging_flags}") + if no_sitecustomize: + cmd.append("-f") + if autosplit_pattern is not None: + cmd.append(f"-F{autosplit_pattern}") + if edit_in_place_backup_ext is not None: + cmd.append(f"-i{edit_in_place_backup_ext}") + if add_include_directory: + for directory in add_include_directory: + cmd.extend(["-I", str(directory)]) + if enable_line_ending_processing is not None: + cmd.append(f"-l{enable_line_ending_processing}") + if use_module: + for mod in use_module: + # Handles -Mmodule, -mmodule, -M-module, etc. + if mod.startswith('m') or mod.startswith('M'): + cmd.append(f"-{mod}") + else: + cmd.append(f"-M{mod}") + # -p overrides -n + if assume_print_loop: + cmd.append("-p") + elif assume_while_loop: + cmd.append("-n") + if enable_switch_parsing: + cmd.append("-s") + if search_program_in_path: + cmd.append("-S") + if enable_taint_warnings: + cmd.append("-t") + if enable_taint_checks: + cmd.append("-T") + if dump_core_after_parse: + cmd.append("-u") + if allow_unsafe_ops: + cmd.append("-U") + if print_version_info: + cmd.append("-v") + if print_config_variable is not None: + cmd.append(f"-V{print_config_variable}") + if enable_many_warnings: + cmd.append("-w") + if enable_all_warnings_W: + cmd.append("-W") + if extract_script_cd_dir: + cmd.extend(["-x", str(extract_script_cd_dir)]) + elif extract_script_from_message: + cmd.append("-x") + if disable_all_warnings_X: + cmd.append("-X") + + if execute_line: + for line in execute_line: + cmd.extend(["-e", line]) + if execute_line_with_features: + for line in execute_line_with_features: + cmd.extend(["-E", line]) + + if programfile: + cmd.append(str(programfile)) + + if arguments: + cmd.append("--") + cmd.extend(arguments) + + # --- Subprocess Execution --- + command_executed = shlex.join(cmd) + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'perl' command not found. Is Perl installed and in the system's PATH?", + "return_code": 1, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + "output_files": [] + } + + # --- Output Handling --- + output_files = [] + if edit_in_place_backup_ext is not None and edit_in_place_backup_ext != "" and arguments: + for arg_file in arguments: + p = Path(arg_file) + if p.is_file(): + backup_file = p.with_name(f"{p.name}{edit_in_place_backup_ext}") + output_files.append(str(backup_file)) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "return_code": result.returncode, + "output_files": output_files + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-tty/app/perl-io-tty_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-tty/app/perl-io-tty_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..caba62ac6c2a73769e4cc9908c6b748c40542678 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-tty/app/perl-io-tty_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-io-tty/app/perl-io-tty_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_io_tty' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-tty/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-tty/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-tty/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-tty/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-tty/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..2b879424d36a9b888c2e5e67b813945cb8252b14 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-tty/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-io-tty: + build: . + image: mcp-perl-io-tty:latest + container_name: mcp-perl-io-tty + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-io-tty + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-tty/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-tty/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3906ae0af6b53a0df5ee6307274426d6c382ac19 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-tty/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-io-tty + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-tty/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-tty/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-io-tty/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-locale-maketext-simple/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-locale-maketext-simple/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..bda10ebc68b470f7fd03e78bb81d45d2d9caf575 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-locale-maketext-simple/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-locale-maketext-simple via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-locale-maketext-simple -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-locale-maketext-simple_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-locale-maketext-simple_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-locale-maketext-simple_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-locale-maketext-simple/app/__pycache__/perl-locale-maketext-simple_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-locale-maketext-simple/app/__pycache__/perl-locale-maketext-simple_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..08aac399fdecc0b4969f0d68c8650c31935883d8 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-locale-maketext-simple/app/__pycache__/perl-locale-maketext-simple_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-locale-maketext-simple/app/perl-locale-maketext-simple_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-locale-maketext-simple/app/perl-locale-maketext-simple_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6e4cd04d21c61470609b47b5b095125e208b1b58 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-locale-maketext-simple/app/perl-locale-maketext-simple_server.py @@ -0,0 +1,174 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +# In a real MCP environment, the @mcp.tool decorator is provided by the framework. +# No import is needed in the final script as per the instructions. + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_locale_maketext_simple' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def perl_interpreter( + programfile: Optional[Path] = None, + arguments: Optional[List[str]] = None, + execute_program: Optional[List[str]] = None, + execute_program_with_features: Optional[List[str]] = None, + check_syntax: bool = False, + print_version: bool = False, + print_config_variable: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + disable_all_warnings: bool = False, + include_dirs: Optional[List[Path]] = None, + use_module: Optional[List[str]] = None, + no_module: Optional[List[str]] = None, + use_module_no_import: Optional[List[str]] = None, + no_module_no_import: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + autosplit: bool = False, + split_pattern: Optional[str] = None, + in_place_edit_extension: Optional[str] = None, + record_separator: Optional[str] = None, + line_ending_processing: Optional[str] = None, + taint_checks: bool = False, + taint_warnings: bool = False, + allow_unsafe_operations: bool = False, + search_path_for_program: bool = False, + enable_switch_parsing: bool = False, + unicode_features: Optional[str] = None, + debugger: Optional[str] = None, + debug_flags: Optional[str] = None, + no_sitecustomize: bool = False, + dump_core: bool = False, + extract_script_and_cd: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Provides a wrapper for the `perl` command-line interpreter. + + This tool can execute Perl scripts from files or strings and supports the full + range of standard Perl command-line switches. It is the underlying engine for + many Perl-based bioinformatics tools. + """ + # --- Input Validation --- + if not any([programfile, execute_program, execute_program_with_features, print_version, print_config_variable is not None]): + raise ValueError("At least one primary action is required: specify a 'programfile', 'execute_program', 'execute_program_with_features', 'print_version', or 'print_config_variable'.") + + if programfile and not programfile.is_file(): + raise FileNotFoundError(f"The specified program file does not exist: {programfile}") + + if include_dirs: + for directory in include_dirs: + if not directory.is_dir(): + raise NotADirectoryError(f"The specified include directory does not exist: {directory}") + + if extract_script_and_cd is not None: + if not extract_script_and_cd.is_dir(): + raise NotADirectoryError(f"The directory specified for the -x option does not exist: {extract_script_and_cd}") + + # --- Command Construction --- + cmd = ["perl"] + + # Flags with optional values + if record_separator is not None: + cmd.append(f"-0{record_separator}") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if debugger is not None: + cmd.append(f"-d{debugger}") + if debug_flags is not None: + cmd.append(f"-D{debug_flags}") + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + if in_place_edit_extension is not None: + cmd.append(f"-i{in_place_edit_extension}") + if line_ending_processing is not None: + cmd.append(f"-l{line_ending_processing}") + if print_config_variable is not None: + cmd.append(f"-V{print_config_variable}") + if extract_script_and_cd is not None: + cmd.extend(["-x", str(extract_script_and_cd)]) + + # Boolean flags + if autosplit: cmd.append("-a") + if check_syntax: cmd.append("-c") + if no_sitecustomize: cmd.append("-f") + if loop_around_program: cmd.append("-n") + if loop_and_print: cmd.append("-p") + if enable_switch_parsing: cmd.append("-s") + if search_path_for_program: cmd.append("-S") + if taint_warnings: cmd.append("-t") + if taint_checks: cmd.append("-T") + if dump_core: cmd.append("-u") + if allow_unsafe_operations: cmd.append("-U") + if print_version: cmd.append("-v") + if enable_warnings: cmd.append("-w") + if enable_all_warnings: cmd.append("-W") + if disable_all_warnings: cmd.append("-X") + + # List-based arguments + if include_dirs: + for directory in include_dirs: + cmd.extend(["-I", str(directory)]) + if use_module: + for mod in use_module: + cmd.append(f"-M{mod}") + if no_module: + for mod in no_module: + cmd.append(f"-m{mod}") # Corrected from -M- to -m as per some perl versions, though -M- is also valid. Sticking to distinct params. + if use_module_no_import: + for mod in use_module_no_import: + cmd.append(f"-m{mod}") + if no_module_no_import: + for mod in no_module_no_import: + cmd.append(f"-M-{mod}") # Corrected from -m- to -M- + if execute_program: + for prog_line in execute_program: + cmd.extend(["-e", prog_line]) + if execute_program_with_features: + for prog_line in execute_program_with_features: + cmd.extend(["-E", prog_line]) + + # Positional arguments + if programfile: + cmd.append(str(programfile)) + if arguments: + cmd.extend(arguments) + + # --- Subprocess Execution --- + command_string = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": command_string, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] # Output files are script-dependent and not predictable + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_string, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl execution failed with return code {e.returncode}", + "return_code": e.returncode + } + except FileNotFoundError: + return { + "command_executed": command_string, + "stdout": "", + "stderr": "The 'perl' executable was not found in the system's PATH.", + "error": "Executable not found", + "return_code": -1 + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-locale-maketext-simple/app/perl-locale-maketext-simple_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-locale-maketext-simple/app/perl-locale-maketext-simple_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b2f229c9a83f67444653cf0d0fb3f44bf85b4638 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-locale-maketext-simple/app/perl-locale-maketext-simple_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-locale-maketext-simple/app/perl-locale-maketext-simple_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_locale_maketext_simple' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-locale-maketext-simple/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-locale-maketext-simple/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-locale-maketext-simple/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-locale-maketext-simple/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-locale-maketext-simple/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..897f1f59ceec4eada3ead655cfd106cf72e75719 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-locale-maketext-simple/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-locale-maketext-simple: + build: . + image: mcp-perl-locale-maketext-simple:latest + container_name: mcp-perl-locale-maketext-simple + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-locale-maketext-simple + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-derivative/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-derivative/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..b42e8da9bd37d1ef99fcaa0933f749e78b4497fc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-derivative/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-math-derivative via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-math-derivative -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-math-derivative_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-math-derivative_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-math-derivative_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-derivative/app/__pycache__/perl-math-derivative_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-derivative/app/__pycache__/perl-math-derivative_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..53e873107d3dba9cb2bb820a5926b3da0a145cdf Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-derivative/app/__pycache__/perl-math-derivative_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-derivative/app/perl-math-derivative_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-derivative/app/perl-math-derivative_server.py new file mode 100644 index 0000000000000000000000000000000000000000..da55b5187135a069d31eb2c29078964e5cfb7262 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-derivative/app/perl-math-derivative_server.py @@ -0,0 +1,175 @@ +import subprocess +import json +from typing import List, Optional +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_math_derivative' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def math_derivative_1st_order( + x_values: List[float], + y_values: List[float], +): + """ + Performs 1st order numeric differentiation using the Perl Math::Derivative module. + + Args: + x_values: List of independent variable values (must be sorted). + y_values: List of dependent variable values (must be same length as x_values). + """ + if len(x_values) != len(y_values): + return {"error": "x_values and y_values must have the same length."} + if len(x_values) < 2: + return {"error": "At least two points are required for 1st order differentiation."} + + # Prepare data for Perl + x_str = ",".join(map(str, x_values)) + y_str = ",".join(map(str, y_values)) + + # Construct Perl command + # We use a one-liner to import the module and execute the function + perl_script = ( + f"use Math::Derivative; " + f"my @x = split(',', '{x_str}'); " + f"my @y = split(',', '{y_str}'); " + f"my @d = Derivative1(\\@x, \\@y); " + f"print join(',', @d);" + ) + + cmd = ["perl", "-MMath::Derivative", "-e", perl_script] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + derivatives = [float(v) for v in result.stdout.strip().split(",") if v] + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "derivatives": derivatives + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def math_derivative_2nd_order( + x_values: List[float], + y_values: List[float], + yp1: float = 1e30, + ypn: float = 1e30, +): + """ + Performs 2nd order numeric differentiation using the Perl Math::Derivative module. + This is typically used for cubic spline interpolation. + + Args: + x_values: List of independent variable values (must be sorted). + y_values: List of dependent variable values (must be same length as x_values). + yp1: The first derivative at the first point. Use 1e30 for a 'natural' spline. + ypn: The first derivative at the last point. Use 1e30 for a 'natural' spline. + """ + if len(x_values) != len(y_values): + return {"error": "x_values and y_values must have the same length."} + if len(x_values) < 3: + return {"error": "At least three points are required for 2nd order differentiation."} + + # Prepare data for Perl + x_str = ",".join(map(str, x_values)) + y_str = ",".join(map(str, y_values)) + + # Construct Perl command + perl_script = ( + f"use Math::Derivative; " + f"my @x = split(',', '{x_str}'); " + f"my @y = split(',', '{y_str}'); " + f"my @d = Derivative2(\\@x, \\@y, {yp1}, {ypn}); " + f"print join(',', @d);" + ) + + cmd = ["perl", "-MMath::Derivative", "-e", perl_script] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + derivatives = [float(v) for v in result.stdout.strip().split(",") if v] + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "derivatives": derivatives + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def math_derivative_from_file( + input_file: str, + order: int = 1, + column_x: int = 0, + column_y: int = 1, + has_header: bool = False, + yp1: float = 1e30, + ypn: float = 1e30, +): + """ + Reads numeric data from a file and calculates the 1st or 2nd order derivatives. + + Args: + input_file: Path to the input text file (space, tab, or comma delimited). + order: Order of differentiation (1 or 2). + column_x: Index of the column containing X values (0-based). + column_y: Index of the column containing Y values (0-based). + has_header: Whether the file has a header row to skip. + yp1: (For 2nd order) First derivative at the first point. + ypn: (For 2nd order) First derivative at the last point. + """ + file_path = Path(input_file) + if not file_path.exists(): + return {"error": f"File not found: {input_file}"} + + x_values = [] + y_values = [] + + try: + with open(file_path, 'r') as f: + lines = f.readlines() + if has_header: + lines = lines[1:] + + for line in lines: + if not line.strip(): + continue + # Split by comma, tab, or whitespace + parts = line.replace(',', ' ').split() + if len(parts) > max(column_x, column_y): + x_values.append(float(parts[column_x])) + y_values.append(float(parts[column_y])) + except Exception as e: + return {"error": f"Failed to parse file: {str(e)}"} + + if order == 1: + return math_derivative_1st_order(x_values, y_values) + elif order == 2: + return math_derivative_2nd_order(x_values, y_values, yp1, ypn) + else: + return {"error": "Order must be 1 or 2."} + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-derivative/app/perl-math-derivative_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-derivative/app/perl-math-derivative_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b97b696fdf04b3e494a50b02dd9fe02e94a3fbe1 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-derivative/app/perl-math-derivative_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-math-derivative/app/perl-math-derivative_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_math_derivative' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-derivative/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-derivative/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-derivative/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-derivative/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-derivative/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b9cd06019f4e5d7b84782b58945207fdd3c532f4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-derivative/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-math-derivative: + build: . + image: mcp-perl-math-derivative:latest + container_name: mcp-perl-math-derivative + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-math-derivative + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-derivative/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-derivative/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..59f592c0d5bd2420f6d3f902f90f055d52f99431 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-derivative/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-math-derivative + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-derivative/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-derivative/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-math-derivative/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-params-check/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-params-check/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..10a6cb4c0f30f2e1692b275a7c1c948ef9054973 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-params-check/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-params-check via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-params-check -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-params-check_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-params-check_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-params-check_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-params-check/app/__pycache__/perl-params-check_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-params-check/app/__pycache__/perl-params-check_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e7cbabec16f1915e44dea7093f4a334a7ba9ead4 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-params-check/app/__pycache__/perl-params-check_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-params-check/app/perl-params-check_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-params-check/app/perl-params-check_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0a3f5a477143db0441e5e1cd525614815ac0ed92 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-params-check/app/perl-params-check_server.py @@ -0,0 +1,214 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# This is a mock decorator. In a real MCP environment, this would be provided by the MCP framework. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_params_check' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_perl( + programfile: Optional[Path] = None, + execute_program: Optional[List[str]] = None, + execute_program_extended: Optional[List[str]] = None, + arguments: Optional[List[str]] = None, + check_syntax_only: bool = False, + run_under_debugger: Optional[str] = None, + dump_core: bool = False, + allow_unsafe: bool = False, + no_sitecustomize: bool = False, + search_path: bool = False, + ignore_pre_hashbang_text: Optional[Path] = None, + record_separator: Optional[str] = None, + autosplit: bool = False, + split_pattern: Optional[str] = None, + line_ending_processing: Optional[str] = None, + in_place_edit: Optional[str] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + disable_all_warnings: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + include_directory: Optional[List[Path]] = None, + use_module: Optional[List[str]] = None, + use_module_no_import: Optional[List[str]] = None, + no_module: Optional[List[str]] = None, + no_module_no_import: Optional[List[str]] = None, + print_version: bool = False, + print_config: Optional[str] = None, + unicode_features: Optional[str] = None, + debugging_flags: Optional[str] = None, + parse_switches: bool = False, +) -> dict: + """ + Executes a Perl script or one-liner using the Perl interpreter. + + This tool provides a comprehensive wrapper around the `perl` command-line + interface, allowing for script execution, syntax checking, module loading, + and control over various runtime behaviors like warnings and data handling. + + Args: + programfile: Path to the Perl program file to execute. + execute_program: One or more lines of a program to execute via `-e`. + execute_program_extended: Like `execute_program`, but enables all optional features (`-E`). + arguments: A list of arguments to be passed to the program. + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks). Corresponds to `-c`. + run_under_debugger: Run the program under the specified debugger. Corresponds to `-d[:debugger]`. + dump_core: Dump core after parsing the program. Corresponds to `-u`. + allow_unsafe: Allow unsafe operations. Corresponds to `-U`. + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup. Corresponds to `-f`. + search_path: Look for programfile using the PATH environment variable. Corresponds to `-S`. + ignore_pre_hashbang_text: Ignore text before #!perl line, optionally cd to the directory. Corresponds to `-x[directory]`. + record_separator: Specify record separator (`\\0` if no argument). Corresponds to `-0[octal]`. + autosplit: Enable autosplit mode with `-n` or `-p` (splits $_ into @F). Corresponds to `-a`. + split_pattern: Specify the split() pattern for the `-a` switch. Corresponds to `-F/pattern/`. + line_ending_processing: Enable line ending processing and specify the line terminator. Corresponds to `-l[octal]`. + in_place_edit: Edit <> files in place, making a backup if an extension is supplied. Corresponds to `-i[extension]`. + loop_around_program: Assume "while (<>) { ... }" loop around the program. Corresponds to `-n`. + loop_and_print: Assume a loop like `-n` but also print the line. Corresponds to `-p`. + enable_warnings: Enable many useful warnings. Corresponds to `-w`. + enable_all_warnings: Enable all warnings. Corresponds to `-W`. + disable_all_warnings: Disable all warnings. Corresponds to `-X`. + tainting_warnings: Enable tainting warnings. Corresponds to `-t`. + tainting_checks: Enable tainting checks. Corresponds to `-T`. + include_directory: Specify @INC/#include directories. Corresponds to `-I`. + use_module: Execute "use module..." before the program. Corresponds to `-Mmodule`. + use_module_no_import: Execute "use module ()" before the program. Corresponds to `-mmodule`. + no_module: Execute "no module..." before the program. Corresponds to `-M-module`. + no_module_no_import: Corresponds to `-m-module`. + print_version: Print version, patchlevel, and license. Corresponds to `-v`. + print_config: Print configuration summary or a single Config.pm variable. Corresponds to `-V[:variable]`. + unicode_features: Enable the listed Unicode features. Corresponds to `-C[number/list]`. + debugging_flags: Set debugging flags. Corresponds to `-D[number/list]`. + parse_switches: Enable rudimentary parsing for switches after programfile. Corresponds to `-s`. + + Returns: + A dictionary containing the executed command, stdout, stderr, and output file paths. + """ + # --- Input Validation --- + program_sources = sum(p is not None for p in [programfile, execute_program, execute_program_extended]) + is_info_only = print_version or (print_config is not None) + + if not is_info_only and program_sources == 0: + raise ValueError("A program must be specified via 'programfile', 'execute_program', or 'execute_program_extended'.") + if program_sources > 1: + raise ValueError("Only one of 'programfile', 'execute_program', or 'execute_program_extended' can be specified.") + + if programfile and not programfile.is_file(): + raise FileNotFoundError(f"Program file not found: {programfile}") + if include_directory: + for d in include_directory: + if not d.is_dir(): + raise NotADirectoryError(f"Include directory not found: {d}") + if ignore_pre_hashbang_text and not ignore_pre_hashbang_text.is_dir(): + raise NotADirectoryError(f"Directory for -x option not found: {ignore_pre_hashbang_text}") + + # --- Command Construction --- + cmd = ["perl"] + + # Boolean flags + if autosplit: cmd.append("-a") + if check_syntax_only: cmd.append("-c") + if no_sitecustomize: cmd.append("-f") + if loop_around_program: cmd.append("-n") + if loop_and_print: cmd.append("-p") + if parse_switches: cmd.append("-s") + if search_path: cmd.append("-S") + if tainting_warnings: cmd.append("-t") + if tainting_checks: cmd.append("-T") + if dump_core: cmd.append("-u") + if allow_unsafe: cmd.append("-U") + if print_version: cmd.append("-v") + if enable_warnings: cmd.append("-w") + if enable_all_warnings: cmd.append("-W") + if disable_all_warnings: cmd.append("-X") + + # Flags with optional or required values + if record_separator is not None: cmd.append(f"-0{record_separator}") + if unicode_features is not None: cmd.append(f"-C{unicode_features}") + if run_under_debugger is not None: cmd.append(f"-d:{run_under_debugger}" if run_under_debugger else "-d") + if debugging_flags is not None: cmd.append(f"-D{debugging_flags}") + if split_pattern is not None: cmd.append(f"-F{split_pattern}") + if in_place_edit is not None: cmd.append(f"-i{in_place_edit}") + if line_ending_processing is not None: cmd.append(f"-l{line_ending_processing}") + if print_config is not None: cmd.append(f"-V:{print_config}" if print_config else "-V") + if ignore_pre_hashbang_text is not None: cmd.append(f"-x{ignore_pre_hashbang_text}") + elif ignore_pre_hashbang_text == Path('.'): # Special case for -x without directory + cmd.append("-x") + + # List-based flags + if include_directory: + for d in include_directory: + cmd.append(f"-I{d}") + if use_module: + for m in use_module: + cmd.append(f"-M{m}") + if use_module_no_import: + for m in use_module_no_import: + cmd.append(f"-m{m}") + if no_module: + for m in no_module: + cmd.append(f"-M-{m}") + if no_module_no_import: + for m in no_module_no_import: + cmd.append(f"-m-{m}") + if execute_program: + for p in execute_program: + cmd.extend(["-e", p]) + if execute_program_extended: + for p in execute_program_extended: + cmd.extend(["-E", p]) + + # Positional arguments + if programfile: + cmd.append(str(programfile)) + if arguments: + cmd.append("--") + cmd.extend(arguments) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] # Perl interpreter itself doesn't guarantee output files; scripts do. + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl execution failed with return code {e.returncode}", + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and in your PATH.", + "error": "Command not found", + "output_files": [] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-params-check/app/perl-params-check_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-params-check/app/perl-params-check_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4299e3c0e9c3918dcf71e52ab88e32e22ad54c6b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-params-check/app/perl-params-check_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-params-check/app/perl-params-check_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_params_check' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-params-check/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-params-check/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-params-check/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-params-check/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-params-check/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c3c99b2a6953e5e2cfd46dfe5bcedeb1a038f472 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-params-check/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-params-check: + build: . + image: mcp-perl-params-check:latest + container_name: mcp-perl-params-check + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-params-check + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-params-check/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-params-check/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3b3cba7112b3aebe734782ac7771cf639f8e4c05 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-params-check/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-params-check + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-params-check/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-params-check/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-params-check/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-postscript/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-postscript/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1d21cbea4ac5fce8270879b9a71c76034235224b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-postscript/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-postscript via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-postscript -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-postscript_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-postscript_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-postscript_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-postscript/app/__pycache__/perl-postscript_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-postscript/app/__pycache__/perl-postscript_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4d408786abfa63639a0da0d19275269c3b8dfd5f Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-postscript/app/__pycache__/perl-postscript_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-postscript/app/perl-postscript_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-postscript/app/perl-postscript_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c32ec97661596fccf4d0822d4326cd678bfb52f8 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-postscript/app/perl-postscript_server.py @@ -0,0 +1,247 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_postscript' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def perl_postscript_execute( + script_path: Optional[str] = None, + one_liner: Optional[str] = None, + modules: Optional[List[str]] = None, + include_paths: Optional[List[str]] = None, + autosplit: bool = False, + split_pattern: Optional[str] = None, + warnings: bool = True, + all_warnings: bool = False, + taint_check: bool = False, + inplace_extension: Optional[str] = None, + line_ending_processing: bool = False, + assume_loop_n: bool = False, + assume_loop_p: bool = False, + script_args: Optional[List[str]] = None, +): + """ + Execute a Perl script or one-liner using the perl interpreter. + This tool is part of the perl-postscript package, which provides PostScript::TextBlock support. + + Args: + script_path: Path to the Perl script file (.pl) to execute. + one_liner: A string containing Perl code to execute (equivalent to -e). + modules: List of modules to load (equivalent to -M). e.g., ["PostScript::TextBlock"] + include_paths: List of directories to add to @INC (equivalent to -I). + autosplit: Enable autosplit mode with -n or -p (equivalent to -a). + split_pattern: Pattern for -a switch (equivalent to -F). + warnings: Enable useful warnings (equivalent to -w). + all_warnings: Enable all warnings (equivalent to -W). + taint_check: Enable taint checks (equivalent to -T). + inplace_extension: Edit files in place, optionally providing a backup extension (equivalent to -i). + line_ending_processing: Enable line ending processing (equivalent to -l). + assume_loop_n: Assume "while (<>) { ... }" loop around program (equivalent to -n). + assume_loop_p: Assume loop like -n but print line also (equivalent to -p). + script_args: Arguments to pass to the Perl script. + """ + cmd = ["perl"] + + # Flags + if all_warnings: + cmd.append("-W") + elif warnings: + cmd.append("-w") + + if taint_check: + cmd.append("-T") + + if autosplit: + cmd.append("-a") + + if split_pattern: + cmd.append(f"-F{split_pattern}") + + if inplace_extension is not None: + cmd.append(f"-i{inplace_extension}") + + if line_ending_processing: + cmd.append("-l") + + if assume_loop_n: + cmd.append("-n") + + if assume_loop_p: + cmd.append("-p") + + # Include paths + if include_paths: + for path in include_paths: + cmd.append(f"-I{path}") + + # Modules + if modules: + for module in modules: + cmd.append(f"-M{module}") + + # Execution source + if one_liner and script_path: + raise ValueError("Provide either 'one_liner' or 'script_path', not both.") + + if one_liner: + cmd.extend(["-e", one_liner]) + elif script_path: + p = Path(script_path) + if not p.exists(): + return {"error": f"Script file not found: {script_path}"} + cmd.append(str(p)) + else: + # If neither is provided, we might just be checking version or similar, + # but this function is for execution. + raise ValueError("Either 'one_liner' or 'script_path' must be provided.") + + # Script arguments + if script_args: + cmd.extend(script_args) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def perl_postscript_check_syntax( + script_path: str, + include_paths: Optional[List[str]] = None, + modules: Optional[List[str]] = None, +): + """ + Check the syntax of a Perl script without executing it (equivalent to perl -c). + + Args: + script_path: Path to the Perl script to check. + include_paths: List of directories to add to @INC. + modules: List of modules to load before checking. + """ + p = Path(script_path) + if not p.exists(): + return {"error": f"File not found: {script_path}"} + + cmd = ["perl", "-c"] + + if include_paths: + for path in include_paths: + cmd.append(f"-I{path}") + + if modules: + for module in modules: + cmd.append(f"-M{module}") + + cmd.append(str(p)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "syntax_ok" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Syntax check failed", + "status": "syntax_error" + } + +@mcp.tool() +def perl_postscript_get_info( + config_variable: Optional[str] = None, + show_version: bool = True, +): + """ + Get Perl version information or configuration details. + + Args: + config_variable: Specific configuration variable to print (equivalent to perl -V:variable). + show_version: Print version and patchlevel (equivalent to perl -v). + """ + if config_variable: + cmd = ["perl", f"-V:{config_variable}"] + elif show_version: + cmd = ["perl", "-v"] + else: + cmd = ["perl", "-V"] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stderr": e.stderr + } + +@mcp.tool() +def perl_postscript_debug_script( + script_path: str, + debugger: Optional[str] = None, + script_args: Optional[List[str]] = None, +): + """ + Run a Perl script under the debugger (equivalent to perl -d). + Note: This is primarily for non-interactive syntax/logic validation in this context. + + Args: + script_path: Path to the Perl script. + debugger: Specific debugger to use (e.g., 'ptkdb'). + script_args: Arguments for the script. + """ + p = Path(script_path) + if not p.exists(): + return {"error": f"File not found: {script_path}"} + + debug_flag = f"-d:{debugger}" if debugger else "-d" + cmd = ["perl", debug_flag, str(p)] + + if script_args: + cmd.extend(script_args) + + try: + # Debugging might require stdin, but in a tool context we capture output + result = subprocess.run(cmd, capture_output=True, text=True, timeout=30) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "info": "Debugger session terminated or timed out." + } + except subprocess.TimeoutExpired: + return {"error": "Debugger session timed out (interactive sessions not supported via MCP tool directly)."} + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stderr": e.stderr, + "error": str(e) + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-postscript/app/perl-postscript_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-postscript/app/perl-postscript_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ad37214aa53d94cdc19eceb22f52b60934f48851 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-postscript/app/perl-postscript_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-postscript/app/perl-postscript_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_postscript' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-postscript/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-postscript/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-postscript/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-postscript/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-postscript/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..39cf53b545e2dbe0213f298eaca841ba73ed0f3d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-postscript/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-postscript: + build: . + image: mcp-perl-postscript:latest + container_name: mcp-perl-postscript + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-postscript + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-postscript/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-postscript/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1f6f93acaa643cba4cd3b51bf1ff66d621b11bb7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-postscript/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-postscript + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-postscript/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-postscript/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-postscript/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-soap-lite/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-soap-lite/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..267217daa05b75e4068fb85c6ec3ef0d962e4e0d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-soap-lite/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-soap-lite via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-soap-lite -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-soap-lite_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-soap-lite_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-soap-lite_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-soap-lite/app/__pycache__/perl-soap-lite_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-soap-lite/app/__pycache__/perl-soap-lite_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..16648b758ac207ae739b1b3a121903e4acb2bcfd Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-soap-lite/app/__pycache__/perl-soap-lite_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-soap-lite/app/perl-soap-lite_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-soap-lite/app/perl-soap-lite_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f49eb8f35f781aff6c9a463c29fd88b351e3ec05 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-soap-lite/app/perl-soap-lite_server.py @@ -0,0 +1,198 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_soap_lite' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def soap_lite_stubmaker( + wsdl_source: str, + output_dir: Optional[str] = None, +) -> Dict[str, Any]: + """ + Generate Perl client stubs from a WSDL (Web Services Description Language) source using stubmaker.pl. + + Args: + wsdl_source: The URL or local file path to the WSDL file. + output_dir: Optional directory where the generated .pm files should be saved. + """ + # Input validation + if not wsdl_source: + return {"error": "wsdl_source is required"} + + command = ["stubmaker.pl", wsdl_source] + + if output_dir: + out_path = Path(output_dir) + if not out_path.exists(): + try: + out_path.mkdir(parents=True, exist_ok=True) + except Exception as e: + return {"error": f"Could not create output directory: {str(e)}"} + command.append(str(out_path)) + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "status": "success", + "message": f"Stubs generated for {wsdl_source}" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "stubmaker.pl failed to execute", + "exit_code": e.returncode + } + except FileNotFoundError: + return {"error": "stubmaker.pl not found in the environment. Ensure perl-soap-lite is installed."} + +@mcp.tool() +def perl_soap_lite_run( + script_path: Optional[str] = None, + one_liner: Optional[str] = None, + arguments: List[str] = [], + include_dirs: List[str] = [], + warnings: bool = True, + taint_check: bool = False, +) -> Dict[str, Any]: + """ + Execute a Perl script or one-liner that utilizes the SOAP::Lite module. + + Args: + script_path: Path to a .pl script to execute. + one_liner: A string containing Perl code to execute (equivalent to perl -e). + arguments: List of command-line arguments to pass to the script. + include_dirs: List of directories to add to @INC (equivalent to -I). + warnings: Enable Perl warnings (equivalent to -w). Default is True. + taint_check: Enable taint checks (equivalent to -T). Default is False. + """ + if not script_path and not one_liner: + return {"error": "Either script_path or one_liner must be provided."} + + command = ["perl"] + + # Add SOAP::Lite module by default + command.extend(["-MSOAP::Lite"]) + + if warnings: + command.append("-w") + + if taint_check: + command.append("-T") + + for directory in include_dirs: + command.append(f"-I{directory}") + + if one_liner: + command.extend(["-e", one_liner]) + elif script_path: + path = Path(script_path) + if not path.exists(): + return {"error": f"Script file not found: {script_path}"} + command.append(str(path)) + + if arguments: + command.append("--") + command.extend(arguments) + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Perl execution failed", + "exit_code": e.returncode + } + +@mcp.tool() +def perl_soap_lite_check_syntax( + script_path: str, + include_dirs: List[str] = [], +) -> Dict[str, Any]: + """ + Check the syntax of a Perl script using SOAP::Lite without executing it. + + Args: + script_path: Path to the Perl script to check. + include_dirs: List of directories to add to @INC. + """ + path = Path(script_path) + if not path.exists(): + return {"error": f"File not found: {script_path}"} + + command = ["perl", "-MSOAP::Lite", "-c", str(path)] + + for directory in include_dirs: + command.insert(2, f"-I{directory}") + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "status": "syntax_ok" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Syntax check failed", + "exit_code": e.returncode + } + +@mcp.tool() +def soap_lite_version_info() -> Dict[str, Any]: + """ + Retrieve version information for the installed Perl and SOAP::Lite module. + """ + # Check Perl version + perl_v = subprocess.run(["perl", "-v"], capture_output=True, text=True) + + # Check SOAP::Lite version + soap_v = subprocess.run( + ["perl", "-MSOAP::Lite", "-e", "print $SOAP::Lite::VERSION"], + capture_output=True, + text=True + ) + + return { + "perl_version_raw": perl_v.stdout.splitlines()[1] if perl_v.returncode == 0 else "Unknown", + "soap_lite_version": soap_v.stdout if soap_v.returncode == 0 else "Not installed or error", + "status": "success" if soap_v.returncode == 0 else "error" + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-soap-lite/app/perl-soap-lite_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-soap-lite/app/perl-soap-lite_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0c0544fcf3e0084271a7c5dae4e9426fdd03374f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-soap-lite/app/perl-soap-lite_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-soap-lite/app/perl-soap-lite_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_soap_lite' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-soap-lite/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-soap-lite/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-soap-lite/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-soap-lite/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-soap-lite/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..292b0a680c7904ecbadc4619047172b8fd8fc1c5 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-soap-lite/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-soap-lite: + build: . + image: mcp-perl-soap-lite:latest + container_name: mcp-perl-soap-lite + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-soap-lite + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-soap-lite/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-soap-lite/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5eaf531c6e72e20eda5b390bf7b50cb70cb58511 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-soap-lite/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-soap-lite + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-soap-lite/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-soap-lite/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-soap-lite/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-parseexcel/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-parseexcel/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7fc8c5b8680b8e98e822ec5145ab3f07e3c9f935 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-parseexcel/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-spreadsheet-parseexcel via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-spreadsheet-parseexcel -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-spreadsheet-parseexcel_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-spreadsheet-parseexcel_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-spreadsheet-parseexcel_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-parseexcel/app/__pycache__/perl-spreadsheet-parseexcel_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-parseexcel/app/__pycache__/perl-spreadsheet-parseexcel_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8153c71f12c6cb9a1f4b10d9876628dd13c1fe99 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-parseexcel/app/__pycache__/perl-spreadsheet-parseexcel_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-parseexcel/app/perl-spreadsheet-parseexcel_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-parseexcel/app/perl-spreadsheet-parseexcel_server.py new file mode 100644 index 0000000000000000000000000000000000000000..09ad5f236857cc2ab0e4decf556fb07f74c7aecb --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-parseexcel/app/perl-spreadsheet-parseexcel_server.py @@ -0,0 +1,352 @@ +import subprocess +import json +import tempfile +from pathlib import Path +from typing import Optional, List, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_spreadsheet_parseexcel' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def parse_excel_summary( + input_file: str, +) -> Dict[str, Any]: + """ + Summarize an Excel (.xls) file, listing all worksheets and their dimensions. + + Args: + input_file: Path to the Excel (.xls) file. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + if not input_path.is_file(): + return {"error": f"Input path is not a file: {input_file}"} + if input_path.suffix.lower() not in ['.xls']: + return {"error": f"Input file must be an .xls Excel file: {input_file}"} + + # Perl script to extract workbook metadata + # Using str.format to avoid f-string brace escaping issues with Perl syntax + perl_script_template = """ + use Spreadsheet::ParseExcel; + use JSON; + my $parser = Spreadsheet::ParseExcel->new(); + my $workbook = $parser->parse('{input_path_str}'); + if (!defined $workbook) {{ + die $parser->error(); + }} + my @sheets; + for my $worksheet ($workbook->worksheets()) {{ + my ($row_min, $row_max) = $worksheet->row_range(); + my ($col_min, $col_max) = $worksheet->col_range(); + push @sheets, {{ + name => $worksheet->get_name(), + rows => ($row_max - $row_min + 1), + cols => ($col_max - $col_min + 1), + row_range => [$row_min, $row_max], + col_range => [$col_min, $col_max] + }}; + }} + print encode_json(\\@sheets); + """ + perl_script = perl_script_template.format(input_path_str=str(input_path)) + + try: + result = subprocess.run( + ["perl", "-e", perl_script], + capture_output=True, + text=True, + check=True + ) + sheets_info = json.loads(result.stdout) + return { + "command_executed": f"perl -MSpreadsheet::ParseExcel ... {input_file}", + "file": input_file, + "worksheets": sheets_info, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to parse Excel file", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd, + "output_files": [] + } + except json.JSONDecodeError as e: + return { + "error": "Failed to decode JSON output from Perl script", + "stdout": result.stdout, + "stderr": result.stderr, + "command_executed": f"perl -MSpreadsheet::ParseExcel ... {input_file}", + "output_files": [] + } + +@mcp.tool() +def parse_excel_sheet_to_csv( + input_file: str, + sheet_index: int = 0, + output_csv: Optional[str] = None, +) -> Dict[str, Any]: + """ + Convert a specific worksheet from an Excel (.xls) file to a CSV file. + + Args: + input_file: Path to the Excel (.xls) file. + sheet_index: Index of the worksheet to extract (starting from 0). Must be non-negative. + output_csv: Optional path for the output CSV. If not provided, returns content in stdout. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + if not input_path.is_file(): + return {"error": f"Input path is not a file: {input_file}"} + if input_path.suffix.lower() not in ['.xls']: + return {"error": f"Input file must be an .xls Excel file: {input_file}"} + if sheet_index < 0: + return {"error": f"Sheet index must be non-negative, got: {sheet_index}"} + + # Perl script to extract a sheet as CSV + # Using str.format to avoid f-string brace escaping issues with Perl syntax + perl_script_template = """ + use Spreadsheet::ParseExcel; + my $parser = Spreadsheet::ParseExcel->new(); + my $workbook = $parser->parse('{input_path_str}'); + die $parser->error() if !defined $workbook; + my $worksheet = $workbook->worksheet({sheet_index_val}); + die "Worksheet at index {sheet_index_val} not found" if !defined $worksheet; + + my ($row_min, $row_max) = $worksheet->row_range(); + my ($col_min, $col_max) = $worksheet->col_range(); + + for my $row ($row_min .. $row_max) {{ + my @row_data; + for my $col ($col_min .. $col_max) {{ + my $cell = $worksheet->get_cell($row, $col); + if ($cell) {{ + my $val = $cell->value(); + $val =~ s/"/""/g; # Escape quotes + push @row_data, qq("$val"); + }} else {{ + push @row_data, '""'; + }} + }} + print join(",", @row_data) . "\\n"; + }} + """ + perl_script = perl_script_template.format( + input_path_str=str(input_path), + sheet_index_val=sheet_index + ) + + try: + result = subprocess.run( + ["perl", "-e", perl_script], + capture_output=True, + text=True, + check=True + ) + + output_files = [] + stdout_message = result.stdout + if output_csv: + out_path = Path(output_csv) + try: + out_path.write_text(result.stdout) + output_files.append(str(out_path)) + stdout_message = f"Content written to file: {output_csv}" + except IOError as e: + return { + "error": f"Failed to write output CSV to {output_csv}: {e}", + "stdout": result.stdout, + "stderr": result.stderr, + "command_executed": f"perl -MSpreadsheet::ParseExcel (extract sheet {sheet_index})", + "output_files": [] + } + + return { + "command_executed": f"perl -MSpreadsheet::ParseExcel (extract sheet {sheet_index})", + "stdout": stdout_message, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + return { + "error": f"Failed to extract sheet {sheet_index}", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd, + "output_files": [] + } + +@mcp.tool() +def parse_excel_to_json( + input_file: str, +) -> Dict[str, Any]: + """ + Convert the entire content of an Excel (.xls) file into a JSON structure. + + Args: + input_file: Path to the Excel (.xls) file. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + if not input_path.is_file(): + return {"error": f"Input path is not a file: {input_file}"} + if input_path.suffix.lower() not in ['.xls']: + return {"error": f"Input file must be an .xls Excel file: {input_file}"} + + # Using str.format to avoid f-string brace escaping issues with Perl syntax + perl_script_template = """ + use Spreadsheet::ParseExcel; + use JSON; + my $parser = Spreadsheet::ParseExcel->new(); + my $workbook = $parser->parse('{input_path_str}'); + die $parser->error() if !defined $workbook; + + my %data; + for my $worksheet ($workbook->worksheets()) {{ + my $name = $worksheet->get_name(); + my ($row_min, $row_max) = $worksheet->row_range(); + my ($col_min, $col_max) = $worksheet->col_range(); + my @rows; + for my $row ($row_min .. $row_max) {{ + my @row_data; + for my $col ($col_min .. $col_max) {{ + my $cell = $worksheet->get_cell($row, $col); + push @row_data, $cell ? $cell->value() : undef; + }} + push @rows, \\@row_data; + }} + $data{{$name}} = \\@rows; + }} + print encode_json(\\%data); + """ + perl_script = perl_script_template.format(input_path_str=str(input_path)) + + try: + result = subprocess.run( + ["perl", "-e", perl_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "perl -MSpreadsheet::ParseExcel -MJSON ...", + "data": json.loads(result.stdout), + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to convert workbook to JSON", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd, + "output_files": [] + } + except json.JSONDecodeError as e: + return { + "error": "Failed to decode JSON output from Perl script", + "stdout": result.stdout, + "stderr": result.stderr, + "command_executed": "perl -MSpreadsheet::ParseExcel -MJSON ...", + "output_files": [] + } + +@mcp.tool() +def parse_excel_cell( + input_file: str, + sheet_index: int = 0, + row: int = 0, + col: int = 0, +) -> Dict[str, Any]: + """ + Retrieve the value and format of a specific cell in an Excel (.xls) file. + + Args: + input_file: Path to the Excel (.xls) file. + sheet_index: Index of the worksheet (starting from 0). Must be non-negative. + row: Row index (starting from 0). Must be non-negative. + col: Column index (starting from 0). Must be non-negative. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + if not input_path.is_file(): + return {"error": f"Input path is not a file: {input_file}"} + if input_path.suffix.lower() not in ['.xls']: + return {"error": f"Input file must be an .xls Excel file: {input_file}"} + if sheet_index < 0: + return {"error": f"Sheet index must be non-negative, got: {sheet_index}"} + if row < 0: + return {"error": f"Row index must be non-negative, got: {row}"} + if col < 0: + return {"error": f"Column index must be non-negative, got: {col}"} + + # Using str.format to avoid f-string brace escaping issues with Perl syntax + perl_script_template = """ + use Spreadsheet::ParseExcel; + use JSON; + my $parser = Spreadsheet::ParseExcel->new(); + my $workbook = $parser->parse('{input_path_str}'); + die $parser->error() if !defined $workbook; + my $worksheet = $workbook->worksheet({sheet_index_val}); + die "Sheet not found" if !defined $worksheet; + + my $cell = $worksheet->get_cell({row_val}, {col_val}); + if ($cell) {{ + print encode_json({{ + value => $cell->value(), + unformatted => $cell->unformatted(), + type => $cell->type(), + format => $cell->{{FormatNo}} + }}); + }} else {{ + print encode_json({{value => undef, status => "empty"}}); + }} + """ + perl_script = perl_script_template.format( + input_path_str=str(input_path), + sheet_index_val=sheet_index, + row_val=row, + col_val=col + ) + + try: + result = subprocess.run( + ["perl", "-e", perl_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"perl -MSpreadsheet::ParseExcel (get cell {row},{col})", + "cell_data": json.loads(result.stdout), + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to retrieve cell data", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd, + "output_files": [] + } + except json.JSONDecodeError as e: + return { + "error": "Failed to decode JSON output from Perl script", + "stdout": result.stdout, + "stderr": result.stderr, + "command_executed": f"perl -MSpreadsheet::ParseExcel (get cell {row},{col})", + "output_files": [] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-parseexcel/app/perl-spreadsheet-parseexcel_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-parseexcel/app/perl-spreadsheet-parseexcel_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..76ebf66e53a1fa7c549420c167a57e9ad48647a3 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-parseexcel/app/perl-spreadsheet-parseexcel_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-parseexcel/app/perl-spreadsheet-parseexcel_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_spreadsheet_parseexcel' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-parseexcel/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-parseexcel/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-parseexcel/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-parseexcel/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-parseexcel/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..2cbb77445cc214574474f6cd390d37024acf5d14 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-parseexcel/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-spreadsheet-parseexcel: + build: . + image: mcp-perl-spreadsheet-parseexcel:latest + container_name: mcp-perl-spreadsheet-parseexcel + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-spreadsheet-parseexcel + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-parseexcel/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-parseexcel/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4909298335736f9d45a848ad0f0812b132d943a8 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-parseexcel/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-spreadsheet-parseexcel + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-parseexcel/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-parseexcel/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-parseexcel/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-writeexcel/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-writeexcel/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0d19939cd82e43d1b0a7dfd52fbd5cd927ce86b2 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-writeexcel/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-spreadsheet-writeexcel via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-spreadsheet-writeexcel -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-spreadsheet-writeexcel_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-spreadsheet-writeexcel_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-spreadsheet-writeexcel_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-writeexcel/app/__pycache__/perl-spreadsheet-writeexcel_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-writeexcel/app/__pycache__/perl-spreadsheet-writeexcel_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..07439de8206e5ef808c6bcf322975d8c4a891a7a Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-writeexcel/app/__pycache__/perl-spreadsheet-writeexcel_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-writeexcel/app/perl-spreadsheet-writeexcel_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-writeexcel/app/perl-spreadsheet-writeexcel_server.py new file mode 100644 index 0000000000000000000000000000000000000000..05861fcfbbcbe7d022ebdd145baaee50f7c2f202 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-writeexcel/app/perl-spreadsheet-writeexcel_server.py @@ -0,0 +1,229 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +# In a real MCP implementation, the mcp module would be imported. +# For this exercise, we assume it's available and the decorator works as expected. +# import mcp + +# This is a placeholder for the MCP decorator. +# In a real environment, this would be provided by the MCP framework. +def tool(): + def decorator(func): + return func + return decorator + +mcp = type('mcp', (), {'tool': tool}) + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_spreadsheet_writeexcel' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_perl_interpreter( + programfile: Optional[Path] = None, + arguments: Optional[List[str]] = None, + program_line: Optional[List[str]] = None, + program_line_features: Optional[List[str]] = None, + record_separator: Optional[str] = None, + autosplit: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + use_debugger: bool = False, + debugger_name: Optional[str] = None, + debugging_flags: Optional[str] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + in_place_edit_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_ending: Optional[str] = None, + use_module: Optional[List[str]] = None, + no_module: Optional[List[str]] = None, + loop_around_program: bool = False, + loop_and_print: bool = False, + parse_switches: bool = False, + search_path: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core: bool = False, + unsafe_operations: bool = False, + print_version: bool = False, + print_config_summary: bool = False, + print_config_variable: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_text_before_shebang: bool = False, + cd_to_directory_for_x: Optional[Path] = None, + disable_all_warnings: bool = False, +) -> Dict[str, Any]: + """ + Wraps the Perl interpreter, allowing execution of scripts like those using Spreadsheet::WriteExcel. + + This tool provides a comprehensive interface to the Perl interpreter's command-line options. + It is designed to run any Perl script, including those that leverage libraries such as + Spreadsheet::WriteExcel to create Excel files. + + Args: + programfile: Path to the Perl program file to execute. + arguments: A list of arguments to be passed to the program file. + program_line: Specifies a line of the program using the -e switch. Can be used multiple times. + program_line_features: Like -e, but enables all optional features (-E switch). + record_separator: Specify record separator (e.g., '\\0') using the -0 switch. + autosplit: Enable autosplit mode with -n or -p (splits $_ into @F) using the -a switch. + unicode_features: Enable the listed Unicode features using the -C switch. + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks) using the -c switch. + use_debugger: Run the program under the debugger (-d switch). + debugger_name: Specify a specific debugger to use (e.g., -d:DebuggerName). + debugging_flags: Set debugging flags (-D switch). + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup (-f switch). + split_pattern: Specify the split() pattern for the -a switch (-F switch). + in_place_edit_extension: Edit <> files in place. Makes a backup if an extension is supplied (-i switch). + include_directories: Specify @INC/#include directory. Can be used multiple times (-I switch). + line_ending: Enable line ending processing, specifies line terminator (-l switch). + use_module: Execute "use module..." before executing the program (-M switch). + no_module: Execute "no module..." before executing the program (-m switch). + loop_around_program: Assume "while (<>) { ... }" loop around the program (-n switch). + loop_and_print: Assume loop like -n but also print the line, like sed (-p switch). + parse_switches: Enable rudimentary parsing for switches after the program file (-s switch). + search_path: Look for the program file using the PATH environment variable (-S switch). + tainting_warnings: Enable tainting warnings (-t switch). + tainting_checks: Enable tainting checks (-T switch). + dump_core: Dump core after parsing the program (-u switch). + unsafe_operations: Allow unsafe operations (-U switch). + print_version: Print version, patchlevel, and license (-v switch). + print_config_summary: Print configuration summary (-V switch). + print_config_variable: Print a single Config.pm variable (-V:variable). + enable_warnings: Enable many useful warnings (-w switch). + enable_all_warnings: Enable all warnings (-W switch). + ignore_text_before_shebang: Ignore text before #!perl line (-x switch). + cd_to_directory_for_x: Optionally cd to a directory with the -x switch. + disable_all_warnings: Disable all warnings (-X switch). + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # Input Validation + if not any([programfile, program_line, program_line_features, print_version, print_config_summary, print_config_variable]): + raise ValueError("Execution requirement missing: you must provide a 'programfile', 'program_line', 'program_line_features', or request version/config info.") + + if programfile and not programfile.is_file(): + raise FileNotFoundError(f"Program file not found: {programfile}") + + if include_directories: + for d in include_directories: + if not d.is_dir(): + raise NotADirectoryError(f"Include directory not found: {d}") + + if cd_to_directory_for_x and not cd_to_directory_for_x.is_dir(): + raise NotADirectoryError(f"Directory for -x option not found: {cd_to_directory_for_x}") + + if debugger_name and not use_debugger: + raise ValueError("'debugger_name' can only be used when 'use_debugger' is True.") + + if cd_to_directory_for_x and not ignore_text_before_shebang: + raise ValueError("'cd_to_directory_for_x' can only be used when 'ignore_text_before_shebang' is True.") + + # Command Construction + cmd = ["perl"] + + if record_separator is not None: + cmd.append(f"-0{record_separator}") + if autosplit: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if use_debugger: + cmd.append(f"-d{':' + debugger_name if debugger_name else ''}") + if debugging_flags is not None: + cmd.append(f"-D{debugging_flags}") + if no_sitecustomize: + cmd.append("-f") + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + if in_place_edit_extension is not None: + cmd.append(f"-i{in_place_edit_extension}") + if include_directories: + for d in include_directories: + cmd.extend(["-I", str(d)]) + if line_ending is not None: + cmd.append(f"-l{line_ending}") + if use_module: + for m in use_module: + cmd.extend(["-M", m]) + if no_module: + for m in no_module: + cmd.extend(["-m", m]) + if loop_around_program: + cmd.append("-n") + if loop_and_print: + cmd.append("-p") + if parse_switches: + cmd.append("-s") + if search_path: + cmd.append("-S") + if tainting_warnings: + cmd.append("-t") + if tainting_checks: + cmd.append("-T") + if dump_core: + cmd.append("-u") + if unsafe_operations: + cmd.append("-U") + if print_version: + cmd.append("-v") + if print_config_summary or print_config_variable: + cmd.append(f"-V{':' + print_config_variable if print_config_variable else ''}") + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if ignore_text_before_shebang: + cmd.append(f"-x{str(cd_to_directory_for_x) if cd_to_directory_for_x else ''}") + if disable_all_warnings: + cmd.append("-X") + if program_line: + for line in program_line: + cmd.extend(["-e", line]) + if program_line_features: + for line in program_line_features: + cmd.extend(["-E", line]) + + if programfile: + cmd.append(str(programfile)) + if arguments: + cmd.extend(arguments) + + command_executed = " ".join(cmd) + + # Subprocess Execution + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] # The interpreter itself doesn't guarantee output files + } + except FileNotFoundError: + raise RuntimeError("The 'perl' executable was not found in the system's PATH. Please ensure Perl is installed and accessible.") + except subprocess.CalledProcessError as e: + # For failed executions, return a structured error with captured output + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Perl execution failed with return code {e.returncode}", + "output_files": [] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-writeexcel/app/perl-spreadsheet-writeexcel_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-writeexcel/app/perl-spreadsheet-writeexcel_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1fc935659e3ec6552f1af0c55976e83c39676568 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-writeexcel/app/perl-spreadsheet-writeexcel_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-spreadsheet-writeexcel/app/perl-spreadsheet-writeexcel_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_spreadsheet_writeexcel' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-writeexcel/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-writeexcel/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-writeexcel/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-writeexcel/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-writeexcel/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..830345fa6ac5dad62b8734e80899362e4f929809 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-writeexcel/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-spreadsheet-writeexcel: + build: . + image: mcp-perl-spreadsheet-writeexcel:latest + container_name: mcp-perl-spreadsheet-writeexcel + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-spreadsheet-writeexcel + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-writeexcel/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-writeexcel/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..911fe58de269ce55c63564047603fa5a68bc15e9 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-writeexcel/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-spreadsheet-writeexcel + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-writeexcel/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-writeexcel/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-spreadsheet-writeexcel/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-sub-uplevel/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-sub-uplevel/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6bfc3e627d159d944a5754a34e441b4c83e0dd91 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-sub-uplevel/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-sub-uplevel via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-sub-uplevel -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-sub-uplevel_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-sub-uplevel_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-sub-uplevel_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-sub-uplevel/app/__pycache__/perl-sub-uplevel_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-sub-uplevel/app/__pycache__/perl-sub-uplevel_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a72106a1cb1ab2e2e03e0be48ddb8014196996ca Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-sub-uplevel/app/__pycache__/perl-sub-uplevel_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-sub-uplevel/app/perl-sub-uplevel_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-sub-uplevel/app/perl-sub-uplevel_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7942fe2a02eb5b40fdaec4c19bf2db617edd72bf --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-sub-uplevel/app/perl-sub-uplevel_server.py @@ -0,0 +1,226 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be imported. +def tool(func): + """A dummy decorator to allow the code to be syntactically valid.""" + return func + +mcp = type("mcp", (), {"tool": tool}) + +@mcp.tool +def run_perl( + programfile: Optional[Path] = None, + arguments: Optional[List[str]] = None, + e_program: Optional[List[str]] = None, + E_program: Optional[List[str]] = None, + include_dirs: Optional[List[Path]] = None, + module: Optional[List[str]] = None, + check_syntax_only: bool = False, + debugger: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + enable_tainting_checks: bool = False, + enable_tainting_warnings: bool = False, + loop_around_program: bool = False, + loop_and_print: bool = False, + autosplit: bool = False, + line_ending: Optional[str] = None, + split_pattern: Optional[str] = None, + inplace_edit_extension: Optional[str] = None, + parse_switches: bool = False, + search_path: bool = False, + print_version: bool = False, + print_config: Optional[str] = None, + unicode_features: Optional[str] = None, + debugging_flags: Optional[str] = None, + no_sitecustomize: bool = False, + dump_core: bool = False, + allow_unsafe: bool = False, + extract_from_text_dir: Optional[Path] = None, + disable_all_warnings: bool = False, + record_separator: Optional[str] = None, +) -> Dict[str, Any]: + """ + Executes a Perl script or command using the Perl interpreter. + + This tool is a wrapper for the `perl` command-line interpreter. The `perl-sub-uplevel` + package is a Perl module and does not have its own executable. + + Args: + programfile: Path to the Perl program file to execute. + arguments: A list of arguments to pass to the program file. + e_program: A list of strings, each being a line of a program. + E_program: Like -e, but enables all optional features. + include_dirs: A list of directories to add to @INC. Corresponds to the -I flag. + module: A list of modules to use/no before executing the program. Corresponds to the -M/-m flag. + check_syntax_only: Check syntax only (runs BEGIN and CHECK blocks). Corresponds to the -c flag. + debugger: Run the program under the specified debugger. Corresponds to the -d[:debugger] flag. + enable_warnings: Enable many useful warnings. Corresponds to the -w flag. + enable_all_warnings: Enable all warnings. Corresponds to the -W flag. + enable_tainting_checks: Enable tainting checks. Corresponds to the -T flag. + enable_tainting_warnings: Enable tainting warnings. Corresponds to the -t flag. + loop_around_program: Assume "while (<>) { ... }" loop around the program. Corresponds to the -n flag. + loop_and_print: Assume loop like -n but also print the line. Corresponds to the -p flag. + autosplit: Autosplit mode with -n or -p (splits $_ into @F). Corresponds to the -a flag. + line_ending: Enable line ending processing, specifies line terminator. Corresponds to the -l[octal] flag. + split_pattern: split() pattern for the -a switch. Corresponds to the -F/pattern/ flag. + inplace_edit_extension: Edit <> files in place, making a backup if an extension is supplied. Corresponds to the -i[extension] flag. + parse_switches: Enable rudimentary parsing for switches after the program file. Corresponds to the -s flag. + search_path: Look for the program file using the PATH environment variable. Corresponds to the -S flag. + print_version: Print version, patchlevel, and license. Corresponds to the -v flag. + print_config: Print configuration summary or a single Config.pm variable. Corresponds to the -V[:variable] flag. + unicode_features: Enables the listed Unicode features. Corresponds to the -C[number/list] flag. + debugging_flags: Set debugging flags. Corresponds to the -D[number/list] flag. + no_sitecustomize: Don't do $sitelib/sitecustomize.pl at startup. Corresponds to the -f flag. + dump_core: Dump core after parsing the program. Corresponds to the -u flag. + allow_unsafe: Allow unsafe operations. Corresponds to the -U flag. + extract_from_text_dir: Ignore text before #!perl line, optionally cd to the directory. Corresponds to the -x[directory] flag. + disable_all_warnings: Disable all warnings. Corresponds to the -X flag. + record_separator: Specify the record separator. Corresponds to the -0[octal] flag. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not any([programfile, e_program, E_program, print_version, print_config is not None]): + raise ValueError("Either a program file, an inline program (-e or -E), or an info flag (-v or -V) must be provided.") + + if programfile and (e_program or E_program): + raise ValueError("`programfile` cannot be used at the same time as `e_program` or `E_program`.") + + if programfile and not programfile.is_file(): + raise FileNotFoundError(f"The specified program file does not exist: {programfile}") + + if include_dirs: + for directory in include_dirs: + if not directory.is_dir(): + raise NotADirectoryError(f"The include directory does not exist: {directory}") + + if extract_from_text_dir and not extract_from_text_dir.is_dir(): + raise NotADirectoryError(f"The directory for -x does not exist: {extract_from_text_dir}") + + # --- Command Construction --- + cmd = ["perl"] + + if record_separator is not None: + cmd.append(f"-0{record_separator}") + if autosplit: + cmd.append("-a") + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + if check_syntax_only: + cmd.append("-c") + if debugger is not None: + cmd.append(f"-d:{debugger}" if debugger else "-d") + if debugging_flags is not None: + cmd.append(f"-D{debugging_flags}") + if no_sitecustomize: + cmd.append("-f") + if split_pattern is not None: + cmd.append(f"-F{split_pattern}") + if inplace_edit_extension is not None: + cmd.append(f"-i{inplace_edit_extension}") + if line_ending is not None: + cmd.append(f"-l{line_ending}") + if loop_around_program: + cmd.append("-n") + if loop_and_print: + cmd.append("-p") + if parse_switches: + cmd.append("-s") + if search_path: + cmd.append("-S") + if enable_tainting_warnings: + cmd.append("-t") + if enable_tainting_checks: + cmd.append("-T") + if dump_core: + cmd.append("-u") + if allow_unsafe: + cmd.append("-U") + if print_version: + cmd.append("-v") + if print_config is not None: + cmd.append(f"-V:{print_config}" if print_config else "-V") + if enable_warnings: + cmd.append("-w") + if enable_all_warnings: + cmd.append("-W") + if extract_from_text_dir is not None: + cmd.extend(["-x", str(extract_from_text_dir)]) + elif extract_from_text_dir is not None: # -x without directory + cmd.append("-x") + if disable_all_warnings: + cmd.append("-X") + + if include_dirs: + for directory in include_dirs: + cmd.extend(["-I", str(directory)]) + + if module: + for mod in module: + if mod.startswith('-'): # for 'no module' + cmd.extend(["-m", mod]) + else: + cmd.extend(["-M", mod]) + + if e_program: + for prog_line in e_program: + cmd.extend(["-e", prog_line]) + + if E_program: + for prog_line in E_program: + cmd.extend(["-E", prog_line]) + + if programfile: + cmd.append(str(programfile)) + + if arguments: + cmd.extend(arguments) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + stdout = result.stdout + stderr = result.stderr + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and in your PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + # --- Structured Result Return --- + output_files = [] + # The -i flag modifies files in place. If used with a programfile and arguments, + # those arguments might be files that get modified. + if inplace_edit_extension is not None and arguments: + for arg in arguments: + p = Path(arg) + if p.is_file(): + output_files.append(str(p)) + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files + } \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-sub-uplevel/app/perl-sub-uplevel_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-sub-uplevel/app/perl-sub-uplevel_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e007adc39824aef4862ad9a5a84d45019c065708 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-sub-uplevel/app/perl-sub-uplevel_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-sub-uplevel/app/perl-sub-uplevel_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_sub_uplevel' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-sub-uplevel/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-sub-uplevel/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-sub-uplevel/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-sub-uplevel/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-sub-uplevel/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c830f8cbcf572935fb9d12691e9e1fe9f53929d0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-sub-uplevel/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-sub-uplevel: + build: . + image: mcp-perl-sub-uplevel:latest + container_name: mcp-perl-sub-uplevel + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-sub-uplevel + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-sub-uplevel/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-sub-uplevel/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fcd9a0f226b068f02f26750f04dbbf1c47a60995 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-sub-uplevel/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-sub-uplevel + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-sub-uplevel/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-sub-uplevel/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-sub-uplevel/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-task-weaken/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-task-weaken/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c3fe1ee968a78a8d0a6eb8988c8e80657283dbfc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-task-weaken/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-task-weaken via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-task-weaken -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-task-weaken_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-task-weaken_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-task-weaken_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-task-weaken/app/__pycache__/perl-task-weaken_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-task-weaken/app/__pycache__/perl-task-weaken_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fb0cea2ce1ce3c868f96000fd42d2ec3e2fef571 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-task-weaken/app/__pycache__/perl-task-weaken_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-task-weaken/app/perl-task-weaken_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-task-weaken/app/perl-task-weaken_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a218ebfde32fa475dd2a87269b8ba7efd2626a84 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-task-weaken/app/perl-task-weaken_server.py @@ -0,0 +1,244 @@ +from typing import Optional, List +import subprocess +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_task_weaken' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def perl_execute( + program_file: Optional[str] = None, + one_liner: Optional[str] = None, + one_liner_extended: Optional[str] = None, + modules: Optional[List[str]] = None, + include_dirs: Optional[List[str]] = None, + warnings: bool = False, + all_warnings: bool = False, + disable_warnings: bool = False, + taint_checks: bool = False, + taint_warnings: bool = False, + autosplit: bool = False, + split_pattern: Optional[str] = None, + loop_n: bool = False, + loop_p: bool = False, + inplace_extension: Optional[str] = None, + record_separator: Optional[str] = None, + line_ending: bool = False, + line_ending_octal: Optional[str] = None, + unicode_features: Optional[str] = None, + debug_flags: Optional[str] = None, + debugger: Optional[str] = None, + no_site_customize: bool = False, + path_search: bool = False, + unsafe_operations: bool = False, + strip_text: bool = False, + strip_text_dir: Optional[str] = None, + arguments: Optional[List[str]] = None, +): + """ + Execute a Perl script or command with various switches. + This tool provides access to the Perl interpreter, which is the primary execution environment for Task::Weaken. + """ + cmd = ["perl"] + + # Handle switches + if record_separator is not None: + cmd.append(f"-0{record_separator}") + if autosplit: + cmd.append("-a") + if unicode_features: + cmd.append(f"-C{unicode_features}") + if debugger: + cmd.append(f"-d:{debugger}") + elif debugger == "": # Handle -d without argument + cmd.append("-d") + if debug_flags: + cmd.append(f"-D{debug_flags}") + if one_liner: + cmd.append("-e") + cmd.append(one_liner) + if one_liner_extended: + cmd.append("-E") + cmd.append(one_liner_extended) + if no_site_customize: + cmd.append("-f") + if split_pattern: + cmd.append(f"-F{split_pattern}") + if inplace_extension is not None: + cmd.append(f"-i{inplace_extension}") + if include_dirs: + for d in include_dirs: + cmd.append(f"-I{d}") + if line_ending: + if line_ending_octal: + cmd.append(f"-l{line_ending_octal}") + else: + cmd.append("-l") + if modules: + for m in modules: + cmd.append(f"-M{m}") + if loop_n: + cmd.append("-n") + if loop_p: + cmd.append("-p") + if path_search: + cmd.append("-S") + if taint_warnings: + cmd.append("-t") + if taint_checks: + cmd.append("-T") + if unsafe_operations: + cmd.append("-U") + if warnings: + cmd.append("-w") + if all_warnings: + cmd.append("-W") + if disable_warnings: + cmd.append("-X") + if strip_text: + if strip_text_dir: + cmd.append(f"-x{strip_text_dir}") + else: + cmd.append("-x") + + # Program file and arguments + if program_file: + prog_path = Path(program_file) + if not prog_path.exists(): + return {"error": f"Program file not found: {program_file}"} + cmd.append(program_file) + + if arguments: + cmd.extend(arguments) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "return_code": result.returncode + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + "error": str(e) + } + +@mcp.tool() +def perl_check_syntax(program_file: str): + """Check the syntax of a Perl script without executing it (-c).""" + prog_path = Path(program_file) + if not prog_path.exists(): + return {"error": f"File not found: {program_file}"} + + cmd = ["perl", "-c", program_file] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "Syntax OK" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Syntax check failed" + } + +@mcp.tool() +def perl_get_version(): + """Print the Perl version, patchlevel, and license information (-v).""" + cmd = ["perl", "-v"] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def perl_get_config(variable: Optional[str] = None): + """Print Perl configuration summary or a single Config.pm variable (-V).""" + cmd = ["perl", "-V"] + if variable: + cmd.append(f":{variable}") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def perl_task_weaken_verify(): + """ + Verify if Task::Weaken is installed and functional in the current environment. + This ensures the platform has support for weak references (Scalar::Util::weaken). + """ + # Task::Weaken is a module that ensures weaken support is present. + # We check it by attempting to load it and verifying Scalar::Util::weaken exists. + perl_code = "use Task::Weaken; use Scalar::Util 'weaken'; print 'Task::Weaken verified: Scalar::Util::weaken is available.';" + cmd = ["perl", "-e", perl_code] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "Success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Task::Weaken verification failed. Weak reference support may be missing or the module is not installed.", + "status": "Failed" + } + +@mcp.tool() +def perl_run_one_liner(code: str, use_extended_features: bool = False): + """ + Run a simple Perl one-liner command (-e or -E). + + Args: + code: The Perl code to execute. + use_extended_features: If True, uses -E to enable all optional features. + """ + flag = "-E" if use_extended_features else "-e" + cmd = ["perl", flag, code] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-task-weaken/app/perl-task-weaken_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-task-weaken/app/perl-task-weaken_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7e2ef4b0423d5d10940aa52a6f287cff38439a27 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-task-weaken/app/perl-task-weaken_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-task-weaken/app/perl-task-weaken_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_task_weaken' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-task-weaken/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-task-weaken/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-task-weaken/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-task-weaken/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-task-weaken/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e0b3967b39f1efca6c3e4c15032de95ff4f656cb --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-task-weaken/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-task-weaken: + build: . + image: mcp-perl-task-weaken:latest + container_name: mcp-perl-task-weaken + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-task-weaken + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-task-weaken/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-task-weaken/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..51111f3a50082ea7bb341f321c3b3c3e4c547522 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-task-weaken/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-task-weaken + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-task-weaken/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-task-weaken/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-task-weaken/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-template-toolkit/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-template-toolkit/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..dab28d2ea9b20d2995bbcf1e60845b7e7bd32f89 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-template-toolkit/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-template-toolkit via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-template-toolkit -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-template-toolkit_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-template-toolkit_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-template-toolkit_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-template-toolkit/app/__pycache__/perl-template-toolkit_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-template-toolkit/app/__pycache__/perl-template-toolkit_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..17d5020e1bfb4656a6281c39c5f29c4c23eee6a0 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-template-toolkit/app/__pycache__/perl-template-toolkit_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-template-toolkit/app/perl-template-toolkit_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-template-toolkit/app/perl-template-toolkit_server.py new file mode 100644 index 0000000000000000000000000000000000000000..762a4fa222e1e4e2662ece3f0f7ea9399d000c4d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-template-toolkit/app/perl-template-toolkit_server.py @@ -0,0 +1,239 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict +import os + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_template_toolkit' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def tpage( + template_file: Optional[str] = None, + defines: Optional[Dict[str, str]] = None, + pre_chomp: bool = False, + post_chomp: bool = False, + trim: bool = False, + absolute: bool = False, + relative: bool = False, + binmode: Optional[str] = None, + debug: bool = False, +): + """ + Process a single template file using the Template Toolkit 'tpage' utility. + + Args: + template_file: Path to the template file to process. If None, reads from stdin (not recommended for MCP). + defines: Dictionary of template variables to define (e.g., {"name": "world"}). + pre_chomp: Remove whitespace before directives. + post_chomp: Remove whitespace after directives. + trim: Trim leading and trailing whitespace from output. + absolute: Allow absolute paths for templates. + relative: Allow relative paths for templates. + binmode: Set binary mode for output (e.g., 'utf8'). + debug: Enable Template Toolkit debugging. + """ + cmd = ["tpage"] + + # Handle defines + if defines: + for key, value in defines.items(): + cmd.extend(["--define", f"{key}={value}"]) + + # Boolean flags + if pre_chomp: + cmd.append("--pre_chomp") + if post_chomp: + cmd.append("--post_chomp") + if trim: + cmd.append("--trim") + if absolute: + cmd.append("--absolute") + if relative: + cmd.append("--relative") + if debug: + cmd.append("--debug") + + # Optional string parameters + if binmode: + cmd.extend(["--binmode", binmode]) + + # Positional argument + if template_file: + path_obj = Path(template_file) + if not path_obj.exists(): + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": f"Error: Template file '{template_file}' not found.", + "output_files": [] + } + cmd.append(str(path_obj)) + + try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def ttree( + src: Optional[str] = None, + dest: Optional[str] = None, + cfg: Optional[str] = None, + lib: Optional[List[str]] = None, + all_files: bool = False, + recurse: bool = False, + verbose: bool = False, + ignore: Optional[List[str]] = None, + accept: Optional[List[str]] = None, + suffix: Optional[Dict[str, str]] = None, + prefix: Optional[str] = None, + wrapper: Optional[str] = None, + pre_process: Optional[List[str]] = None, + post_process: Optional[List[str]] = None, + dry_run: bool = False, +): + """ + Process entire directories of template files using the Template Toolkit 'ttree' utility. + + Args: + src: Source directory containing templates. + dest: Destination directory for processed files. + cfg: Path to a configuration file (e.g., .ttreerc). + lib: List of library directories for templates. + all_files: Process all files, even those that haven't changed. + recurse: Recurse into subdirectories. + verbose: List files as they are processed. + ignore: List of regular expressions for files to ignore. + accept: List of regular expressions for files to accept. + suffix: Dictionary mapping template suffixes to output suffixes (e.g., {"tt2": "html"}). + prefix: Prefix to add to output filenames. + wrapper: Template file to wrap around every template processed. + pre_process: List of templates to process before the main template. + post_process: List of templates to process after the main template. + dry_run: Show what would be done without actually doing it. + """ + cmd = ["ttree"] + + # Configuration file + if cfg: + cfg_path = Path(cfg) + if not cfg_path.exists(): + return {"error": f"Config file {cfg} not found."} + cmd.extend(["-f", str(cfg_path)]) + + # Source and Destination + if src: + src_path = Path(src) + if not src_path.is_dir(): + return {"error": f"Source directory {src} does not exist or is not a directory."} + cmd.extend(["-s", str(src_path)]) + + if dest: + dest_path = Path(dest) + # ttree usually requires the destination to exist + if not dest_path.exists(): + dest_path.mkdir(parents=True, exist_ok=True) + cmd.extend(["-d", str(dest_path)]) + + # Libraries + if lib: + for l in lib: + cmd.extend(["-l", l]) + + # Boolean flags + if all_files: + cmd.append("-a") + if recurse: + cmd.append("-r") + if verbose: + cmd.append("-v") + if dry_run: + cmd.append("-n") + + # Regex filters + if ignore: + for pattern in ignore: + cmd.extend(["--ignore", pattern]) + if accept: + for pattern in accept: + cmd.extend(["--accept", pattern]) + + # Suffix mapping + if suffix: + for old, new in suffix.items(): + cmd.extend(["--suffix", f"{old}={new}"]) + + # Other options + if prefix: + cmd.extend(["--prefix", prefix]) + if wrapper: + cmd.extend(["--wrapper", wrapper]) + if pre_process: + for p in pre_process: + cmd.extend(["--pre_process", p]) + if post_process: + for p in post_process: + cmd.extend(["--post_process", p]) + + try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True) + + # Identify output files if destination was provided + output_files = [] + if dest: + dest_path = Path(dest) + output_files = [str(p) for p in dest_path.rglob('*') if p.is_file()] + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def perl_template_version(): + """ + Check the version of the installed Template Toolkit. + """ + # Template Toolkit doesn't have a simple --version flag on its binaries, + # so we check via perl module version. + cmd = ["perl", "-MTemplate", "-e", "print $Template::VERSION"] + + try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True) + return { + "command_executed": " ".join(cmd), + "template_toolkit_version": result.stdout.strip(), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": "Could not determine Template Toolkit version. Is it installed?", + "stderr": e.stderr + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-template-toolkit/app/perl-template-toolkit_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-template-toolkit/app/perl-template-toolkit_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c9c7e379187426e5cba0fcbfd93a0cb4a3302697 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-template-toolkit/app/perl-template-toolkit_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-template-toolkit/app/perl-template-toolkit_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_template_toolkit' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-template-toolkit/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-template-toolkit/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-template-toolkit/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-template-toolkit/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-template-toolkit/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..af6c9ebacb43b582921847a705d6608a142fc51b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-template-toolkit/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-template-toolkit: + build: . + image: mcp-perl-template-toolkit:latest + container_name: mcp-perl-template-toolkit + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-template-toolkit + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-template-toolkit/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-template-toolkit/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5e19d174a070be83ffb76f1034d5dac835e6ea22 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-template-toolkit/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-template-toolkit + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-template-toolkit/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-template-toolkit/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-template-toolkit/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-deep/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-deep/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ae33589b1adbb38ca8215eb9e354e614f6649f03 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-deep/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-test-deep via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-test-deep -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-test-deep_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-test-deep_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-test-deep_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-deep/app/__pycache__/perl-test-deep_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-deep/app/__pycache__/perl-test-deep_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..8ff1ba799ce7cfe29053bc006058c924f16dc778 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-deep/app/__pycache__/perl-test-deep_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-deep/app/perl-test-deep_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-deep/app/perl-test-deep_server.py new file mode 100644 index 0000000000000000000000000000000000000000..868b4ff14128e1c2de8a21a44b87f7827ca1f120 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-deep/app/perl-test-deep_server.py @@ -0,0 +1,233 @@ +from typing import List, Optional +import subprocess +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_test_deep' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def perl_test_deep_run_script( + script_path: str, + arguments: Optional[List[str]] = None, + include_dirs: Optional[List[str]] = None, + modules: Optional[List[str]] = None, + warning_mode: str = "many", + taint_mode: str = "none", + syntax_check_only: bool = False, + autosplit: bool = False, + split_pattern: Optional[str] = None, + inplace_extension: Optional[str] = None, + line_ending_processing: Optional[str] = None, + loop_mode: str = "none", + unicode_features: Optional[str] = None, + no_site_customize: bool = False, + search_path: bool = False, + unsafe_operations: bool = False, + record_separator: Optional[str] = None, +): + """ + Execute a Perl script using the perl-test-deep environment. + This tool allows running complex deep comparison tests using the Test::Deep module. + + Args: + script_path: Path to the Perl script (.pl or .t) to execute. + arguments: List of command-line arguments to pass to the script. + include_dirs: List of directories to add to @INC (Perl's include path). + modules: List of additional modules to load (e.g., ["JSON", "YAML"]). Test::Deep is often loaded within the script. + warning_mode: Warning level: 'default', 'many' (-w), 'all' (-W), or 'none' (-X). + taint_mode: Taint checking: 'none', 'warnings' (-t), or 'checks' (-T). + syntax_check_only: If True, only check syntax without executing (-c). + autosplit: Enable autosplit mode (-a) with loop_mode. + split_pattern: Pattern for autosplit (-F). + inplace_extension: Edit files in place, optionally providing a backup extension (-i). + line_ending_processing: Enable line ending processing (-l). + loop_mode: Loop mode: 'none', 'n' (while(<>)), or 'p' (while(<>) { print }). + unicode_features: Enable Unicode features (-C). + no_site_customize: Don't run sitecustomize.pl at startup (-f). + search_path: Look for programfile using PATH environment variable (-S). + unsafe_operations: Allow unsafe operations (-U). + record_separator: Specify record separator (-0). + """ + # Input validation + script_file = Path(script_path) + if not script_file.exists(): + return {"error": f"Script file not found: {script_path}"} + + if warning_mode not in ["default", "many", "all", "none"]: + return {"error": "warning_mode must be one of: default, many, all, none"} + + if taint_mode not in ["none", "warnings", "checks"]: + return {"error": "taint_mode must be one of: none, warnings, checks"} + + if loop_mode not in ["none", "n", "p"]: + return {"error": "loop_mode must be one of: none, n, p"} + + # Build command + cmd = ["perl"] + + # Add switches + if warning_mode == "many": cmd.append("-w") + elif warning_mode == "all": cmd.append("-W") + elif warning_mode == "none": cmd.append("-X") + + if taint_mode == "warnings": cmd.append("-t") + elif taint_mode == "checks": cmd.append("-T") + + if syntax_check_only: cmd.append("-c") + if autosplit: cmd.append("-a") + if no_site_customize: cmd.append("-f") + if search_path: cmd.append("-S") + if unsafe_operations: cmd.append("-U") + + if record_separator is not None: cmd.append(f"-0{record_separator}") + if unicode_features is not None: cmd.append(f"-C{unicode_features}") + if split_pattern is not None: cmd.append(f"-F{split_pattern}") + if inplace_extension is not None: cmd.append(f"-i{inplace_extension}") + if line_ending_processing is not None: cmd.append(f"-l{line_ending_processing}") + + if loop_mode == "n": cmd.append("-n") + elif loop_mode == "p": cmd.append("-p") + + if include_dirs: + for d in include_dirs: + cmd.append(f"-I{d}") + + if modules: + for m in modules: + cmd.append(f"-M{m}") + + # Add script and its arguments + cmd.append(str(script_file)) + if arguments: + cmd.extend(arguments) + + 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, + "status": "error", + "exit_code": e.returncode + } + +@mcp.tool() +def perl_test_deep_one_liner( + code: str, + arguments: Optional[List[str]] = None, + include_dirs: Optional[List[str]] = None, + use_test_deep: bool = True, + warning_mode: str = "many", + autosplit: bool = False, + loop_mode: str = "none", + unicode_features: Optional[str] = None, +): + """ + Execute a Perl one-liner using the perl-test-deep environment. + Useful for quick data structure comparisons or small test snippets. + + Args: + code: The Perl code to execute. + arguments: List of command-line arguments (e.g., input files). + include_dirs: List of directories to add to @INC. + use_test_deep: Automatically load the Test::Deep module (-MTest::Deep). + warning_mode: Warning level: 'default', 'many' (-w), 'all' (-W), or 'none' (-X). + autosplit: Enable autosplit mode (-a). + loop_mode: Loop mode: 'none', 'n' (while(<>)), or 'p' (while(<>) { print }). + unicode_features: Enable Unicode features (-C). + """ + if warning_mode not in ["default", "many", "all", "none"]: + return {"error": "warning_mode must be one of: default, many, all, none"} + + if loop_mode not in ["none", "n", "p"]: + return {"error": "loop_mode must be one of: none, n, p"} + + cmd = ["perl"] + + if use_test_deep: + cmd.append("-MTest::Deep") + + if warning_mode == "many": cmd.append("-w") + elif warning_mode == "all": cmd.append("-W") + elif warning_mode == "none": cmd.append("-X") + + if autosplit: cmd.append("-a") + if loop_mode == "n": cmd.append("-n") + elif loop_mode == "p": cmd.append("-p") + if unicode_features is not None: cmd.append(f"-C{unicode_features}") + + if include_dirs: + for d in include_dirs: + cmd.append(f"-I{d}") + + cmd.extend(["-e", code]) + + if arguments: + cmd.extend(arguments) + + 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, + "status": "error", + "exit_code": e.returncode + } + +@mcp.tool() +def perl_test_deep_version_info( + verbose: bool = False, + config_variable: Optional[str] = None, +): + """ + Get version and configuration information for the Perl environment. + + Args: + verbose: If True, print configuration summary (-V). If False, print version (-v). + config_variable: Print the value of a specific configuration variable (e.g., 'installsitelib'). + """ + cmd = ["perl"] + + if config_variable: + cmd.append(f"-V:{config_variable}") + elif verbose: + cmd.append("-V") + else: + cmd.append("-v") + + 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, + "status": "error", + "exit_code": e.returncode + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-deep/app/perl-test-deep_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-deep/app/perl-test-deep_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a6349558888e76ae5c9407159877d8e5023a84ea --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-deep/app/perl-test-deep_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-deep/app/perl-test-deep_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_test_deep' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-deep/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-deep/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-deep/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-deep/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-deep/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..53ff855d2d208b1c0b0a31662cb9d9c2c2351308 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-deep/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-test-deep: + build: . + image: mcp-perl-test-deep:latest + container_name: mcp-perl-test-deep + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-test-deep + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-deep/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-deep/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f387fe381f1a634c87ef05d5e1486a6fd7dcdc8d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-deep/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-test-deep + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-deep/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-deep/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-deep/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-warn/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-warn/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a73593138358727164adccda839539106af4531e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-warn/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-test-warn via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-test-warn -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-test-warn_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-test-warn_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-test-warn_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-warn/app/__pycache__/perl-test-warn_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-warn/app/__pycache__/perl-test-warn_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..f3648a15a5d258cb06f5dc0136b732bdfe52bad3 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-warn/app/__pycache__/perl-test-warn_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-warn/app/perl-test-warn_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-warn/app/perl-test-warn_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f0d4e50c33bf88db75a4ccb66196f46af558100c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-warn/app/perl-test-warn_server.py @@ -0,0 +1,221 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_test_warn' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def perl_interpreter( + program_file: Optional[str] = None, + arguments: List[str] = [], + one_liner: Optional[str] = None, + use_all_features: bool = False, + check_syntax_only: bool = False, + modules: List[str] = ["Test::Warn"], + include_directories: List[str] = [], + warning_mode: str = "useful", + taint_checks: bool = False, + taint_warnings: bool = False, + autosplit_mode: bool = False, + split_pattern: Optional[str] = None, + inplace_edit_extension: Optional[str] = None, + loop_assume_while: bool = False, + loop_assume_while_print: bool = False, + unicode_features: Optional[str] = None, + record_separator: Optional[str] = None, + line_ending_processing: Optional[str] = None, + unsafe_operations: bool = False, + ignore_text_before_perl_line: Optional[str] = None, +): + """ + Execute Perl scripts or commands, with built-in support for the Test::Warn module. + This tool provides access to the Perl interpreter and its various switches. + + Args: + program_file: Path to the Perl script to execute. + arguments: Arguments to pass to the Perl script. + one_liner: One line of program to execute (maps to -e). + use_all_features: Like one_liner, but enables all optional features (maps to -E). + check_syntax_only: Check syntax only without executing (maps to -c). + modules: List of modules to execute 'use module' before the program (maps to -M). Defaults to ['Test::Warn']. + include_directories: List of directories to add to @INC (maps to -I). + warning_mode: Warning level: 'useful' (-w), 'all' (-W), 'none' (-X), or 'default'. + taint_checks: Enable tainting checks (maps to -T). + taint_warnings: Enable tainting warnings (maps to -t). + autosplit_mode: Enable autosplit mode with -n or -p (maps to -a). + split_pattern: Pattern for autosplit mode (maps to -F). + inplace_edit_extension: Edit files in place, optionally providing a backup extension (maps to -i). + loop_assume_while: Assume 'while (<>) { ... }' loop around program (maps to -n). + loop_assume_while_print: Assume loop like -n but print line also (maps to -p). + unicode_features: Enable listed Unicode features (maps to -C). + record_separator: Specify record separator (maps to -0). + line_ending_processing: Enable line ending processing (maps to -l). + unsafe_operations: Allow unsafe operations (maps to -U). + ignore_text_before_perl_line: Ignore text before #!perl line, optionally cd to directory (maps to -x). + """ + cmd = ["perl"] + + # Handle switches + if record_separator is not None: + cmd.append(f"-0{record_separator}") + + if autosplit_mode: + cmd.append("-a") + + if unicode_features is not None: + cmd.append(f"-C{unicode_features}") + + if check_syntax_only: + cmd.append("-c") + + if one_liner: + cmd.append("-e") + cmd.append(one_liner) + elif use_all_features: + # Note: If both are provided, -E usually takes precedence or they are used together. + # Here we treat them as mutually exclusive for the primary code input. + cmd.append("-E") + cmd.append(use_all_features if isinstance(use_all_features, str) else "") + + if split_pattern: + cmd.append(f"-F{split_pattern}") + + if inplace_edit_extension is not None: + cmd.append(f"-i{inplace_edit_extension}") + + for directory in include_directories: + cmd.append(f"-I{directory}") + + if line_ending_processing is not None: + cmd.append(f"-l{line_ending_processing}") + + for module in modules: + cmd.append(f"-M{module}") + + if loop_assume_while: + cmd.append("-n") + + if loop_assume_while_print: + cmd.append("-p") + + if taint_warnings: + cmd.append("-t") + + if taint_checks: + cmd.append("-T") + + if unsafe_operations: + cmd.append("-U") + + if warning_mode == "useful": + cmd.append("-w") + elif warning_mode == "all": + cmd.append("-W") + elif warning_mode == "none": + cmd.append("-X") + + if ignore_text_before_perl_line is not None: + cmd.append(f"-x{ignore_text_before_perl_line}") + + # Handle program file and arguments + if program_file: + prog_path = Path(program_file) + if not prog_path.exists(): + return {"error": f"Program file not found: {program_file}"} + cmd.append(str(prog_path)) + + if arguments: + cmd.extend(arguments) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def perl_version_info( + config_variable: Optional[str] = None +): + """ + Print the Perl version, patchlevel, license, or configuration summary. + + Args: + config_variable: If provided, print the value of a specific Config.pm variable (maps to -V:variable). + If None, prints version and configuration summary. + """ + if config_variable: + cmd = ["perl", f"-V:{config_variable}"] + else: + cmd = ["perl", "-V"] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def perl_test_warn_check( + test_code: str +): + """ + A specialized tool to run a snippet of Perl code specifically using Test::Warn. + This is useful for verifying if certain code blocks emit expected warnings. + + Args: + test_code: The Perl code snippet to test. It should ideally use Test::More and Test::Warn functions. + Example: 'use Test::More; use Test::Warn; warning_is { warn "foo" } "foo", "got foo warning"; done_testing();' + """ + # Ensure the code includes necessary modules if not present + if "use Test::Warn" not in test_code: + test_code = "use Test::Warn; " + test_code + if "use Test::More" not in test_code: + test_code = "use Test::More; " + test_code + if "done_testing" not in test_code: + test_code = test_code + "; done_testing();" + + cmd = ["perl", "-e", test_code] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Test failed or syntax error occurred.", + "status": "error" + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-warn/app/perl-test-warn_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-warn/app/perl-test-warn_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..077f26985c8d1f2baa6888b39e45a5a4bfd92a21 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-warn/app/perl-test-warn_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-test-warn/app/perl-test-warn_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_test_warn' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-warn/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-warn/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-warn/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-warn/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-warn/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f3db06bfdc2e1b9327248145ab86b4aa00720992 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-warn/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-test-warn: + build: . + image: mcp-perl-test-warn:latest + container_name: mcp-perl-test-warn + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-test-warn + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-warn/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-warn/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e9bf0b1afeb3a81582154c969aa1a1898395041d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-warn/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-test-warn + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-warn/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-warn/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-test-warn/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-text-parsewords/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-text-parsewords/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-text-parsewords/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-tie-ixhash/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-tie-ixhash/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3a8986669d7122c5b982c49a54fc7419ff1cc01e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-tie-ixhash/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-tie-ixhash via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-tie-ixhash -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-tie-ixhash_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-tie-ixhash_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-tie-ixhash_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-tie-ixhash/app/__pycache__/perl-tie-ixhash_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-tie-ixhash/app/__pycache__/perl-tie-ixhash_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0506c7bf039eea2c0774903ea0853c081f4385cc Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-tie-ixhash/app/__pycache__/perl-tie-ixhash_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-tie-ixhash/app/perl-tie-ixhash_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-tie-ixhash/app/perl-tie-ixhash_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3407cf4128b06524df81ef821921d3d2156df563 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-tie-ixhash/app/perl-tie-ixhash_server.py @@ -0,0 +1,248 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union +import tempfile + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_tie_ixhash' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def perl_tie_ixhash_execute( + code: str, + input_files: Optional[List[str]] = None, + use_ixhash: bool = True, + autosplit: bool = False, + split_pattern: Optional[str] = None, + inplace_extension: Optional[str] = None, + line_ending_processing: bool = False, + assume_while_loop: bool = False, + assume_print_loop: bool = False, + warnings: bool = True, + all_warnings: bool = False, + include_dirs: Optional[List[str]] = None, + unicode_features: Optional[str] = None, +) -> dict: + """ + Execute Perl code (one-liner) with Tie::IxHash support. + + Args: + code: The Perl code to execute. + input_files: List of input files to process. + use_ixhash: If True, automatically prepends 'use Tie::IxHash;' to the code. + autosplit: Enable autosplit mode with -n or -p (splits $_ into @F). + split_pattern: Pattern for autosplit (-F). + inplace_extension: Edit files in place, optionally providing a backup extension. + line_ending_processing: Enable line ending processing (-l). + assume_while_loop: Assume "while (<>) { ... }" loop around program (-n). + assume_print_loop: Assume loop like -n but print line also (-p). + warnings: Enable many useful warnings (-w). + all_warnings: Enable all warnings (-W). + include_dirs: List of directories to add to @INC. + unicode_features: Enable listed Unicode features (-C). + """ + cmd = ["perl"] + + # Handle flags + if unicode_features: + cmd.append(f"-C{unicode_features}") + if warnings: + cmd.append("-w") + if all_warnings: + cmd.append("-W") + if autosplit: + cmd.append("-a") + if split_pattern: + cmd.append(f"-F{split_pattern}") + if inplace_extension is not None: + cmd.append(f"-i{inplace_extension}") + if line_ending_processing: + cmd.append("-l") + if assume_while_loop: + cmd.append("-n") + if assume_print_loop: + cmd.append("-p") + + if include_dirs: + for d in include_dirs: + cmd.append(f"-I{d}") + + # Prepare code + final_code = code + if use_ixhash: + final_code = "use Tie::IxHash; " + code + + cmd.extend(["-e", final_code]) + + # Handle input files + if input_files: + for f in input_files: + path = Path(f) + if not path.exists(): + return {"error": f"Input file not found: {f}"} + cmd.append(str(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": "error" + } + +@mcp.tool() +def perl_tie_ixhash_run_script( + script_path: str, + args: Optional[List[str]] = None, + warnings: bool = True, + include_dirs: Optional[List[str]] = None, + taint_checks: bool = False, +) -> dict: + """ + Run a Perl script file that utilizes Tie::IxHash. + + Args: + script_path: Path to the Perl script (.pl). + args: Arguments to pass to the script. + warnings: Enable warnings (-w). + include_dirs: List of directories to add to @INC. + taint_checks: Enable tainting checks (-T). + """ + path = Path(script_path) + if not path.exists(): + return {"error": f"Script file not found: {script_path}"} + + cmd = ["perl"] + + if warnings: + cmd.append("-w") + if taint_checks: + cmd.append("-T") + if include_dirs: + for d in include_dirs: + cmd.append(f"-I{d}") + + cmd.append(str(path)) + + if args: + cmd.extend(args) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def perl_tie_ixhash_check_syntax( + script_path: str, + include_dirs: Optional[List[str]] = None, +) -> dict: + """ + Check the syntax of a Perl script without executing it. + + Args: + script_path: Path to the Perl script. + include_dirs: List of directories to add to @INC. + """ + path = Path(script_path) + if not path.exists(): + return {"error": f"Script file not found: {script_path}"} + + cmd = ["perl", "-c"] + if include_dirs: + for d in include_dirs: + cmd.append(f"-I{d}") + cmd.append(str(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": "syntax_ok" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Syntax check failed", + "status": "syntax_error" + } + +@mcp.tool() +def perl_tie_ixhash_version_info() -> dict: + """ + Get Perl version and configuration information. + """ + try: + # Get basic version + v_result = subprocess.run(["perl", "-v"], capture_output=True, text=True, check=True) + # Check if Tie::IxHash is actually installed and get its version + ix_check = subprocess.run( + ["perl", "-MTie::IxHash", "-e", "print $Tie::IxHash::VERSION"], + capture_output=True, text=True + ) + + return { + "perl_version": v_result.stdout, + "tie_ixhash_version": ix_check.stdout if ix_check.returncode == 0 else "Not found", + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "error": str(e), + "stderr": e.stderr, + "status": "error" + } + +@mcp.tool() +def perl_tie_ixhash_example_usage() -> dict: + """ + Returns a code example showing how to use Tie::IxHash in Perl. + """ + example_code = """ +use Tie::IxHash; + +# Tie a hash to Tie::IxHash to maintain insertion order +tie my %hash, 'Tie::IxHash'; + +$hash{first} = 1; +$hash{second} = 2; +$hash{third} = 3; + +# Keys will be printed in the order they were inserted +foreach my $key (keys %hash) { + print "$key: $hash{$key}\\n"; +} +""" + return { + "example_perl_code": example_code, + "description": "This example demonstrates how to maintain key order in a Perl hash using Tie::IxHash." + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-tie-ixhash/app/perl-tie-ixhash_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-tie-ixhash/app/perl-tie-ixhash_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..867910fce3a76b5638a287f791f160983889b684 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-tie-ixhash/app/perl-tie-ixhash_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-tie-ixhash/app/perl-tie-ixhash_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_tie_ixhash' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-tie-ixhash/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-tie-ixhash/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-tie-ixhash/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-tie-ixhash/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-tie-ixhash/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..555921a48b6e71df18ab1dea8a8fd96c8061e171 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-tie-ixhash/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-tie-ixhash: + build: . + image: mcp-perl-tie-ixhash:latest + container_name: mcp-perl-tie-ixhash + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-tie-ixhash + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-tie-ixhash/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-tie-ixhash/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1f7a590267a8087d582178dbca6a214ab59f88e8 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-tie-ixhash/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-tie-ixhash + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-tie-ixhash/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-tie-ixhash/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-tie-ixhash/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-www-robotrules/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-www-robotrules/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..25a0db90f0ee86f710258070adcbaecd574ff13d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-www-robotrules/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-www-robotrules via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-www-robotrules -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-www-robotrules_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-www-robotrules_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-www-robotrules_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-www-robotrules/app/__pycache__/perl-www-robotrules_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-www-robotrules/app/__pycache__/perl-www-robotrules_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e60c6537570f54799f1c0542cdf5bc911bcf95e7 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-www-robotrules/app/__pycache__/perl-www-robotrules_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-www-robotrules/app/perl-www-robotrules_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-www-robotrules/app/perl-www-robotrules_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b1716d8359a5fcd8a033bf5995e97322d0d41665 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-www-robotrules/app/perl-www-robotrules_server.py @@ -0,0 +1,189 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_www_robotrules' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def check_robots_url_allowed( + robots_txt_content: str, + user_agent: str, + url_to_check: str, + base_url: str = "http://localhost", +) -> Dict[str, Any]: + """ + Checks if a specific URL is allowed for a given user agent based on robots.txt content + using the Perl WWW::RobotRules module. + + Args: + robots_txt_content: The raw text content of the robots.txt file. + user_agent: The name of the robot/user-agent to check (e.g., 'Googlebot'). + url_to_check: The full URL or path to check for access permissions. + base_url: The base URL where the robots.txt is hosted (required by the parser). + """ + # Input validation + if not robots_txt_content.strip(): + return {"error": "robots_txt_content cannot be empty"} + if not user_agent.strip(): + return {"error": "user_agent cannot be empty"} + if not url_to_check.strip(): + return {"error": "url_to_check cannot be empty"} + + # Create a temporary file for the robots.txt content to avoid shell escaping issues + with tempfile.NamedTemporaryFile(mode='w', suffix='.txt', delete=False) as tmp: + tmp.write(robots_txt_content) + tmp_path = tmp.name + + # Construct the Perl script + # WWW::RobotRules->new($ua_name) + # $rules->parse($base_url, $content) + # $rules->allowed($url) + perl_script = f""" +use WWW::RobotRules; +my $ua = '{user_agent}'; +my $base = '{base_url}'; +my $url = '{url_to_check}'; +my $rules = WWW::RobotRules->new($ua); + +open(my $fh, '<', '{tmp_path}') or die "Could not open temp file: $!"; +my $content = do {{ local $/; <$fh> }}; +close($fh); + +$rules->parse($base, $content); +if ($rules->allowed($url)) {{ + print "ALLOWED"; +}} else {{ + print "DISALLOWED"; +}} +""" + + try: + result = subprocess.run( + ["perl", "-e", perl_script], + capture_output=True, + text=True, + check=True + ) + + is_allowed = result.stdout.strip() == "ALLOWED" + + return { + "command_executed": f"perl -e 'WWW::RobotRules->allowed(...)'", + "is_allowed": is_allowed, + "status": result.stdout.strip(), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "Perl execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd + } + finally: + # Cleanup + if Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def check_robots_url_allowed_from_file( + robots_txt_path: str, + user_agent: str, + url_to_check: str, + base_url: str = "http://localhost", +) -> Dict[str, Any]: + """ + Checks if a specific URL is allowed for a given user agent using a local robots.txt file. + + Args: + robots_txt_path: Path to the local robots.txt file. + user_agent: The name of the robot/user-agent to check. + url_to_check: The full URL or path to check for access permissions. + base_url: The base URL where the robots.txt is conceptually hosted. + """ + path_obj = Path(robots_txt_path) + if not path_obj.exists(): + return {"error": f"File not found: {robots_txt_path}"} + + try: + content = path_obj.read_text() + return check_robots_url_allowed( + robots_txt_content=content, + user_agent=user_agent, + url_to_check=url_to_check, + base_url=base_url + ) + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def get_robots_txt_agent_string( + user_agent: str +) -> Dict[str, Any]: + """ + Returns the agent string that the WWW::RobotRules parser will use for identification. + This is useful for verifying how the Perl module identifies your crawler. + + Args: + user_agent: The name of the robot/user-agent. + """ + perl_script = f""" +use WWW::RobotRules; +my $rules = WWW::RobotRules->new('{user_agent}'); +print $rules->agent(); +""" + try: + result = subprocess.run( + ["perl", "-e", perl_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": "perl -e 'WWW::RobotRules->agent()'", + "agent_string": result.stdout.strip(), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "Perl execution failed", + "stderr": e.stderr + } + +@mcp.tool() +def validate_perl_robotrules_environment() -> Dict[str, Any]: + """ + Verifies that Perl and the WWW::RobotRules module are correctly installed in the environment. + """ + perl_script = "use WWW::RobotRules; print 'OK';" + try: + result = subprocess.run( + ["perl", "-e", perl_script], + capture_output=True, + text=True, + check=True + ) + return { + "status": "Ready", + "module_found": result.stdout.strip() == "OK", + "perl_version": subprocess.run(["perl", "-v"], capture_output=True, text=True).stdout.splitlines()[1] + } + except subprocess.CalledProcessError: + return { + "status": "Error", + "message": "WWW::RobotRules module not found. Please install perl-www-robotrules." + } + except FileNotFoundError: + return { + "status": "Error", + "message": "Perl interpreter not found in PATH." + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-www-robotrules/app/perl-www-robotrules_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-www-robotrules/app/perl-www-robotrules_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2c16f77e2626502b508a4623a419311667d66997 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-www-robotrules/app/perl-www-robotrules_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-www-robotrules/app/perl-www-robotrules_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_www_robotrules' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-www-robotrules/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-www-robotrules/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-www-robotrules/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-www-robotrules/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-www-robotrules/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e92d138122bf09afea98701d4914441bb0abd469 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-www-robotrules/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-www-robotrules: + build: . + image: mcp-perl-www-robotrules:latest + container_name: mcp-perl-www-robotrules + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-www-robotrules + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-www-robotrules/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-www-robotrules/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ec69db11a386bcf3fea1cf062fd0d0117813066c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-www-robotrules/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-www-robotrules + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-www-robotrules/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-www-robotrules/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-www-robotrules/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-expat/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-expat/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..325d6d7aaefdf66c54c95e360bb5fc54ba8f3535 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-expat/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-xml-sax-expat via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-xml-sax-expat -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-xml-sax-expat_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-xml-sax-expat_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-xml-sax-expat_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-expat/app/__pycache__/perl-xml-sax-expat_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-expat/app/__pycache__/perl-xml-sax-expat_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0100afaea097e68da0b7f629ea466e5cc95c5d4b Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-expat/app/__pycache__/perl-xml-sax-expat_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-expat/app/perl-xml-sax-expat_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-expat/app/perl-xml-sax-expat_server.py new file mode 100644 index 0000000000000000000000000000000000000000..219166442a70b1e6cec579608f5995418ceb7531 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-expat/app/perl-xml-sax-expat_server.py @@ -0,0 +1,247 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union + +# Helper function for validating directory existence +def _validate_dir_exists(path: Path, param_name: str): + """Validates that a given path exists and is a directory.""" + if not path.exists(): + raise ValueError(f"Error: {param_name} '{path}' does not exist.") + if not path.is_dir(): + raise ValueError(f"Error: {param_name} '{path}' is not a directory.") + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_xml_sax_expat' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_perl_script( + program_file: Optional[Path] = None, + program_line: Optional[List[str]] = None, + program_line_extended: Optional[List[str]] = None, + script_arguments: Optional[List[str]] = None, + record_separator_octal: Optional[str] = None, + autosplit_mode: bool = False, + unicode_features: Optional[str] = None, + check_syntax_only: bool = False, + debugger: Optional[str] = None, + debugging_flags: Optional[str] = None, + no_sitecustomize: bool = False, + split_pattern: Optional[str] = None, + edit_in_place_extension: Optional[str] = None, + include_directories: Optional[List[Path]] = None, + line_ending_processing: Optional[str] = None, + module_operations: Optional[List[str]] = None, + assume_loop_no_print: bool = False, + assume_loop_and_print: bool = False, + rudimentary_switch_parsing: bool = False, + look_for_programfile_in_path: bool = False, + tainting_warnings: bool = False, + tainting_checks: bool = False, + dump_core_after_parsing: bool = False, + allow_unsafe_operations: bool = False, + print_version: bool = False, + print_config_summary: Optional[str] = None, + enable_warnings: bool = False, + enable_all_warnings: bool = False, + ignore_text_before_shebang_dir: Optional[Path] = None, + disable_all_warnings: bool = False, + pass_dash_dash: bool = False, +) -> dict: + """ + Executes a Perl script or one-liner with various command-line options. + + This tool provides an interface to the Perl interpreter, allowing users to run + Perl programs, check syntax, enable debugging, manage warnings, and more. + It supports all the standard command-line switches available with the `perl` + executable. + + Args: + program_file (Optional[Path]): Path to the Perl script file to execute. + Cannot be used with `program_line` or `program_line_extended`. + program_line (Optional[List[str]]): One or more lines of program code to execute. + Equivalent to multiple `-e` switches. + program_line_extended (Optional[List[str]]): One or more lines of program code to execute, + enabling all optional features. Equivalent to multiple `-E` switches. + script_arguments (Optional[List[str]]): Arguments to be passed to the Perl script. + record_separator_octal (Optional[str]): Specifies the input record separator. + If no argument, defaults to `\0`. (e.g., "0", "0777") + autosplit_mode (bool): Enables autosplit mode with -n or -p (splits $_ into @F). Equivalent to `-a`. + unicode_features (Optional[str]): Enables listed Unicode features. (e.g., "all", "io") Equivalent to `-C`. + check_syntax_only (bool): Checks syntax only (runs BEGIN and CHECK blocks). Equivalent to `-c`. + debugger (Optional[str]): Runs program under debugger. Optionally specify debugger name. Equivalent to `-d[:debugger]`. + debugging_flags (Optional[str]): Sets debugging flags (argument is a bit mask or alphabets). Equivalent to `-D`. + no_sitecustomize (bool): Don't do $sitelib/sitecustomize.pl at startup. Equivalent to `-f`. + split_pattern (Optional[str]): `split()` pattern for -a switch. (e.g., "/\s+/") Equivalent to `-F`. + edit_in_place_extension (Optional[str]): Edits <> files in place. Makes backup if extension supplied. + (e.g., ".bak") Equivalent to `-i[extension]`. + include_directories (Optional[List[Path]]): Specifies @INC/#include directories. Equivalent to multiple `-I`. + line_ending_processing (Optional[str]): Enables line ending processing, specifies line terminator. + (e.g., "012" for newline) Equivalent to `-l[octal]`. + module_operations (Optional[List[str]]): Executes "use/no module..." before executing program. + Each string should be in the format "m:Module", "M:Module", + "m-:Module", or "M-:Module". (e.g., ["m:XML::SAX::Expat", "M-:strict"]) + assume_loop_no_print (bool): Assumes "while (<>) { ... }" loop around program. Equivalent to `-n`. + assume_loop_and_print (bool): Assumes loop like -n but prints line also, like sed. Equivalent to `-p`. + rudimentary_switch_parsing (bool): Enables rudimentary parsing for switches after programfile. Equivalent to `-s`. + look_for_programfile_in_path (bool): Looks for programfile using PATH environment variable. Equivalent to `-S`. + tainting_warnings (bool): Enables tainting warnings. Equivalent to `-t`. + tainting_checks (bool): Enables tainting checks. Equivalent to `-T`. + dump_core_after_parsing (bool): Dumps core after parsing program. Equivalent to `-u`. + allow_unsafe_operations (bool): Allows unsafe operations. Equivalent to `-U`. + print_version (bool): Prints version, patchlevel and license. Equivalent to `-v`. + print_config_summary (Optional[str]): Prints configuration summary. Optionally specify a Config.pm variable. + (e.g., "archname") Equivalent to `-V[:variable]`. + enable_warnings (bool): Enables many useful warnings. Equivalent to `-w`. + enable_all_warnings (bool): Enables all warnings. Equivalent to `-W`. + ignore_text_before_shebang_dir (Optional[Path]): Ignores text before #!perl line. + Optionally change directory to the specified path. + Equivalent to `-x[directory]`. + disable_all_warnings (bool): Disables all warnings. Equivalent to `-X`. + pass_dash_dash (bool): Explicitly passes '--' before the program file or script arguments. + Useful if script arguments might be mistaken for Perl options. + + Returns: + dict: A dictionary containing the command executed, stdout, stderr, and any output files. + Includes an 'error' key if the execution fails. + """ + command: List[str] = ["perl"] + output_files: List[Path] = [] + + # Input validation + if program_file: + if not program_file.is_file(): + raise ValueError(f"Error: Program file '{program_file}' does not exist or is not a file.") + if program_line or program_line_extended: + raise ValueError("Cannot specify both a program file and a one-liner (-e or -E).") + elif not (program_line or program_line_extended): + # If no program_file, at least one of program_line or program_line_extended must be provided + # to prevent perl from hanging waiting for STDIN, unless -v or -V is used. + if not (print_version or print_config_summary is not None): + raise ValueError("Either a 'program_file' or 'program_line'/'program_line_extended' must be provided.") + + if assume_loop_no_print and assume_loop_and_print: + raise ValueError("Cannot use both -n (assume loop, no print) and -p (assume loop, print line).") + if enable_warnings and enable_all_warnings: + raise ValueError("Cannot use both -w (enable warnings) and -W (enable all warnings). -W implies -w.") + if (enable_warnings or enable_all_warnings) and disable_all_warnings: + raise ValueError("Cannot enable warnings (-w or -W) and disable all warnings (-X) simultaneously.") + + # Add switches + if record_separator_octal is not None: + command.append(f"-0{record_separator_octal}") + if autosplit_mode: + command.append("-a") + if unicode_features is not None: + command.append(f"-C{unicode_features}") + if check_syntax_only: + command.append("-c") + if debugger is not None: + command.append(f"-d:{debugger}" if debugger else "-d") + if debugging_flags is not None: + command.append(f"-D{debugging_flags}") + if program_line: + for line in program_line: + command.extend(["-e", line]) + if program_line_extended: + for line in program_line_extended: + command.extend(["-E", line]) + if no_sitecustomize: + command.append("-f") + if split_pattern is not None: + command.append(f"-F{split_pattern}") + if edit_in_place_extension is not None: + command.append(f"-i{edit_in_place_extension}") + if include_directories: + for directory in include_directories: + _validate_dir_exists(directory, "include_directory") + command.extend(["-I", str(directory)]) + if line_ending_processing is not None: + command.append(f"-l{line_ending_processing}") + if module_operations: + for op in module_operations: + # Validate format: e.g., "m:MyModule", "M-:AnotherModule" + if not (op.startswith("m:") or op.startswith("M:") or op.startswith("m-:") or op.startswith("M-:")): + raise ValueError(f"Invalid module operation format: '{op}'. Expected 'm:Module', 'M:Module', 'm-:Module', or 'M-:Module'.") + # Reconstruct the command-line argument, e.g., "-mMyModule" or "-M-AnotherModule" + prefix, module_name = op.split(':', 1) + command.append(f"-{prefix}{module_name}") + if assume_loop_no_print: + command.append("-n") + if assume_loop_and_print: + command.append("-p") + if rudimentary_switch_parsing: + command.append("-s") + if look_for_programfile_in_path: + command.append("-S") + if tainting_warnings: + command.append("-t") + if tainting_checks: + command.append("-T") + if dump_core_after_parsing: + command.append("-u") + if allow_unsafe_operations: + command.append("-U") + if print_version: + command.append("-v") + if print_config_summary is not None: + command.append(f"-V:{print_config_summary}" if print_config_summary else "-V") + if enable_warnings: + command.append("-w") + if enable_all_warnings: + command.append("-W") + if ignore_text_before_shebang_dir is not None: + _validate_dir_exists(ignore_text_before_shebang_dir, "ignore_text_before_shebang_dir") + command.append(f"-x{ignore_text_before_shebang_dir}") + if disable_all_warnings: + command.append("-X") + + # Add '--' if explicitly requested or if there are script arguments and no program file + # (perl handles '--' implicitly if program_file is present and followed by args) + if pass_dash_dash or (not program_file and script_arguments): + command.append("--") + + # Add program file + if program_file: + command.append(str(program_file)) + + # Add script arguments + if script_arguments: + command.extend(script_arguments) + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": f"Perl execution failed with exit code {e.returncode}" + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: 'perl' command not found. Please ensure Perl is installed and in your PATH.", + "output_files": [], + "error": "Perl executable not found." + } + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-expat/app/perl-xml-sax-expat_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-expat/app/perl-xml-sax-expat_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a938f4f8edbbd7efc420bc404a8cffc3ab3d315f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-expat/app/perl-xml-sax-expat_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax-expat/app/perl-xml-sax-expat_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_xml_sax_expat' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-expat/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-expat/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-expat/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-expat/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-expat/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d3b51fb674174e9235b018006ee4892f07d30790 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-expat/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-xml-sax-expat: + build: . + image: mcp-perl-xml-sax-expat:latest + container_name: mcp-perl-xml-sax-expat + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-xml-sax-expat + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-expat/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-expat/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..70e8590d3eba26bd879d43a6396d2118f1236dcf --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-expat/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-xml-sax-expat + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-expat/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-expat/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax-expat/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4887ed827bf3a2f9a9288486a11851eb2da8963a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-xml-sax via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-xml-sax -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-xml-sax_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-xml-sax_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-xml-sax_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax/app/__pycache__/perl-xml-sax_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax/app/__pycache__/perl-xml-sax_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5f8fe501a98eb6d0118645e6fb3b3862149274ae Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax/app/__pycache__/perl-xml-sax_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax/app/perl-xml-sax_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax/app/perl-xml-sax_server.py new file mode 100644 index 0000000000000000000000000000000000000000..55d0dffa0fef3acba5e1f4fb2c99d04c7889ca1e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax/app/perl-xml-sax_server.py @@ -0,0 +1,206 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_xml_sax' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def xml_sax_list_parsers() -> Dict[str, Any]: + """ + Get a list of all known/registered XML SAX parsers on the system. + This corresponds to the XML::SAX->parsers() method. + """ + # Perl one-liner to dump the parsers list using Data::Dumper for structured output + perl_cmd = [ + "perl", "-MXML::SAX", "-MData::Dumper", "-e", + "$Data::Dumper::Terse = 1; $Data::Dumper::Indent = 1; print Dumper(XML::SAX->parsers())" + ] + + try: + result = subprocess.run(perl_cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(perl_cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(perl_cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def xml_sax_add_parser(module_name: str) -> Dict[str, Any]: + """ + Register a new SAX parser module in the system's ParserDetails.ini. + + Args: + module_name: The Perl module name of the parser (e.g., 'XML::SAX::PurePerl' or 'XML::LibXML::SAX') + """ + if not module_name: + raise ValueError("module_name must be provided") + + # Perl one-liner to add the parser and save the configuration + perl_cmd = [ + "perl", "-MXML::SAX", "-e", + f"XML::SAX->add_parser(q({module_name}))->save_parsers()" + ] + + try: + result = subprocess.run(perl_cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(perl_cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "message": f"Successfully added and saved parser: {module_name}", + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(perl_cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def xml_sax_remove_parser(module_name: str) -> Dict[str, Any]: + """ + Remove a registered SAX parser module from the system's configuration. + + Args: + module_name: The Perl module name of the parser to remove. + """ + if not module_name: + raise ValueError("module_name must be provided") + + # Perl one-liner to remove the parser and save the configuration + perl_cmd = [ + "perl", "-MXML::SAX", "-e", + f"XML::SAX->remove_parser(q({module_name}))->save_parsers()" + ] + + try: + result = subprocess.run(perl_cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(perl_cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "message": f"Successfully removed and saved parser: {module_name}", + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(perl_cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def xml_sax_save_parsers() -> Dict[str, Any]: + """ + Explicitly save the current state of registered parsers to the ParserDetails.ini file. + """ + perl_cmd = ["perl", "-MXML::SAX", "-e", "XML::SAX->save_parsers()"] + + try: + result = subprocess.run(perl_cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(perl_cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "message": "Parser configuration saved successfully.", + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(perl_cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def xml_sax_parse_validate( + xml_file: str, + parser_package: Optional[str] = None +) -> Dict[str, Any]: + """ + Validate an XML file using a SAX parser to check for well-formedness. + + Args: + xml_file: Path to the XML file to be parsed. + parser_package: Optional specific SAX parser package to use (e.g., 'XML::SAX::PurePerl'). + If not provided, the system default is used. + """ + file_path = Path(xml_file) + if not file_path.exists(): + return {"error": f"File not found: {xml_file}", "status": "error"} + + # Construct the Perl script + # We use XML::SAX::ParserFactory to get a parser and parse the file. + # If parser_package is specified, we set $XML::SAX::ParserPackage. + perl_script = "use XML::SAX::ParserFactory; " + if parser_package: + perl_script += f"$XML::SAX::ParserPackage = q({parser_package}); " + + perl_script += ( + "my $p = XML::SAX::ParserFactory->parser(); " + "eval { $p->parse_uri($ARGV[0]) }; " + "if ($@) { print STDERR $@; exit 1 } else { print 'OK' }" + ) + + perl_cmd = ["perl", "-e", perl_script, str(file_path)] + + try: + result = subprocess.run(perl_cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(perl_cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "result": "File is well-formed" if "OK" in result.stdout else "Unknown status", + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(perl_cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "XML Parsing Error: " + e.stderr, + "status": "error" + } + +@mcp.tool() +def xml_sax_get_version() -> Dict[str, Any]: + """ + Check the installed version of the XML::SAX Perl module. + """ + perl_cmd = ["perl", "-MXML::SAX", "-e", "print $XML::SAX::VERSION"] + + try: + result = subprocess.run(perl_cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(perl_cmd), + "version": result.stdout.strip(), + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(perl_cmd), + "error": str(e), + "status": "error" + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax/app/perl-xml-sax_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax/app/perl-xml-sax_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..11e102a2f323db2674a15784c5a671cc63be8a40 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax/app/perl-xml-sax_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-sax/app/perl-xml-sax_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_xml_sax' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..08990f858f048c9465a67efc3e850e3d8e134db7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-xml-sax: + build: . + image: mcp-perl-xml-sax:latest + container_name: mcp-perl-xml-sax + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-xml-sax + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8f5ca6e94667ae6113c1d9501f6e64772d540fb6 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-xml-sax + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-sax/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-twig/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-twig/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3c5a84cbc0dbd89c282399543b082a022a7e379e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-twig/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install perl-xml-twig via conda (e.g., from bioconda) +RUN conda install -c bioconda perl-xml-twig -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/perl-xml-twig_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/perl-xml-twig_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/perl-xml-twig_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-twig/app/__pycache__/perl-xml-twig_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-twig/app/__pycache__/perl-xml-twig_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5c406ae440040ab78de5ce087bdeaac8a6014538 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-twig/app/__pycache__/perl-xml-twig_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-twig/app/perl-xml-twig_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-twig/app/perl-xml-twig_server.py new file mode 100644 index 0000000000000000000000000000000000000000..89e2b7caeeb1eccdebed5d2650dc587e458b0366 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-twig/app/perl-xml-twig_server.py @@ -0,0 +1,321 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_perl_xml_twig' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def xml_pp( + input_files: List[str], + style: str = "indented", + in_place_ext: Optional[str] = None, + encoding: Optional[str] = None, + preserve_white_spaces: bool = False, + load_dtd: bool = False, + verbose: bool = False, +) -> dict: + """ + XML pretty printer using XML::Twig. + + Args: + input_files: List of XML files to process. + style: Output style (indented, record, record_c, indented_a, none, nsgmls, smgl, cvs). + in_place_ext: If provided, edit files in place and use this extension for backups (e.g., '.bak'). + encoding: Output encoding. + preserve_white_spaces: If True, preserve white spaces. + load_dtd: If True, load the DTD. + verbose: Enable verbose output. + """ + cmd = ["xml_pp"] + + # Style validation + valid_styles = ["indented", "record", "record_c", "indented_a", "none", "nsgmls", "smgl", "cvs"] + if style not in valid_styles: + style = "indented" + cmd.extend(["-s", style]) + + if in_place_ext is not None: + cmd.append(f"-i{in_place_ext}") + + if encoding: + cmd.extend(["-e", encoding]) + + if preserve_white_spaces: + cmd.append("-p") + + if load_dtd: + cmd.append("-l") + + if verbose: + cmd.append("-v") + + # File validation + validated_files = [] + for f in input_files: + path = Path(f) + if not path.exists(): + return {"error": f"Input file not found: {f}"} + validated_files.append(str(path)) + + cmd.extend(validated_files) + + 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": validated_files if in_place_ext else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def xml_grep( + xpath: str, + input_files: List[str], + root: Optional[str] = None, + wrap: Optional[str] = None, + nowrap: bool = False, + descr: Optional[str] = None, + cond: Optional[str] = None, + count: bool = False, + files_with_matches: bool = False, + files_without_matches: bool = False, + pretty_print: Optional[str] = None, + text_only: bool = False, + html: bool = False, + encoding: Optional[str] = None, +) -> dict: + """ + Grep-like utility for XML files using XPath expressions. + + Args: + xpath: The XPath expression to search for. + input_files: List of XML files to search. + root: Look for matches under this root. + wrap: Wrap the results in this tag. + nowrap: Do not wrap the results. + descr: Add a description tag. + cond: Additional condition (XPath). + count: Only print the count of matches. + files_with_matches: Only print filenames of files containing matches. + files_without_matches: Only print filenames of files NOT containing matches. + pretty_print: Pretty print the output using this style. + text_only: Output only the text content of matches. + html: Input is HTML. + encoding: Input/Output encoding. + """ + cmd = ["xml_grep"] + + if root: + cmd.extend(["--root", root]) + if wrap: + cmd.extend(["--wrap", wrap]) + if nowrap: + cmd.append("--nowrap") + if descr: + cmd.extend(["--descr", descr]) + if cond: + cmd.extend(["--cond", cond]) + if count: + cmd.append("--count") + if files_with_matches: + cmd.append("--files-with-matches") + if files_without_matches: + cmd.append("--files-without-matches") + if pretty_print: + cmd.extend(["--pretty_print", pretty_print]) + if text_only: + cmd.append("--text_only") + if html: + cmd.append("--html") + if encoding: + cmd.extend(["--encoding", encoding]) + + cmd.append(xpath) + + # File validation + validated_files = [] + for f in input_files: + path = Path(f) + if not path.exists(): + return {"error": f"Input file not found: {f}"} + validated_files.append(str(path)) + + cmd.extend(validated_files) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + 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 xml_split( + input_file: str, + level: Optional[int] = None, + condition: Optional[str] = None, + size: Optional[str] = None, + max_files: Optional[int] = None, + base_name: Optional[str] = None, + verbose: bool = False, +) -> dict: + """ + Split an XML file into several smaller files. + + Args: + input_file: The XML file to split. + level: Split at this level (depth). + condition: Split at elements matching this XPath condition. + size: Split into files of approximately this size (e.g., '1Mb', '500Kb'). + max_files: Maximum number of files to create. + base_name: Base name for the output files. + verbose: Enable verbose output. + """ + path = Path(input_file) + if not path.exists(): + return {"error": f"Input file not found: {input_file}"} + + cmd = ["xml_split"] + + if level is not None: + cmd.extend(["-l", str(level)]) + if condition: + cmd.extend(["-c", condition]) + if size: + cmd.extend(["-s", size]) + if max_files is not None: + cmd.extend(["-n", str(max_files)]) + if base_name: + cmd.extend(["-b", base_name]) + if verbose: + cmd.append("-v") + + cmd.append(str(path)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + # xml_split creates files in the current directory or based on base_name + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "info": "Check the current directory for generated XML chunks and the master file." + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def xml_merge( + input_file: str, + output_file: Optional[str] = None, + verbose: bool = False, +) -> dict: + """ + Merge XML files split by xml_split. + + Args: + input_file: The master XML file (usually file-main.xml) created by xml_split. + output_file: Name of the merged output file. If not provided, prints to stdout. + verbose: Enable verbose output. + """ + path = Path(input_file) + if not path.exists(): + return {"error": f"Master input file not found: {input_file}"} + + cmd = ["xml_merge"] + + if output_file: + cmd.extend(["-o", output_file]) + if verbose: + cmd.append("-v") + + cmd.append(str(path)) + + 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] if output_file else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def xml_spellcheck( + input_files: List[str], + conf: Optional[str] = None, + pretty_print: str = "indented", +) -> dict: + """ + Spellcheck the text content of XML files. + + Args: + input_files: List of XML files to spellcheck. + conf: Configuration file for the spellchecker. + pretty_print: Pretty print style for the output. + """ + cmd = ["xml_spellcheck"] + + if conf: + cmd.extend(["--conf", conf]) + + cmd.extend(["--pretty_print", pretty_print]) + + # File validation + validated_files = [] + for f in input_files: + path = Path(f) + if not path.exists(): + return {"error": f"Input file not found: {f}"} + validated_files.append(str(path)) + + cmd.extend(validated_files) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + 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 + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-twig/app/perl-xml-twig_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-twig/app/perl-xml-twig_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..63b6d7f83a34f07dbf19351065238deeb569552d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-twig/app/perl-xml-twig_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_perl-xml-twig/app/perl-xml-twig_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_perl_xml_twig' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-twig/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-twig/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-twig/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-twig/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-twig/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..88e6d4d1be0a8cf53c6d56a131ad026dd93d5dfd --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-twig/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-perl-xml-twig: + build: . + image: mcp-perl-xml-twig:latest + container_name: mcp-perl-xml-twig + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=perl-xml-twig + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-twig/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-twig/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8bfafe49d7f1dce26cdce59fb037b414f9fb12c4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-twig/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - perl-xml-twig + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-twig/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-twig/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_perl-xml-twig/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_piaso/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_piaso/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3fcf7f14a1e768a779061976ecc81a39fa2a872b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_piaso/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install piaso via conda (e.g., from bioconda) +RUN conda install -c bioconda piaso -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/piaso_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/piaso_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/piaso_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_piaso/app/__pycache__/piaso_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_piaso/app/__pycache__/piaso_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..069204bbb0ac96e9907d9e55eed8e5ac396bdf07 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_piaso/app/__pycache__/piaso_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_piaso/app/piaso_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_piaso/app/piaso_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2f659011296429173d719e1d868a245baa1a2f7d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_piaso/app/piaso_server.py @@ -0,0 +1,192 @@ +import subprocess +import logging +from pathlib import Path +from typing import List, Optional + +# Configure logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +# @mcp.tool decorator is assumed to be available in the execution environment. + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_piaso' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def piaso_integrate( + input_adata: Path, + output_adata: Path, + batch_key: str = "batch", + n_dims: int = 30, + k_neigh: int = 15, + n_epochs: int = 100, +) -> dict: + """ + Integrates multiple single-cell datasets from an AnnData file using a hypothetical + PIASO 'integrate' command, likely based on its GDR (Geometric Sketching) method. + + This function wraps a non-existent CLI for the piaso library. + + Args: + input_adata (Path): Path to the input AnnData file (.h5ad) containing unintegrated data. + output_adata (Path): Path to save the output AnnData file with the integrated embedding. + batch_key (str): The column key in the .obs AnnData attribute that identifies the batch for each cell. + Defaults to 'batch'. + n_dims (int): The dimensionality of the integrated embedding space. Defaults to 30. + k_neigh (int): The number of neighbors to use for constructing the k-nearest neighbors graph. + Defaults to 15. + n_epochs (int): The number of epochs for the integration model training. Defaults to 100. + + Returns: + dict: A dictionary containing the executed command, stdout, stderr, and the path to the output file. + """ + # --- Input Validation --- + if not input_adata.is_file(): + raise FileNotFoundError(f"Input file not found: {input_adata}") + if n_dims <= 0: + raise ValueError("n_dims must be a positive integer.") + if k_neigh <= 0: + raise ValueError("k_neigh must be a positive integer.") + if n_epochs <= 0: + raise ValueError("n_epochs must be a positive integer.") + + output_adata.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + # This assumes a hypothetical CLI: `piaso integrate [options]` + cmd = [ + "piaso", "integrate", + str(input_adata), + str(output_adata), + "--batch-key", batch_key, + "--n-dims", str(n_dims), + "--k-neigh", str(k_neigh), + "--n-epochs", str(n_epochs), + ] + + command_executed = " ".join(cmd) + logger.info(f"Executing command: {command_executed}") + + # --- Subprocess Execution --- + try: + # Since 'piaso' is a library without a CLI, this call is expected to fail. + # The code demonstrates the correct wrapping pattern if a CLI were available. + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + stdout = process.stdout + stderr = process.stderr + except FileNotFoundError: + # This is the most likely error because the `piaso` executable doesn't exist. + stdout = "" + stderr = ( + "FileNotFoundError: 'piaso' command not found. " + "This is expected as piaso is a Python library without a native CLI. " + "This MCP tool is based on a hypothetical command-line wrapper." + ) + logger.error(stderr) + except subprocess.CalledProcessError as e: + logger.error(f"Command failed with exit code {e.returncode}") + logger.error(f"Stderr: {e.stderr}") + logger.error(f"Stdout: {e.stdout}") + stdout = e.stdout + stderr = e.stderr + + # --- Structured Result Return --- + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_adata)] if output_adata.exists() else [], + } + +@mcp.tool() +def piaso_find_markers( + input_adata: Path, + output_markers: Path, + cluster_key: str = "leiden", + n_genes_per_cluster: int = 25, + mu: int = 1, +) -> dict: + """ + Finds marker genes for pre-computed clusters using a hypothetical PIASO + 'find-markers' command, likely based on its COSG method. + + This function wraps a non-existent CLI for the piaso library. + + Args: + input_adata (Path): Path to the input AnnData file (.h5ad) with clustering results. + output_markers (Path): Path to save the output marker genes file (e.g., markers.csv). + cluster_key (str): The column key in the .obs AnnData attribute that identifies cluster labels. + Defaults to 'leiden'. + n_genes_per_cluster (int): The number of top marker genes to identify per cluster. Defaults to 25. + mu (int): The penalty parameter for the COSG algorithm. Defaults to 1. + + Returns: + dict: A dictionary containing the executed command, stdout, stderr, and the path to the output file. + """ + # --- Input Validation --- + if not input_adata.is_file(): + raise FileNotFoundError(f"Input file not found: {input_adata}") + if n_genes_per_cluster <= 0: + raise ValueError("n_genes_per_cluster must be a positive integer.") + if mu <= 0: + raise ValueError("mu must be a positive integer.") + + output_markers.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + # This assumes a hypothetical CLI: `piaso find-markers [options]` + cmd = [ + "piaso", "find-markers", + str(input_adata), + str(output_markers), + "--cluster-key", cluster_key, + "--n-genes-per-cluster", str(n_genes_per_cluster), + "--mu", str(mu), + ] + + command_executed = " ".join(cmd) + logger.info(f"Executing command: {command_executed}") + + # --- Subprocess Execution --- + try: + # This call is expected to fail as the 'piaso' executable does not exist. + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + stdout = process.stdout + stderr = process.stderr + except FileNotFoundError: + stdout = "" + stderr = ( + "FileNotFoundError: 'piaso' command not found. " + "This is expected as piaso is a Python library without a native CLI. " + "This MCP tool is based on a hypothetical command-line wrapper." + ) + logger.error(stderr) + except subprocess.CalledProcessError as e: + logger.error(f"Command failed with exit code {e.returncode}") + logger.error(f"Stderr: {e.stderr}") + logger.error(f"Stdout: {e.stdout}") + stdout = e.stdout + stderr = e.stderr + + # --- Structured Result Return --- + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_markers)] if output_markers.exists() else [], + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_piaso/app/piaso_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_piaso/app/piaso_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b1ce0a9d6278cbec3a29149dae72242a8dc98963 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_piaso/app/piaso_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_piaso/app/piaso_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_piaso' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_piaso/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_piaso/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_piaso/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_piaso/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_piaso/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..2614a0b4ee5cdabc9fb7431331a93a4419e950e4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_piaso/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-piaso: + build: . + image: mcp-piaso:latest + container_name: mcp-piaso + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=piaso + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_piaso/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_piaso/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3e7a81fb14c75506629cea93afc292c080d02ce8 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_piaso/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - piaso + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_piaso/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_piaso/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_piaso/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_picard copy/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_picard copy/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_picard copy/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pilon/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pilon/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pilon/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pixelator/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pixelator/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..633bbd48a6e9e1144318eaf8281b84209d75336d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pixelator/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install pixelator via conda (e.g., from bioconda) +RUN conda install -c bioconda pixelator -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/pixelator_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/pixelator_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/pixelator_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pixelator/app/__pycache__/pixelator_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pixelator/app/__pycache__/pixelator_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a841e2d923a97dfbb4bd07ff4762d35d2bdd80f Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pixelator/app/__pycache__/pixelator_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pixelator/app/pixelator_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pixelator/app/pixelator_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7c40c837d965ef02c2e0e2f02a62fc8ddab74e4c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pixelator/app/pixelator_server.py @@ -0,0 +1,591 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Literal, Optional + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided by the MCP framework. +def tool(*args, **kwargs): + def decorator(func): + return func + return decorator + +mcp = type("mcp", (), {"tool": tool}) + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_pixelator' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def pixelator_single_cell( + input_files: List[Path], + config: Path, + output: Path, + sample_id: str, + panel: Path, + cores: int = 1, + use_full_length: bool = False, + min_length: int = 20, + max_length: int = 0, + quality_limit: int = 20, + unqualified_percent_limit: int = 40, + average_qual: int = 0, + min_pixels: int = 10, + min_reads: int = 1, + max_component_size: int = 500, + dynamic_component_size: bool = False, +) -> dict: + """ + Run the pixelator single-cell pipeline on one or more FASTQ files. + + This command processes raw sequencing data to generate a PXL file, which + contains pixel information for each cell. + """ + # Input validation + if not input_files: + raise ValueError("At least one input FASTQ file is required.") + for file_path in input_files: + if not file_path.is_file(): + raise FileNotFoundError(f"Input file not found: {file_path}") + if not config.is_file(): + raise FileNotFoundError(f"Config file not found: {config}") + if not panel.is_file(): + raise FileNotFoundError(f"Panel file not found: {panel}") + if cores < 1: + raise ValueError("--cores must be a positive integer.") + + # Prepare output directory + output.mkdir(parents=True, exist_ok=True) + output_pxl_file = output / f"{sample_id}.pxl" + + # Command construction + cmd = [ + "pixelator", "single-cell", + "--config", str(config), + "--output", str(output), + "--sample-id", sample_id, + "--panel", str(panel), + "--cores", str(cores), + "--min-length", str(min_length), + "--max-length", str(max_length), + "--quality-limit", str(quality_limit), + "--unqualified-percent-limit", str(unqualified_percent_limit), + "--average-qual", str(average_qual), + "--min-pixels", str(min_pixels), + "--min-reads", str(min_reads), + "--max-component-size", str(max_component_size), + ] + if use_full_length: + cmd.append("--use-full-length") + if dynamic_component_size: + cmd.append("--dynamic-component-size") + + cmd.extend([str(p) for p in input_files]) + + # Subprocess execution + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_pxl_file)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"pixelator single-cell failed with exit code {e.returncode}", + "output_files": [] + } + + +@mcp.tool() +def pixelator_demux( + input_files: List[Path], + sample_sheet: Path, + output: Path, + cores: int = 1, + mismatches: int = 1, +) -> dict: + """ + Demultiplex single-cell FASTQ files based on a sample sheet. + """ + # Input validation + if not input_files: + raise ValueError("At least one input FASTQ file is required.") + for file_path in input_files: + if not file_path.is_file(): + raise FileNotFoundError(f"Input file not found: {file_path}") + if not sample_sheet.is_file(): + raise FileNotFoundError(f"Sample sheet file not found: {sample_sheet}") + if cores < 1: + raise ValueError("--cores must be a positive integer.") + if mismatches < 0: + raise ValueError("--mismatches must be a non-negative integer.") + + # Prepare output directory + output.mkdir(parents=True, exist_ok=True) + + # Command construction + cmd = [ + "pixelator", "demux", + "--sample-sheet", str(sample_sheet), + "--output", str(output), + "--cores", str(cores), + "--mismatches", str(mismatches), + ] + cmd.extend([str(p) for p in input_files]) + + # Subprocess execution + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + # Output files are determined by the sample sheet, so we list the directory + output_contents = [str(p) for p in output.glob('*')] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_contents + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"pixelator demux failed with exit code {e.returncode}", + "output_files": [] + } + + +@mcp.tool() +def pixelator_preqc( + input_files: List[Path], + output: Path, + sample_id: str, + cores: int = 1, + json: bool = True, + html: bool = True, +) -> dict: + """ + Run pre-QC on FASTQ files using fastp. + """ + # Input validation + if not input_files: + raise ValueError("At least one input FASTQ file is required.") + for file_path in input_files: + if not file_path.is_file(): + raise FileNotFoundError(f"Input file not found: {file_path}") + if cores < 1: + raise ValueError("--cores must be a positive integer.") + + # Prepare output directory + output.mkdir(parents=True, exist_ok=True) + + # Command construction + cmd = [ + "pixelator", "preqc", + "--output", str(output), + "--sample-id", sample_id, + "--cores", str(cores), + ] + if json: + cmd.append("--json") + else: + cmd.append("--no-json") + if html: + cmd.append("--html") + else: + cmd.append("--no-html") + + cmd.extend([str(p) for p in input_files]) + + # Subprocess execution + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + output_files = [] + if html: + output_files.append(str(output / f"{sample_id}.preqc.html")) + if json: + output_files.append(str(output / f"{sample_id}.preqc.json")) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"pixelator preqc failed with exit code {e.returncode}", + "output_files": [] + } + + +@mcp.tool() +def pixelator_collapse( + input_file: Path, + output: Path, + panel: Path, + method: Literal["unique", "majority"] = "unique", + add_region_ids: bool = False, +) -> dict: + """ + Collapse a PXL file by antibody. + """ + # Input validation + if not input_file.is_file(): + raise FileNotFoundError(f"Input PXL file not found: {input_file}") + if not panel.is_file(): + raise FileNotFoundError(f"Panel file not found: {panel}") + + # Prepare output directory + output.parent.mkdir(parents=True, exist_ok=True) + + # Command construction + cmd = [ + "pixelator", "collapse", + "--output", str(output), + "--panel", str(panel), + "--method", method, + ] + if add_region_ids: + cmd.append("--add-region-ids") + + cmd.append(str(input_file)) + + # Subprocess execution + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"pixelator collapse failed with exit code {e.returncode}", + "output_files": [] + } + + +@mcp.tool() +def pixelator_graph( + input_file: Path, + output: Path, + components: Literal["connected", "a-b"] = "connected", + metrics: Optional[List[Literal["moran", "geary", "all"]]] = None, + use_full_length: bool = False, + min_marker_count: int = 1, +) -> dict: + """ + Build graphs from a PXL file. + """ + # Input validation + if not input_file.is_file(): + raise FileNotFoundError(f"Input PXL file not found: {input_file}") + if min_marker_count < 1: + raise ValueError("--min-marker-count must be a positive integer.") + + # Prepare output directory + output.parent.mkdir(parents=True, exist_ok=True) + + # Command construction + cmd = [ + "pixelator", "graph", + "--output", str(output), + "--components", components, + "--min-marker-count", str(min_marker_count), + ] + if use_full_length: + cmd.append("--use-full-length") + if metrics: + for metric in metrics: + cmd.extend(["--metrics", metric]) + + cmd.append(str(input_file)) + + # Subprocess execution + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"pixelator graph failed with exit code {e.returncode}", + "output_files": [] + } + + +@mcp.tool() +def pixelator_layout( + input_file: Path, + output: Path, + method: Literal["umap", "fr"] = "umap", +) -> dict: + """ + Compute a layout for the graphs in a PXL file. + """ + # Input validation + if not input_file.is_file(): + raise FileNotFoundError(f"Input PXL file not found: {input_file}") + + # Prepare output directory + output.parent.mkdir(parents=True, exist_ok=True) + + # Command construction + cmd = [ + "pixelator", "layout", + "--output", str(output), + "--method", method, + str(input_file), + ] + + # Subprocess execution + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"pixelator layout failed with exit code {e.returncode}", + "output_files": [] + } + + +@mcp.tool() +def pixelator_analysis( + input_file: Path, + output: Path, + panel: Path, + leiden_resolution: float = 0.25, + min_size: int = 10, + min_marker_count: int = 1, + polarization_markers: Optional[str] = None, + colocalization_markers: Optional[str] = None, +) -> dict: + """ + Run the analysis pipeline on a PXL file. + """ + # Input validation + if not input_file.is_file(): + raise FileNotFoundError(f"Input PXL file not found: {input_file}") + if not panel.is_file(): + raise FileNotFoundError(f"Panel file not found: {panel}") + if leiden_resolution <= 0: + raise ValueError("--leiden-resolution must be positive.") + if min_size < 1 or min_marker_count < 1: + raise ValueError("--min-size and --min-marker-count must be positive.") + + # Prepare output directory + output.mkdir(parents=True, exist_ok=True) + + # Command construction + cmd = [ + "pixelator", "analysis", + "--output", str(output), + "--panel", str(panel), + "--leiden-resolution", str(leiden_resolution), + "--min-size", str(min_size), + "--min-marker-count", str(min_marker_count), + ] + if polarization_markers: + cmd.extend(["--polarization-markers", polarization_markers]) + if colocalization_markers: + cmd.extend(["--colocalization-markers", colocalization_markers]) + + cmd.append(str(input_file)) + + # Subprocess execution + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + output_contents = [str(p) for p in output.glob('*')] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_contents + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"pixelator analysis failed with exit code {e.returncode}", + "output_files": [] + } + + +@mcp.tool() +def pixelator_annotate( + input_file: Path, + annotation_file: Path, + output: Path, + on: str, +) -> dict: + """ + Annotate a PXL file with data from a CSV file. + """ + # Input validation + if not input_file.is_file(): + raise FileNotFoundError(f"Input PXL file not found: {input_file}") + if not annotation_file.is_file(): + raise FileNotFoundError(f"Annotation file not found: {annotation_file}") + if not on: + raise ValueError("--on parameter (join column) cannot be empty.") + + # Prepare output directory + output.parent.mkdir(parents=True, exist_ok=True) + + # Command construction + cmd = [ + "pixelator", "annotate", + "--annotation-file", str(annotation_file), + "--output", str(output), + "--on", on, + str(input_file), + ] + + # Subprocess execution + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"pixelator annotate failed with exit code {e.returncode}", + "output_files": [] + } + + +@mcp.tool() +def pixelator_adapter_design( + input_file: Path, + output: Path, + linker_file: Optional[Path] = None, + min_sep: int = 3, + strict: bool = False, +) -> dict: + """ + Design adapters for a given antibody panel. + """ + # Input validation + if not input_file.is_file(): + raise FileNotFoundError(f"Input antibody panel file not found: {input_file}") + if linker_file and not linker_file.is_file(): + raise FileNotFoundError(f"Linker file not found: {linker_file}") + if min_sep < 0: + raise ValueError("--min-sep must be a non-negative integer.") + + # Prepare output directory + output.mkdir(parents=True, exist_ok=True) + + # Command construction + cmd = [ + "pixelator", "adapter-design", + "--output", str(output), + "--min-sep", str(min_sep), + ] + if linker_file: + cmd.extend(["--linker-file", str(linker_file)]) + if strict: + cmd.append("--strict") + + cmd.append(str(input_file)) + + # Subprocess execution + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + output_contents = [str(p) for p in output.glob('*')] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_contents + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"pixelator adapter-design failed with exit code {e.returncode}", + "output_files": [] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pixelator/app/pixelator_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pixelator/app/pixelator_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1f592e402548eb57d2e1fbc821b4c4bf368848d1 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pixelator/app/pixelator_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_pixelator/app/pixelator_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_pixelator' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pixelator/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pixelator/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pixelator/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pixelator/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pixelator/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..dd6239aea23e693dc27f4137b41d4058a6cc426c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pixelator/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-pixelator: + build: . + image: mcp-pixelator:latest + container_name: mcp-pixelator + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=pixelator + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pixelator/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pixelator/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..93d2a2ec22676ef38efc286f7f48e3ecf53447d6 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pixelator/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - pixelator + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pixelator/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pixelator/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pixelator/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_primer3-py/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_primer3-py/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_primer3-py/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteomiqon-peptidedb/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteomiqon-peptidedb/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..821e28ab9fc7a2248d3b6c99215247da8b11d037 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteomiqon-peptidedb/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install proteomiqon-peptidedb via conda (e.g., from bioconda) +RUN conda install -c bioconda proteomiqon-peptidedb -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/proteomiqon-peptidedb_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/proteomiqon-peptidedb_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/proteomiqon-peptidedb_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteomiqon-peptidedb/app/__pycache__/proteomiqon-peptidedb_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteomiqon-peptidedb/app/__pycache__/proteomiqon-peptidedb_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..afd98ea97ce4a2ff150ed6ad387b1f2befaae6a9 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteomiqon-peptidedb/app/__pycache__/proteomiqon-peptidedb_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteomiqon-peptidedb/app/proteomiqon-peptidedb_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteomiqon-peptidedb/app/proteomiqon-peptidedb_server.py new file mode 100644 index 0000000000000000000000000000000000000000..558841ae54d6fad62639038288a8619d60964871 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteomiqon-peptidedb/app/proteomiqon-peptidedb_server.py @@ -0,0 +1,136 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict + +# The mcp.tool decorator is assumed to be available in the execution environment. +# It is not imported here as per the instructions. + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_proteomiqon_peptidedb' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def peptidedb( + input_fasta: Path, + output_db: Path, + enzyme: str = "Trypsin/P", + missed_cleavages: int = 2, + min_peptide_length: int = 7, + max_peptide_length: int = 50, + fixed_modifications: Optional[List[str]] = None, + variable_modifications: Optional[List[str]] = None, + threads: int = 1, +) -> Dict: + """ + Creates a peptide database from a protein FASTA file using proteomiqon-peptidedb. + + NOTE: This is a hypothetical wrapper. The actual tool failed to run during + analysis due to a missing .NET dependency, so its command-line arguments are + inferred. The parameters defined here are based on common features of similar + proteomics tools and should be verified against the actual tool's documentation. + + Args: + input_fasta: Path to the input protein FASTA file. + output_db: Path for the generated output peptide database file. + enzyme: The enzyme to use for in-silico digestion (e.g., 'Trypsin/P'). + missed_cleavages: Maximum number of allowed missed cleavages. + min_peptide_length: Minimum length of peptides to include in the database. + max_peptide_length: Maximum length of peptides to include in the database. + fixed_modifications: List of fixed modifications to apply. + variable_modifications: List of variable modifications to apply. + threads: Number of processor threads to use. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a list + of output files. + """ + # --- Input Validation --- + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found at: {input_fasta}") + + if threads < 1: + raise ValueError("The number of threads must be at least 1.") + + if missed_cleavages < 0: + raise ValueError("Missed cleavages cannot be negative.") + + if min_peptide_length < 1 or max_peptide_length < min_peptide_length: + raise ValueError( + f"Invalid peptide length range: min={min_peptide_length}, max={max_peptide_length}" + ) + + # Ensure the output directory exists + output_db.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + # This command structure is HYPOTHETICAL. You MUST replace these flags + # with the actual flags from the tool's documentation. + cmd = [ + "proteomiqon-peptidedb", + "--input", str(input_fasta), + "--output", str(output_db), + "--enzyme", enzyme, + "--missed-cleavages", str(missed_cleavages), + "--min-length", str(min_peptide_length), + "--max-length", str(max_peptide_length), + "--threads", str(threads), + ] + + if fixed_modifications: + for mod in fixed_modifications: + # Assuming a repeatable flag like --fixed-mod + cmd.extend(["--fixed-mod", mod]) + + if variable_modifications: + for mod in variable_modifications: + # Assuming a repeatable flag like --variable-mod + cmd.extend(["--variable-mod", mod]) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + # --- Result Handling --- + # Verify that the output file was actually created + if not output_db.is_file(): + raise FileNotFoundError( + f"Tool executed successfully, but the expected output file was not created: {output_db}" + ) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_db)] + } + + except FileNotFoundError: + # This error occurs if 'proteomiqon-peptidedb' is not in the PATH + stderr_msg = ( + "Error: 'proteomiqon-peptidedb' command not found. " + "Ensure the Proteomiqon suite is installed and its bin directory is in your system's PATH." + ) + return { + "command_executed": command_executed, + "stdout": "", + "stderr": stderr_msg, + "output_files": [] + } + except subprocess.CalledProcessError as e: + # This error occurs if the tool returns a non-zero exit code + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteomiqon-peptidedb/app/proteomiqon-peptidedb_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteomiqon-peptidedb/app/proteomiqon-peptidedb_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6dcdf0809a34778fe5d123106d21d3192f47f6e8 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteomiqon-peptidedb/app/proteomiqon-peptidedb_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_proteomiqon-peptidedb/app/proteomiqon-peptidedb_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_proteomiqon_peptidedb' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteomiqon-peptidedb/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteomiqon-peptidedb/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteomiqon-peptidedb/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteomiqon-peptidedb/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteomiqon-peptidedb/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..6d339b247891e009ea5b07eec1f4b1ccef41e3cf --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteomiqon-peptidedb/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-proteomiqon-peptidedb: + build: . + image: mcp-proteomiqon-peptidedb:latest + container_name: mcp-proteomiqon-peptidedb + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=proteomiqon-peptidedb + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteomiqon-peptidedb/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteomiqon-peptidedb/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..21c204dd7433ce319a4c838e0f9e56969be62320 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteomiqon-peptidedb/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - proteomiqon-peptidedb + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteomiqon-peptidedb/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteomiqon-peptidedb/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_proteomiqon-peptidedb/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pubchempy/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pubchempy/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2b444bf226db039b2628764dbac5b22f0e4693d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pubchempy/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install pubchempy via conda (e.g., from bioconda) +RUN conda install -c bioconda pubchempy -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/pubchempy_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/pubchempy_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/pubchempy_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pubchempy/app/__pycache__/pubchempy_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pubchempy/app/__pycache__/pubchempy_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ad793c4cf1f41df56f450411f3defd2d30af6201 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pubchempy/app/__pycache__/pubchempy_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pubchempy/app/pubchempy_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pubchempy/app/pubchempy_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e36bb8af0daf7301cf21609098af06b172dfcca1 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pubchempy/app/pubchempy_server.py @@ -0,0 +1,345 @@ +import subprocess +import json +import sys +from pathlib import Path +from typing import Optional, List, Union + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_pubchempy' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def pubchem_get_compounds( + identifier: str, + namespace: str = "name", + searchtype: Optional[str] = None, + threshold: int = 90, + max_results: int = 10, +): + """ + Search the PubChem Compound database and return detailed compound records. + + Args: + identifier: The search query (e.g., "Aspirin", "CC(=O)OC1=CC=CC=C1C(=O)O", "CID2244"). + namespace: The type of identifier provided ('name', 'smiles', 'inchi', 'inchikey', 'formula', 'cid'). + searchtype: Optional search type for structural searches ('substructure', 'similarity', 'superstructure', 'identity'). + threshold: Similarity threshold (0-100) used when searchtype is 'similarity'. + max_results: Maximum number of compound records to return. + """ + if threshold < 0 or threshold > 100: + return {"error": "Threshold must be between 0 and 100"} + if max_results <= 0: + return {"error": "max_results must be a positive integer"} + + # Construct Python script to execute pubchempy + python_script = f""" +import pubchempy as pcp +import json +import sys + +try: + results = pcp.get_compounds( + identifier={repr(identifier)}, + namespace={repr(namespace)}, + searchtype={repr(searchtype)}, + threshold={threshold} + ) + # Convert compound objects to dictionaries and limit results + output = [c.to_dict() for c in results[:{max_results}]] + print(json.dumps(output)) +except Exception as e: + print(str(e), file=sys.stderr) + sys.exit(1) +""" + try: + process = subprocess.run( + [sys.executable, "-c", python_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"pubchempy.get_compounds({identifier}, {namespace}, ...)", + "stdout": process.stdout, + "stderr": process.stderr, + "results": json.loads(process.stdout) if process.stdout.strip() else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": "pubchempy.get_compounds", + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to retrieve compounds from PubChem" + } + +@mcp.tool() +def pubchem_get_substances( + identifier: str, + namespace: str = "name", + max_results: int = 10, +): + """ + Search the PubChem Substance database. Substances are often less processed than Compounds. + + Args: + identifier: The search query (e.g., "Glucose", "SID12345"). + namespace: The type of identifier ('name', 'sid'). + max_results: Maximum number of substance records to return. + """ + python_script = f""" +import pubchempy as pcp +import json +import sys + +try: + results = pcp.get_substances( + identifier={repr(identifier)}, + namespace={repr(namespace)} + ) + output = [s.to_dict() for s in results[:{max_results}]] + print(json.dumps(output)) +except Exception as e: + print(str(e), file=sys.stderr) + sys.exit(1) +""" + try: + process = subprocess.run( + [sys.executable, "-c", python_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"pubchempy.get_substances({identifier}, {namespace})", + "stdout": process.stdout, + "stderr": process.stderr, + "results": json.loads(process.stdout) if process.stdout.strip() else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": "pubchempy.get_substances", + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to retrieve substances from PubChem" + } + +@mcp.tool() +def pubchem_get_properties( + identifiers: str, + properties: str, + namespace: str = "cid", +): + """ + Retrieve specific calculated properties for a list of PubChem identifiers. + + Args: + identifiers: Comma-separated list of identifiers (e.g., "2244,1234" or "Aspirin,Caffeine"). + properties: Comma-separated list of property names (e.g., "MolecularFormula,MolecularWeight,XLogP,CanonicalSMILES"). + namespace: The type of identifiers provided ('cid', 'name', 'smiles', 'inchi', 'inchikey'). + """ + # Split strings into lists for the Python script + id_list = [i.strip() for i in identifiers.split(",")] + prop_list = [p.strip() for p in properties.split(",")] + + python_script = f""" +import pubchempy as pcp +import json +import sys + +try: + # get_properties returns a list of dictionaries + results = pcp.get_properties( + properties={repr(prop_list)}, + identifier={repr(id_list)}, + namespace={repr(namespace)} + ) + print(json.dumps(results)) +except Exception as e: + print(str(e), file=sys.stderr) + sys.exit(1) +""" + try: + process = subprocess.run( + [sys.executable, "-c", python_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"pubchempy.get_properties({properties}, {identifiers})", + "stdout": process.stdout, + "stderr": process.stderr, + "properties": json.loads(process.stdout) if process.stdout.strip() else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": "pubchempy.get_properties", + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to retrieve properties from PubChem" + } + +@mcp.tool() +def pubchem_get_synonyms( + identifier: str, + namespace: str = "name", +): + """ + Retrieve all known synonyms (trade names, IUPAC names, CAS numbers) for a given identifier. + + Args: + identifier: The search query (e.g., "Aspirin" or "2244"). + namespace: The type of identifier ('name', 'cid', 'sid'). + """ + python_script = f""" +import pubchempy as pcp +import json +import sys + +try: + # get_synonyms returns a list of dictionaries with 'CID' and 'Synonym' keys + results = pcp.get_synonyms( + identifier={repr(identifier)}, + namespace={repr(namespace)} + ) + print(json.dumps(results)) +except Exception as e: + print(str(e), file=sys.stderr) + sys.exit(1) +""" + try: + process = subprocess.run( + [sys.executable, "-c", python_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"pubchempy.get_synonyms({identifier})", + "stdout": process.stdout, + "stderr": process.stderr, + "synonyms": json.loads(process.stdout) if process.stdout.strip() else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": "pubchempy.get_synonyms", + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to retrieve synonyms from PubChem" + } + +@mcp.tool() +def pubchem_download( + identifier: str, + output_path: str, + outformat: str = "SDF", + namespace: str = "cid", + overwrite: bool = False, +): + """ + Download compound or substance records from PubChem in various file formats. + + Args: + identifier: The search query or identifier. + output_path: Local path where the file should be saved. + outformat: The file format ('SDF', 'JSON', 'XML', 'ASNT', 'ASNB', 'CSV', 'PNG'). + namespace: The type of identifier ('cid', 'sid', 'name', 'smiles', etc.). + overwrite: Whether to overwrite the file if it already exists. + """ + path_obj = Path(output_path) + if path_obj.exists() and not overwrite: + return {"error": f"File {output_path} already exists. Set overwrite=True to replace it."} + + python_script = f""" +import pubchempy as pcp +import sys + +try: + pcp.download( + outformat={repr(outformat)}, + path={repr(str(path_obj))}, + identifier={repr(identifier)}, + namespace={repr(namespace)}, + overwrite={overwrite} + ) + print(f"Successfully downloaded to {repr(str(path_obj))}") +except Exception as e: + print(str(e), file=sys.stderr) + sys.exit(1) +""" + try: + process = subprocess.run( + [sys.executable, "-c", python_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"pubchempy.download({outformat}, {output_path}, ...)", + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(path_obj)] if path_obj.exists() else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": "pubchempy.download", + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to download data from PubChem" + } + +@mcp.tool() +def pubchem_get_cids( + identifier: str, + namespace: str = "name", + searchtype: Optional[str] = None, +): + """ + Get a list of PubChem Compound Identifiers (CIDs) for a given input. + + Args: + identifier: The search query (e.g., "Aspirin"). + namespace: The type of identifier ('name', 'smiles', 'inchi', 'formula'). + searchtype: Optional search type ('substructure', 'similarity', 'superstructure', 'identity'). + """ + python_script = f""" +import pubchempy as pcp +import json +import sys + +try: + # get_cids returns a list of integers + results = pcp.get_cids( + identifier={repr(identifier)}, + namespace={repr(namespace)}, + searchtype={repr(searchtype)} + ) + print(json.dumps(results)) +except Exception as e: + print(str(e), file=sys.stderr) + sys.exit(1) +""" + try: + process = subprocess.run( + [sys.executable, "-c", python_script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"pubchempy.get_cids({identifier})", + "stdout": process.stdout, + "stderr": process.stderr, + "cids": json.loads(process.stdout) if process.stdout.strip() else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": "pubchempy.get_cids", + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to retrieve CIDs from PubChem" + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pubchempy/app/pubchempy_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pubchempy/app/pubchempy_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2a55bbe5753531fc2c95d0cea9a861d0fb9628a2 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pubchempy/app/pubchempy_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_pubchempy/app/pubchempy_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_pubchempy' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pubchempy/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pubchempy/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pubchempy/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pubchempy/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pubchempy/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..60421cba7e6fa2fbb1d55c8c9680257b341d3625 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pubchempy/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-pubchempy: + build: . + image: mcp-pubchempy:latest + container_name: mcp-pubchempy + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=pubchempy + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pubchempy/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pubchempy/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e556ac2600e96e60945810715ddced604aea0729 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pubchempy/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - pubchempy + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pubchempy/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pubchempy/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pubchempy/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pybigwig/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pybigwig/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8870b587f69b6f459956378a5ed96811e05c1598 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pybigwig/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install pybigwig via conda (e.g., from bioconda) +RUN conda install -c bioconda pybigwig -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/pybigwig_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/pybigwig_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/pybigwig_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pybigwig/app/__pycache__/pybigwig_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pybigwig/app/__pycache__/pybigwig_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0376dadaabb6bf6c020ab15e81dc650477d61a0f Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pybigwig/app/__pycache__/pybigwig_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pybigwig/app/pybigwig_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pybigwig/app/pybigwig_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ee079eb2164be4864fedaa05abdaba465a63f7ad --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pybigwig/app/pybigwig_server.py @@ -0,0 +1,406 @@ +import subprocess +import json +import sys +from pathlib import Path +from typing import Optional, List, Dict, Union, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_pybigwig' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def pybigwig_get_info( + input_file: str, +) -> Dict[str, Any]: + """ + Retrieve general information about a bigWig or bigBed file, including header, + chromosome list, and file type verification. + """ + # Input validation + if not input_file.startswith(("http://", "https://", "ftp://")): + path = Path(input_file) + if not path.exists(): + return {"error": f"File not found: {input_file}"} + + # Python script to extract info using pyBigWig + python_code = f""" +import pyBigWig +import json +import sys + +try: + bw = pyBigWig.open("{input_file}") + res = {{ + "is_bigwig": bw.isBigWig(), + "is_bigbed": bw.isBigBed(), + "header": bw.header(), + "chroms": bw.chroms(), + }} + if bw.isBigBed(): + try: + res["sql"] = bw.SQL() + except: + res["sql"] = None + bw.close() + print(json.dumps(res)) +except Exception as e: + print(json.dumps({{"error": str(e)}}), file=sys.stderr) + sys.exit(1) +""" + try: + result = subprocess.run( + [sys.executable, "-c", python_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"pyBigWig.open('{input_file}') info extraction", + "stdout": result.stdout, + "data": json.loads(result.stdout) + } + except subprocess.CalledProcessError as e: + return { + "error": "Failed to extract bigWig info", + "stderr": e.stderr, + "stdout": e.stdout + } + +@mcp.tool() +def pybigwig_get_stats( + input_file: str, + chrom: str, + start: int = 0, + end: Optional[int] = None, + stat_type: str = "mean", + n_bins: int = 1, + exact: bool = False +) -> Dict[str, Any]: + """ + Compute summary information (statistics) on a range within a bigWig file. + + Args: + input_file: Path or URL to the bigWig file. + chrom: Chromosome name. + start: Start position (0-based). + end: End position (0-based). If None, the whole chromosome is used. + stat_type: Type of statistic: "mean", "max", "min", "coverage", or "std". + n_bins: Number of evenly spaced bins to compute values for. + exact: If True, compute exact summary statistics ignoring zoom levels. + """ + valid_types = ["mean", "max", "min", "coverage", "std"] + if stat_type not in valid_types: + return {"error": f"stat_type must be one of {valid_types}"} + + if n_bins < 1: + return {"error": "n_bins must be at least 1"} + + end_val = "None" if end is None else end + + python_code = f""" +import pyBigWig +import json +import sys + +try: + bw = pyBigWig.open("{input_file}") + if not bw.isBigWig(): + print(json.dumps({{"error": "File is not a bigWig file. Stats are only for bigWig."}}), file=sys.stderr) + sys.exit(1) + + stats = bw.stats("{chrom}", {start}, {end_val}, type="{stat_type}", nBins={n_bins}, exact={exact}) + bw.close() + print(json.dumps(stats)) +except Exception as e: + print(json.dumps({{"error": str(e)}}), file=sys.stderr) + sys.exit(1) +""" + try: + result = subprocess.run( + [sys.executable, "-c", python_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"bw.stats('{chrom}', {start}, {end}, type='{stat_type}', nBins={n_bins})", + "stdout": result.stdout, + "statistics": json.loads(result.stdout) + } + except subprocess.CalledProcessError as e: + return {"error": "Failed to compute stats", "stderr": e.stderr} + +@mcp.tool() +def pybigwig_get_values( + input_file: str, + chrom: str, + start: int, + end: int +) -> Dict[str, Any]: + """ + Retrieve per-base values for individual bases in a range. + Returns a list with one value for every base (NaN if no value exists). + """ + if start >= end: + return {"error": "Start position must be less than end position"} + + python_code = f""" +import pyBigWig +import json +import sys +import numpy as np + +class NumpyEncoder(json.JSONEncoder): + def default(self, obj): + if isinstance(obj, np.ndarray): + return obj.tolist() + if isinstance(obj, float) and np.isnan(obj): + return None + return json.JSONEncoder.default(self, obj) + +try: + bw = pyBigWig.open("{input_file}") + vals = bw.values("{chrom}", {start}, {end}) + bw.close() + print(json.dumps(vals, cls=NumpyEncoder)) +except Exception as e: + print(json.dumps({{"error": str(e)}}), file=sys.stderr) + sys.exit(1) +""" + try: + result = subprocess.run( + [sys.executable, "-c", python_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"bw.values('{chrom}', {start}, {end})", + "values": json.loads(result.stdout) + } + except subprocess.CalledProcessError as e: + return {"error": "Failed to retrieve values", "stderr": e.stderr} + +@mcp.tool() +def pybigwig_get_intervals( + input_file: str, + chrom: str, + start: int = 0, + end: Optional[int] = None +) -> Dict[str, Any]: + """ + Retrieve all intervals overlapping a specific range in a bigWig file. + Returns a list of (start, end, value) tuples. + """ + end_val = "None" if end is None else end + + python_code = f""" +import pyBigWig +import json +import sys + +try: + bw = pyBigWig.open("{input_file}") + intervals = bw.intervals("{chrom}", {start}, {end_val}) + bw.close() + print(json.dumps(intervals)) +except Exception as e: + print(json.dumps({{"error": str(e)}}), file=sys.stderr) + sys.exit(1) +""" + try: + result = subprocess.run( + [sys.executable, "-c", python_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"bw.intervals('{chrom}', {start}, {end})", + "intervals": json.loads(result.stdout) + } + except subprocess.CalledProcessError as e: + return {"error": "Failed to retrieve intervals", "stderr": e.stderr} + +@mcp.tool() +def pybigwig_get_bigbed_entries( + input_file: str, + chrom: str, + start: int, + end: int, + with_string: bool = True +) -> Dict[str, Any]: + """ + Retrieve entries from a bigBed file overlapping a range. + Returns a list of tuples (start, end, string) or (start, end). + """ + python_code = f""" +import pyBigWig +import json +import sys + +try: + bb = pyBigWig.open("{input_file}") + if not bb.isBigBed(): + print(json.dumps({{"error": "File is not a bigBed file."}}), file=sys.stderr) + sys.exit(1) + entries = bb.entries("{chrom}", {start}, {end}, withString={with_string}) + bb.close() + print(json.dumps(entries)) +except Exception as e: + print(json.dumps({{"error": str(e)}}), file=sys.stderr) + sys.exit(1) +""" + try: + result = subprocess.run( + [sys.executable, "-c", python_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"bb.entries('{chrom}', {start}, {end}, withString={with_string})", + "entries": json.loads(result.stdout) + } + except subprocess.CalledProcessError as e: + return {"error": "Failed to retrieve bigBed entries", "stderr": e.stderr} + +@mcp.tool() +def pybigwig_create_bigwig( + output_file: str, + chrom_sizes: Dict[str, int], + starts: List[int], + ends: List[int], + values: List[float], + chroms: Optional[List[str]] = None, + max_zooms: int = 10, + validate: bool = True +) -> Dict[str, Any]: + """ + Create a new bigWig file from provided data (bedGraph-like format). + + Args: + output_file: Path where the bigWig will be saved. + chrom_sizes: Dictionary of {chrom_name: length}. + starts: List of start positions. + ends: List of end positions. + values: List of values for each interval. + chroms: List of chromosome names for each interval. If None, assumes first chrom in chrom_sizes. + max_zooms: Maximum number of zoom levels (default 10). + validate: Whether to validate that entries are in order (default True). + """ + output_path = Path(output_file) + + # If chroms is not provided, we assume all entries belong to the first chromosome in the dict + if chroms is None: + first_chrom = list(chrom_sizes.keys())[0] + chroms = [first_chrom] * len(starts) + + if not (len(chroms) == len(starts) == len(ends) == len(values)): + return {"error": "Lists for chroms, starts, ends, and values must be of equal length"} + + # Prepare data for the script + chrom_list = list(chrom_sizes.items()) + + python_code = f""" +import pyBigWig +import sys + +try: + bw = pyBigWig.open("{output_file}", "w") + bw.addHeader({chrom_list}, maxZooms={max_zooms}) + bw.addEntries( + {chroms}, + {starts}, + ends={ends}, + values={values}, + validate={validate} + ) + bw.close() + print("Successfully created bigWig") +except Exception as e: + print(str(e), file=sys.stderr) + sys.exit(1) +""" + try: + result = subprocess.run( + [sys.executable, "-c", python_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"pyBigWig.open('{output_file}', 'w') + addHeader + addEntries", + "stdout": result.stdout, + "output_file": str(output_path.absolute()) + } + except subprocess.CalledProcessError as e: + return {"error": "Failed to create bigWig file", "stderr": e.stderr} + +@mcp.tool() +def pybigwig_create_wiggle_step( + output_file: str, + chrom_sizes: Dict[str, int], + chrom: str, + starts: List[int], + values: List[float], + span: int, + step: Optional[int] = None, + max_zooms: int = 10 +) -> Dict[str, Any]: + """ + Create a bigWig file using fixedStep or variableStep wiggle formats. + + Args: + output_file: Path to output file. + chrom_sizes: Dictionary of {chrom_name: length}. + chrom: The chromosome name for these entries. + starts: List of start positions (or single start if fixedStep). + values: List of values. + span: The span of each entry. + step: If provided, uses fixedStep format. If None, uses variableStep. + max_zooms: Maximum number of zoom levels. + """ + chrom_list = list(chrom_sizes.items()) + + # Logic for fixedStep vs variableStep + if step is not None: + # fixedStep: starts should be a single integer + start_arg = starts[0] if isinstance(starts, list) else starts + add_entries_call = f"bw.addEntries('{chrom}', {start_arg}, values={values}, span={span}, step={step})" + else: + # variableStep: starts is a list + add_entries_call = f"bw.addEntries('{chrom}', {starts}, values={values}, span={span})" + + python_code = f""" +import pyBigWig +import sys + +try: + bw = pyBigWig.open("{output_file}", "w") + bw.addHeader({chrom_list}, maxZooms={max_zooms}) + {add_entries_call} + bw.close() + print("Successfully created bigWig from wiggle format") +except Exception as e: + print(str(e), file=sys.stderr) + sys.exit(1) +""" + try: + result = subprocess.run( + [sys.executable, "-c", python_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": add_entries_call, + "stdout": result.stdout, + "output_file": output_file + } + except subprocess.CalledProcessError as e: + return {"error": "Failed to create bigWig file", "stderr": e.stderr} + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pybigwig/app/pybigwig_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pybigwig/app/pybigwig_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..886b9b27ac044c6f73ff6c0cc29ad6efe712f767 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pybigwig/app/pybigwig_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_pybigwig/app/pybigwig_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_pybigwig' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pybigwig/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pybigwig/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pybigwig/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pybigwig/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pybigwig/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..ab4d9f36e3493d67f9abbb8d613d0e20e4a62bf7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pybigwig/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-pybigwig: + build: . + image: mcp-pybigwig:latest + container_name: mcp-pybigwig + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=pybigwig + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pybigwig/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pybigwig/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c0953fb5916d75849f37814fdee3535bfd383682 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pybigwig/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - pybigwig + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pybigwig/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pybigwig/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pybigwig/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyfastx/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyfastx/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ce2baa8aa182a26809dcd606e038f5fc18bc4a4d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyfastx/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install pyfastx via conda (e.g., from bioconda) +RUN conda install -c bioconda pyfastx -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/pyfastx_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/pyfastx_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/pyfastx_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyfastx/app/__pycache__/pyfastx_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyfastx/app/__pycache__/pyfastx_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..55ca7dcdfd28d9af71965d6975add3f445f9eed0 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyfastx/app/__pycache__/pyfastx_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyfastx/app/pyfastx_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyfastx/app/pyfastx_server.py new file mode 100644 index 0000000000000000000000000000000000000000..71d11fb27e858ac25539b918842340f8aca695ad --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyfastx/app/pyfastx_server.py @@ -0,0 +1,330 @@ +from pathlib import Path +import subprocess +from typing import Optional, List +import tempfile + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_pyfastx' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def pyfastx_index( + fasta_q_file: str +): + """ + Build index for FASTA or FASTQ file to enable fast random access. + + Args: + fasta_q_file: Path to the input FASTA or FASTQ file (plain or gzipped). + """ + input_path = Path(fasta_q_file) + if not input_path.exists(): + return {"error": f"Input file {fasta_q_file} does not exist"} + + cmd = ["pyfastx", "index", str(input_path)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + # pyfastx index creates a .fxi or .fqi file in the same directory + index_file = input_path.with_suffix(input_path.suffix + ".fxi") if "fa" in input_path.suffix.lower() else input_path.with_suffix(input_path.suffix + ".fqi") + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(index_file)] if index_file.exists() else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def pyfastx_stat( + fasta_q_file: str +): + """ + Show detailed statistics information of FASTA or FASTQ file. + + Args: + fasta_q_file: Path to the input FASTA or FASTQ file. + """ + input_path = Path(fasta_q_file) + if not input_path.exists(): + return {"error": f"Input file {fasta_q_file} does not exist"} + + cmd = ["pyfastx", "stat", str(input_path)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + 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 pyfastx_split( + fasta_q_file: str, + num_files: Optional[int] = None, + seq_count: Optional[int] = None, + out_dir: str = "." +): + """ + Split FASTA or FASTQ file into multiple smaller files. + + Args: + fasta_q_file: Path to the input FASTA or FASTQ file. + num_files: Split into N files. + seq_count: Split into files containing N sequences each. + out_dir: Directory to save the split files. + """ + input_path = Path(fasta_q_file) + if not input_path.exists(): + return {"error": f"Input file {fasta_q_file} does not exist"} + + cmd = ["pyfastx", "split"] + + if num_files is not None: + if num_files <= 0: + return {"error": "num_files must be greater than 0"} + cmd.extend(["-n", str(num_files)]) + elif seq_count is not None: + if seq_count <= 0: + return {"error": "seq_count must be greater than 0"} + cmd.extend(["-c", str(seq_count)]) + else: + return {"error": "Either num_files or seq_count must be provided"} + + output_path = Path(out_dir) + if not output_path.exists(): + output_path.mkdir(parents=True, exist_ok=True) + + cmd.extend(["-o", str(output_path)]) + cmd.append(str(input_path)) + + 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(output_path) + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def pyfastx_fq2fa( + fastq_file: str, + output_fasta: Optional[str] = None +): + """ + Convert FASTQ file to FASTA file. + + Args: + fastq_file: Path to the input FASTQ file. + output_fasta: Path to the output FASTA file. If not provided, prints to stdout. + """ + input_path = Path(fastq_file) + if not input_path.exists(): + return {"error": f"Input file {fastq_file} does not exist"} + + cmd = ["pyfastx", "fq2fa", str(input_path)] + + if output_fasta: + cmd.extend(["-o", output_fasta]) + + 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_fasta] if output_fasta else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def pyfastx_subseq( + fasta_file: str, + region: str, + strand: str = "+" +): + """ + Get subsequences from FASTA file by region. + + Args: + fasta_file: Path to the input FASTA file. + region: Region in format 'name:start-end' (1-based). + strand: Strand to extract, '+' or '-'. + """ + input_path = Path(fasta_file) + if not input_path.exists(): + return {"error": f"Input file {fasta_file} does not exist"} + + if strand not in ["+", "-"]: + return {"error": "Strand must be '+' or '-'"} + + cmd = ["pyfastx", "subseq", "--strand", strand, str(input_path), region] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + 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 pyfastx_sample( + fasta_q_file: str, + num: Optional[int] = None, + proportion: Optional[float] = None, + output: Optional[str] = None +): + """ + Randomly sample sequences from FASTA or FASTQ file. + + Args: + fasta_q_file: Path to the input FASTA or FASTQ file. + num: Number of sequences to sample. + proportion: Proportion of sequences to sample (0.0 to 1.0). + output: Path to the output file. If not provided, prints to stdout. + """ + input_path = Path(fasta_q_file) + if not input_path.exists(): + return {"error": f"Input file {fasta_q_file} does not exist"} + + cmd = ["pyfastx", "sample"] + + if num is not None: + if num <= 0: + return {"error": "num must be greater than 0"} + cmd.extend(["-n", str(num)]) + elif proportion is not None: + if not (0.0 < proportion <= 1.0): + return {"error": "proportion must be between 0.0 and 1.0"} + cmd.extend(["-p", str(proportion)]) + else: + return {"error": "Either num or proportion must be provided"} + + if output: + cmd.extend(["-o", output]) + + cmd.append(str(input_path)) + + 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] if output else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def pyfastx_extract( + fasta_q_file: str, + ids: Optional[List[str]] = None, + id_file: Optional[str] = None, + output: Optional[str] = None, + space: bool = False +): + """ + Extract full sequences or reads from FASTA/Q file by identifiers. + + Args: + fasta_q_file: Path to the input FASTA or FASTQ file. + ids: List of sequence identifiers to extract. + id_file: Path to a file containing a list of identifiers (one per line). + output: Path to the output file. If not provided, prints to stdout. + space: Use the first word of the header as the identifier (default is full header). + """ + input_path = Path(fasta_q_file) + if not input_path.exists(): + return {"error": f"Input file {fasta_q_file} does not exist"} + + cmd = ["pyfastx", "extract"] + + if space: + cmd.append("--space") + + if output: + cmd.extend(["-o", output]) + + # Handle ID input + temp_id_file = None + if id_file: + if not Path(id_file).exists(): + return {"error": f"ID file {id_file} does not exist"} + cmd.extend(["-l", id_file]) + elif ids: + # Create a temporary file for the IDs to use the -l flag which is safer for many IDs + temp_id_file = tempfile.NamedTemporaryFile(mode='w', delete=False) + for seq_id in ids: + temp_id_file.write(f"{seq_id}\n") + temp_id_file.close() + cmd.extend(["-l", temp_id_file.name]) + else: + return {"error": "Either ids list or id_file must be provided"} + + cmd.append(str(input_path)) + + 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] if output else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + finally: + if temp_id_file: + Path(temp_id_file.name).unlink(missing_ok=True) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyfastx/app/pyfastx_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyfastx/app/pyfastx_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0ff04a9ad2d43f2b140c5b53789517980402016a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyfastx/app/pyfastx_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_pyfastx/app/pyfastx_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_pyfastx' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyfastx/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyfastx/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyfastx/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyfastx/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyfastx/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..73272c718275c11f957585efb3ac8ca6174b404c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyfastx/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-pyfastx: + build: . + image: mcp-pyfastx:latest + container_name: mcp-pyfastx + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=pyfastx + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyfastx/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyfastx/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4b4459e344c5f8660272bc99bde8e289c816f811 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyfastx/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - pyfastx + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyfastx/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyfastx/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyfastx/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyranges/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyranges/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c57f28e22f570484e02925471fac8b726878b218 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyranges/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install pyranges via conda (e.g., from bioconda) +RUN conda install -c bioconda pyranges -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/pyranges_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/pyranges_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/pyranges_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyranges/app/__pycache__/pyranges_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyranges/app/__pycache__/pyranges_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..67b089a558fe00eed763914c61dfbc80e419f26c Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyranges/app/__pycache__/pyranges_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyranges/app/pyranges_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyranges/app/pyranges_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fce81be62117c275db4010308b311e4e9be929b2 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyranges/app/pyranges_server.py @@ -0,0 +1,295 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_pyranges' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def pyranger_intersect( + input_a: str, + input_b: str, + output_file: str, + stranded: bool = False, + invert: bool = False, + overlap_fraction: float = 1e-9, +) -> Dict[str, Any]: + """ + Find overlapping genomic intervals between two files using pyranger. + + Args: + input_a: Path to the first genomic file (BED, GTF, GFF, VCF, BAM). + input_b: Path to the second genomic file. + output_file: Path where the intersected results will be saved. + stranded: If True, only report overlaps on the same strand. + invert: If True, report intervals in A that do NOT overlap with B. + overlap_fraction: Minimum fraction of overlap required (default is any overlap). + """ + path_a = Path(input_a) + path_b = Path(input_b) + path_out = Path(output_file) + + if not path_a.exists(): + return {"error": f"Input file A not found: {input_a}"} + if not path_b.exists(): + return {"error": f"Input file B not found: {input_b}"} + + cmd = ["pyranger", "intersect", str(path_a), str(path_b), "-o", str(path_out)] + + if stranded: + cmd.append("--stranded") + if invert: + cmd.append("--invert") + if overlap_fraction > 1e-9: + cmd.extend(["--overlap", str(overlap_fraction)]) + + 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": [str(path_out)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def pyranger_join( + input_a: str, + input_b: str, + output_file: str, + how: str = "inner", + stranded: bool = False, + suffix: str = "_b" +) -> Dict[str, Any]: + """ + Join two sets of genomic intervals based on overlap. + + Args: + input_a: Path to the first genomic file. + input_b: Path to the second genomic file. + output_file: Path to save the joined results. + how: Type of join: 'inner', 'left', or 'outer'. + stranded: If True, join only intervals on the same strand. + suffix: Suffix to add to overlapping columns from input_b. + """ + path_a = Path(input_a) + path_b = Path(input_b) + path_out = Path(output_file) + + if not path_a.exists() or not path_b.exists(): + return {"error": "One or both input files do not exist."} + + if how not in ["inner", "left", "outer"]: + return {"error": "Parameter 'how' must be 'inner', 'left', or 'outer'."} + + cmd = ["pyranger", "join", str(path_a), str(path_b), "-o", str(path_out), "--how", how, "--suffix", suffix] + + if stranded: + cmd.append("--stranded") + + 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": [str(path_out)] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def pyranger_subtract( + input_a: str, + input_b: str, + output_file: str, + stranded: bool = False +) -> Dict[str, Any]: + """ + Subtract intervals in file B from intervals in file A. + + Args: + input_a: Path to the source genomic file. + input_b: Path to the genomic file to subtract. + output_file: Path to save the resulting intervals. + stranded: If True, subtract only if intervals are on the same strand. + """ + path_a = Path(input_a) + path_b = Path(input_b) + path_out = Path(output_file) + + if not path_a.exists() or not path_b.exists(): + return {"error": "Input files not found."} + + cmd = ["pyranger", "subtract", str(path_a), str(path_b), "-o", str(path_out)] + if stranded: + cmd.append("--stranded") + + 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": [str(path_out)] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def pyranger_merge( + input_file: str, + output_file: str, + stranded: bool = False, + distance: int = 0 +) -> Dict[str, Any]: + """ + Merge overlapping or nearby genomic intervals into single intervals. + + Args: + input_file: Path to the genomic file to merge. + output_file: Path to save the merged results. + stranded: If True, only merge intervals on the same strand. + distance: Maximum distance between intervals to be merged (default 0). + """ + path_in = Path(input_file) + path_out = Path(output_file) + + if not path_in.exists(): + return {"error": f"Input file not found: {input_file}"} + + cmd = ["pyranger", "merge", str(path_in), "-o", str(path_out), "--distance", str(distance)] + if stranded: + cmd.append("--stranded") + + 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": [str(path_out)] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def pyranger_nearest( + input_a: str, + input_b: str, + output_file: str, + stranded: bool = False, + how: str = "both" +) -> Dict[str, Any]: + """ + Find the nearest intervals in file B for each interval in file A. + + Args: + input_a: Path to the query genomic file. + input_b: Path to the reference genomic file. + output_file: Path to save the results. + stranded: If True, look for nearest intervals on the same strand. + how: Direction to look: 'upstream', 'downstream', or 'both'. + """ + path_a = Path(input_a) + path_b = Path(input_b) + path_out = Path(output_file) + + if not path_a.exists() or not path_b.exists(): + return {"error": "Input files not found."} + + if how not in ["upstream", "downstream", "both"]: + return {"error": "Parameter 'how' must be 'upstream', 'downstream', or 'both'."} + + cmd = ["pyranger", "nearest", str(path_a), str(path_b), "-o", str(path_out), "--how", how] + if stranded: + cmd.append("--stranded") + + 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": [str(path_out)] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def pyranger_sort( + input_file: str, + output_file: str +) -> Dict[str, Any]: + """ + Sort genomic intervals by Chromosome, Start, and End. + + Args: + input_file: Path to the genomic file to sort. + output_file: Path to save the sorted file. + """ + path_in = Path(input_file) + path_out = Path(output_file) + + if not path_in.exists(): + return {"error": f"Input file not found: {input_file}"} + + cmd = ["pyranger", "sort", str(path_in), "-o", str(path_out)] + + 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": [str(path_out)] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def pyranger_coverage( + input_file: str, + output_file: str, + stranded: bool = False +) -> Dict[str, Any]: + """ + Calculate genomic coverage for the intervals in the input file. + + Args: + input_file: Path to the genomic file. + output_file: Path to save the coverage results. + stranded: If True, calculate coverage separately for each strand. + """ + path_in = Path(input_file) + path_out = Path(output_file) + + if not path_in.exists(): + return {"error": f"Input file not found: {input_file}"} + + cmd = ["pyranger", "coverage", str(path_in), "-o", str(path_out)] + if stranded: + cmd.append("--stranded") + + 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": [str(path_out)] + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyranges/app/pyranges_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyranges/app/pyranges_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2a1ccafbe8a151184b2c1c64bb5851041278f540 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyranges/app/pyranges_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_pyranges/app/pyranges_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_pyranges' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyranges/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyranges/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyranges/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyranges/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyranges/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..8adf9ae9940994e8585305a8ce80a08bf7f41ad4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyranges/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-pyranges: + build: . + image: mcp-pyranges:latest + container_name: mcp-pyranges + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=pyranges + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyranges/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyranges/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8a7af9c6c9ce848d1f37f54bfd30fd8e1c74d02b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyranges/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - pyranges + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyranges/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyranges/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyranges/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyroe/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyroe/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..23aafb51b24869270b33c17721d9059cb63aa376 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyroe/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install pyroe via conda (e.g., from bioconda) +RUN conda install -c bioconda pyroe -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY pyroe_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/pyroe_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/pyroe_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyroe/app/__pycache__/pyroe_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyroe/app/__pycache__/pyroe_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3390c96bc4278e2d6f8e2c0cb0a991c70828e1c4 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyroe/app/__pycache__/pyroe_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyroe/app/pyroe_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyroe/app/pyroe_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b2f9349cb6318e549630b298514dbd17e662e65d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyroe/app/pyroe_server.py @@ -0,0 +1,443 @@ +from pathlib import Path +from typing import Optional, List +import subprocess +import tempfile +import shutil + +# Note: mcp is not imported as per instructions, but @mcp.tool is used for clarity. + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_pyroe' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def make_splici( + genome_fasta: Path, + gtf_annotation: Path, + output_dir: Path, + flank_length: int = 90, + threads: int = 1, + keep_intermediate: bool = False, + fasta_name: Optional[str] = None, + gtf_name: Optional[str] = None, +) -> dict: + """ + Make a spliced + intronic reference (splici) for alevin-fry. + + This function generates a reference transcriptome that includes both spliced + and intronic sequences, suitable for single-cell RNA-seq quantification + with tools like alevin-fry. + + Args: + genome_fasta: Path to the input genome FASTA file. + gtf_annotation: Path to the input GTF annotation file. + output_dir: Directory where the generated reference files will be saved. + flank_length: Length of flanking sequence to include for intronic regions. + Must be a non-negative integer. + threads: Number of threads to use for processing. Must be a positive integer. + keep_intermediate: If True, intermediate files generated during reference + creation will be kept. + fasta_name: Optional name for the output FASTA file. If None, a default + name like 'splici_ref.fasta' will be used. + gtf_name: Optional name for the output GTF file. If None, a default + name like 'splici_ref.gtf' will be used. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list + of generated output files. + """ + # Input validation + if not genome_fasta.is_file(): + raise FileNotFoundError(f"Genome FASTA file not found: {genome_fasta}") + if not gtf_annotation.is_file(): + raise FileNotFoundError(f"GTF annotation file not found: {gtf_annotation}") + + if flank_length < 0: + raise ValueError("Flank length must be a non-negative integer.") + if threads < 1: + raise ValueError("Number of threads must be a positive integer.") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "pyroe", + "make-splici", + "--genome", str(genome_fasta), + "--gtf", str(gtf_annotation), + "--output", str(output_dir), + "--flank-length", str(flank_length), + "--threads", str(threads), + ] + + if keep_intermediate: + cmd.append("--keep-intermediate") + if fasta_name: + cmd.extend(["--fasta-name", fasta_name]) + if gtf_name: + cmd.extend(["--gtf-name", gtf_name]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + stdout = result.stdout + stderr = result.stderr + + # Determine output files based on common pyroe behavior + # Assuming default names if not specified + output_fasta = output_dir / (fasta_name if fasta_name else "splici_ref.fasta") + output_gtf = output_dir / (gtf_name if gtf_name else "splici_ref.gtf") + + output_files = [str(f) for f in [output_fasta, output_gtf] if f.exists()] + + return { + "command_executed": " ".join(cmd), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"pyroe make-splici failed with exit code {e.returncode}: {e}", + "returncode": e.returncode, + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "error": "pyroe command not found. Is it installed and in your PATH?", + } + +@mcp.tool() +def make_spliceu( + genome_fasta: Path, + gtf_annotation: Path, + output_dir: Path, + flank_length: int = 90, + threads: int = 1, + keep_intermediate: bool = False, + fasta_name: Optional[str] = None, + gtf_name: Optional[str] = None, +) -> dict: + """ + Make a spliced + unspliced reference (spliceu) for alevin-fry. + + This function generates a reference transcriptome that includes both spliced + and unspliced sequences, suitable for single-cell RNA-seq quantification + with tools like alevin-fry. + + Args: + genome_fasta: Path to the input genome FASTA file. + gtf_annotation: Path to the input GTF annotation file. + output_dir: Directory where the generated reference files will be saved. + flank_length: Length of flanking sequence to include for unspliced regions. + Must be a non-negative integer. + threads: Number of threads to use for processing. Must be a positive integer. + keep_intermediate: If True, intermediate files generated during reference + creation will be kept. + fasta_name: Optional name for the output FASTA file. If None, a default + name like 'spliceu_ref.fasta' will be used. + gtf_name: Optional name for the output GTF file. If None, a default + name like 'spliceu_ref.gtf' will be used. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list + of generated output files. + """ + # Input validation + if not genome_fasta.is_file(): + raise FileNotFoundError(f"Genome FASTA file not found: {genome_fasta}") + if not gtf_annotation.is_file(): + raise FileNotFoundError(f"GTF annotation file not found: {gtf_annotation}") + + if flank_length < 0: + raise ValueError("Flank length must be a non-negative integer.") + if threads < 1: + raise ValueError("Number of threads must be a positive integer.") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "pyroe", + "make-spliceu", + "--genome", str(genome_fasta), + "--gtf", str(gtf_annotation), + "--output", str(output_dir), + "--flank-length", str(flank_length), + "--threads", str(threads), + ] + + if keep_intermediate: + cmd.append("--keep-intermediate") + if fasta_name: + cmd.extend(["--fasta-name", fasta_name]) + if gtf_name: + cmd.extend(["--gtf-name", gtf_name]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + stdout = result.stdout + stderr = result.stderr + + # Determine output files based on common pyroe behavior + # Assuming default names if not specified + output_fasta = output_dir / (fasta_name if fasta_name else "spliceu_ref.fasta") + output_gtf = output_dir / (gtf_name if gtf_name else "spliceu_ref.gtf") + + output_files = [str(f) for f in [output_fasta, output_gtf] if f.exists()] + + return { + "command_executed": " ".join(cmd), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"pyroe make-spliceu failed with exit code {e.returncode}: {e}", + "returncode": e.returncode, + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "error": "pyroe command not found. Is it installed and in your PATH?", + } + +@mcp.tool() +def fetch_quant( + quant_path: Path, + output_dir: Path, + format: str = "csv", + gene_id_to_name_map: Optional[Path] = None, +) -> dict: + """ + Fetch processed quantification results from an alevin-fry output directory. + + This function retrieves and potentially converts quantification results + into a specified format. + + Args: + quant_path: Path to the input alevin-fry quantification directory. + output_dir: Directory where the fetched/converted results will be saved. + format: The desired output format for the quantification results. + Common options include "csv", "tsv", "json". + gene_id_to_name_map: Optional path to a gene ID to gene name mapping file. + If provided, gene IDs in the output will be replaced + with gene names. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list + of generated output files. + """ + # Input validation + if not quant_path.is_dir(): + raise FileNotFoundError(f"Quantification directory not found: {quant_path}") + + output_dir.mkdir(parents=True, exist_ok=True) + + valid_formats = ["csv", "tsv", "json", "mtx"] # Assuming common formats + if format.lower() not in valid_formats: + raise ValueError(f"Invalid format '{format}'. Must be one of: {', '.join(valid_formats)}") + + cmd = [ + "pyroe", + "fetch-quant", + "--quant-path", str(quant_path), + "--output", str(output_dir), + "--format", format.lower(), + ] + + if gene_id_to_name_map: + if not gene_id_to_name_map.is_file(): + raise FileNotFoundError(f"Gene ID to name map file not found: {gene_id_to_name_map}") + cmd.extend(["--id-to-name", str(gene_id_to_name_map)]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + stdout = result.stdout + stderr = result.stderr + + # Assuming a generic output file name based on format + output_file_name = f"quant_results.{format.lower()}" + output_file_path = output_dir / output_file_name + + output_files = [str(output_file_path)] if output_file_path.exists() else [] + + return { + "command_executed": " ".join(cmd), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"pyroe fetch-quant failed with exit code {e.returncode}: {e}", + "returncode": e.returncode, + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "error": "pyroe command not found. Is it installed and in your PATH?", + } + +@mcp.tool() +def id_to_name( + gtf_annotation: Path, + output_file: Path, + attribute_id: str = "gene_id", + attribute_name: str = "gene_name", +) -> dict: + """ + Generate a gene ID to gene name mapping file from a GTF annotation. + + This function parses a GTF file to extract gene IDs and their corresponding + gene names, saving them into a tab-separated file. + + Args: + gtf_annotation: Path to the input GTF annotation file. + output_file: Path where the gene ID to gene name mapping file will be saved. + The parent directory must exist. + attribute_id: The GTF attribute key used for gene IDs (e.g., "gene_id"). + attribute_name: The GTF attribute key used for gene names (e.g., "gene_name"). + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list + of generated output files. + """ + # Input validation + if not gtf_annotation.is_file(): + raise FileNotFoundError(f"GTF annotation file not found: {gtf_annotation}") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + cmd = [ + "pyroe", + "id-to-name", + "--gtf", str(gtf_annotation), + "--output", str(output_file), + "--attribute-id", attribute_id, + "--attribute-name", attribute_name, + ] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + stdout = result.stdout + stderr = result.stderr + + output_files = [str(output_file)] if output_file.exists() else [] + + return { + "command_executed": " ".join(cmd), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"pyroe id-to-name failed with exit code {e.returncode}: {e}", + "returncode": e.returncode, + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "error": "pyroe command not found. Is it installed and in your PATH?", + } + +@mcp.tool() +def convert( + input_quant_dir: Path, + output_format: str, + output_file: Path, + gene_id_to_name_map: Optional[Path] = None, + cell_barcode_file: Optional[Path] = None, +) -> dict: + """ + Convert alevin-fry quantification results to another format. + + This function takes an alevin-fry quantification directory and converts + its contents into a specified single-cell data format (e.g., loom, h5ad, mtx). + + Args: + input_quant_dir: Path to the input alevin-fry quantification directory. + output_format: The desired output format (e.g., "loom", "h5ad", "mtx"). + This parameter is required. + output_file: Path where the converted output file will be saved. + The parent directory must exist. + gene_id_to_name_map: Optional path to a gene ID to gene name mapping file. + If provided, gene IDs in the output will be replaced + with gene names. + cell_barcode_file: Optional path to a file containing cell barcodes. + If provided, these barcodes will be used for cell + annotation in the output. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list + of generated output files. + """ + # Input validation + if not input_quant_dir.is_dir(): + raise FileNotFoundError(f"Input quantification directory not found: {input_quant_dir}") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + valid_formats = ["loom", "h5ad", "mtx"] # Common single-cell formats + if output_format.lower() not in valid_formats: + raise ValueError(f"Invalid output format '{output_format}'. Must be one of: {', '.join(valid_formats)}") + + cmd = [ + "pyroe", + "convert", + "--input", str(input_quant_dir), + "--output-format", output_format.lower(), + "--output", str(output_file), + ] + + if gene_id_to_name_map: + if not gene_id_to_name_map.is_file(): + raise FileNotFoundError(f"Gene ID to name map file not found: {gene_id_to_name_map}") + cmd.extend(["--id-to-name", str(gene_id_to_name_map)]) + + if cell_barcode_file: + if not cell_barcode_file.is_file(): + raise FileNotFoundError(f"Cell barcode file not found: {cell_barcode_file}") + cmd.extend(["--cell-barcodes", str(cell_barcode_file)]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + stdout = result.stdout + stderr = result.stderr + + output_files = [str(output_file)] if output_file.exists() else [] + + return { + "command_executed": " ".join(cmd), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"pyroe convert failed with exit code {e.returncode}: {e}", + "returncode": e.returncode, + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "error": "pyroe command not found. Is it installed and in your PATH?", + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyroe/app/pyroe_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyroe/app/pyroe_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ae318d810c3e4964064f3b3ab40819a9f1a3be1a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyroe/app/pyroe_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_pyroe/app/pyroe_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_pyroe' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyroe/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyroe/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..25e7f9f27f7f5b5de6ba28f45cb58432bd7a46b3 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyroe/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-pyroe: + build: . + image: mcp-pyroe:latest + container_name: mcp-pyroe + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=pyroe + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyroe/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyroe/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..471797530eee2dad6c86e39b7ce6339f40fd1f95 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyroe/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - pyroe + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyroe/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyroe/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyroe/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyvcf/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyvcf/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_pyvcf/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-acidbase/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-acidbase/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e9cb36742ecb3e7722c7286aa4f5dfe8c2ee27ad --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-acidbase/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install r-acidbase via conda (e.g., from bioconda) +RUN conda install -c bioconda r-acidbase -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/r-acidbase_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/r-acidbase_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/r-acidbase_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-acidbase/app/__pycache__/r-acidbase_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-acidbase/app/__pycache__/r-acidbase_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..db40e4f53a99d91366224e6c4b261d7222df274e Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-acidbase/app/__pycache__/r-acidbase_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-acidbase/app/r-acidbase_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-acidbase/app/r-acidbase_server.py new file mode 100644 index 0000000000000000000000000000000000000000..300417ed7b169f43a74db6b42fdcdef0247bc648 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-acidbase/app/r-acidbase_server.py @@ -0,0 +1,232 @@ +import subprocess +import json +from pathlib import Path +from typing import Optional, List, Union, Dict +import tempfile + +def _run_r_command(r_code: str) -> dict: + """ + Helper function to execute R code via Rscript. + """ + try: + # Ensure AcidBase is loaded + full_code = f"suppressPackageStartupMessages(library(AcidBase)); {r_code}" + result = subprocess.run( + ["Rscript", "-e", full_code], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e '{full_code}'", + "stdout": result.stdout.strip(), + "stderr": result.stderr.strip(), + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript -e '{r_code}'", + "stdout": e.stdout.strip() if e.stdout else "", + "stderr": e.stderr.strip() if e.stderr else str(e), + "status": "error" + } + except FileNotFoundError: + return { + "command_executed": "Rscript", + "stdout": "", + "stderr": "Rscript not found. Please ensure R is installed and in your PATH.", + "status": "error" + } + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_r_acidbase' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def detect_organism( + query: str +): + """ + Detect the organism from a character string (e.g., gene symbols, chromosome names, or Latin names). + + Args: + query: The string to analyze (e.g., 'Homo sapiens', 'ENSG000001', 'chr1'). + """ + # Input validation + if not query: + return {"error": "Query string cannot be empty"} + + r_code = f'cat(as.character(detectOrganism("{query}")))' + return _run_r_command(r_code) + +@mcp.tool() +def match_genes( + query: List[str], + subject: List[str] +): + """ + Match gene identifiers against a reference subject list. + + Args: + query: List of gene identifiers to match. + subject: List of reference gene identifiers. + """ + if not query or not subject: + return {"error": "Query and subject lists cannot be empty"} + + # Format lists for R vector syntax + query_r = "c(" + ",".join([f'"{q}"' for q in query]) + ")" + subject_r = "c(" + ",".join([f'"{s}"' for s in subject]) + ")" + + r_code = f'print(matchGenes(x = {query_r}, table = {subject_r}))' + return _run_r_command(r_code) + +@mcp.tool() +def init_project( + path: str, + force: bool = False +): + """ + Initialize a standard Acid Genomics project directory structure. + + Args: + path: Directory path where the project should be initialized. + force: Whether to overwrite existing files. + """ + project_path = Path(path) + # Validation + if not project_path.parent.exists(): + return {"error": f"Parent directory {project_path.parent} does not exist"} + + force_r = "TRUE" if force else "FALSE" + r_code = f'initProject(path = "{str(project_path)}", force = {force_r})' + return _run_r_command(r_code) + +@mcp.tool() +def check_dependencies( + packages: List[str] +): + """ + Check if required R packages are installed and meet version requirements. + + Args: + packages: List of R package names to check. + """ + if not packages: + return {"error": "Package list cannot be empty"} + + pkgs_r = "c(" + ",".join([f'"{p}"' for p in packages]) + ")" + r_code = f'checkDependencies({pkgs_r})' + return _run_r_command(r_code) + +@mcp.tool() +def render_report( + input_file: str, + output_dir: Optional[str] = None, + quiet: bool = False +): + """ + Render an RMarkdown report using Acid Genomics templates. + + Args: + input_file: Path to the .Rmd file. + output_dir: Directory to save the rendered report. + quiet: Whether to suppress RMarkdown rendering output. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file {input_file} not found"} + + out_dir_arg = f'"{output_dir}"' if output_dir else "NULL" + quiet_r = "TRUE" if quiet else "FALSE" + + r_code = f'renderReport(input = "{str(input_path)}", outputDir = {out_dir_arg}, quiet = {quiet_r})' + return _run_r_command(r_code) + +@mcp.tool() +def is_url( + path: str +): + """ + Check if a string is a valid URL. + + Args: + path: The string to check. + """ + r_code = f'cat(isUrl("{path}"))' + return _run_r_command(r_code) + +@mcp.tool() +def is_existing_file( + path: str +): + """ + Check if a file exists and is not a directory. + + Args: + path: File path to check. + """ + r_code = f'cat(isExistingFile("{path}"))' + return _run_r_command(r_code) + +@mcp.tool() +def get_session_info(): + """ + Get the current R session information including AcidBase version and dependencies. + """ + r_code = 'print(sessionInfo())' + return _run_r_command(r_code) + +@mcp.tool() +def acidbase_system_check(): + """ + Run low-level system environment checks (OS, GUI, ANSI support). + """ + r_code = ( + 'cat(paste0("OS: ", .Platform$OS.type, "\\n", ' + '"Unix: ", isUnix(), "\\n", ' + '"Windows: ", isWindows(), "\\n", ' + '"Mac: ", isMac(), "\\n", ' + '"ANSI Support: ", isAnsiSupported(), "\\n", ' + '"Interactive: ", isInteractive()))' + ) + return _run_r_command(r_code) + +@mcp.tool() +def make_names( + names: List[str], + unique: bool = True +): + """ + Make syntactically valid names for R (cleaning up strings for column names, etc.). + + Args: + names: List of strings to clean. + unique: Whether to ensure the resulting names are unique. + """ + if not names: + return {"error": "Names list cannot be empty"} + + names_r = "c(" + ",".join([f'"{n}"' for n in names]) + ")" + unique_r = "TRUE" if unique else "FALSE" + r_code = f'cat(makeNames({names_r}, unique = {unique_r}), sep = ", ")' + return _run_r_command(r_code) + +@mcp.tool() +def paste_url( + base_url: str, + path: str +): + """ + Safely concatenate a base URL and a path, ensuring correct slash handling. + + Args: + base_url: The base URL (e.g., 'https://acidgenomics.com'). + path: The path to append. + """ + r_code = f'cat(pasteURL("{base_url}", "{path}"))' + return _run_r_command(r_code) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-acidbase/app/r-acidbase_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-acidbase/app/r-acidbase_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9afcd27eafb1f7fb9f346aad383ebff3dc25abfe --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-acidbase/app/r-acidbase_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_r-acidbase/app/r-acidbase_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_r_acidbase' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-acidbase/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-acidbase/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-acidbase/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-acidbase/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-acidbase/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..42081d51e349cec76287749d056a820b006c2091 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-acidbase/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-r-acidbase: + build: . + image: mcp-r-acidbase:latest + container_name: mcp-r-acidbase + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=r-acidbase + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-acidbase/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-acidbase/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ec2a69adbb27db017ab3e62b538f4178f0f480aa --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-acidbase/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - r-acidbase + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-acidbase/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-acidbase/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-acidbase/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-cdseq/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-cdseq/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8a1152e40fe4583f21d8e63c6fdc43cf040b612f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-cdseq/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install r-cdseq via conda (e.g., from bioconda) +RUN conda install -c bioconda r-cdseq -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/r-cdseq_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/r-cdseq_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/r-cdseq_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-cdseq/app/__pycache__/r-cdseq_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-cdseq/app/__pycache__/r-cdseq_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cef2af684287783e25ae6c9c0db4db2395e60462 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-cdseq/app/__pycache__/r-cdseq_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-cdseq/app/r-cdseq_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-cdseq/app/r-cdseq_server.py new file mode 100644 index 0000000000000000000000000000000000000000..16c9eae66833059dae11a1418b8380c65b2ac65b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-cdseq/app/r-cdseq_server.py @@ -0,0 +1,349 @@ +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 tool(func): + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + return wrapper + +mcp = type("mcp", (), {"tool": tool}) + +@mcp.tool +def cdseq( + bulk_data: Path, + cell_type_number: str, + output_gep_path: Path, + output_prop_path: Path, + mcmc_iterations: int = 700, + dilution_factor: int = 10, + block_number: int = 5, + beta: float = 0.5, + alpha: float = 5.0, + gene_length: Optional[Path] = None, + reference_gep: Optional[Path] = None, + gene_subset_size: Optional[int] = None, + cpu_number: int = 1, + print_progress_msg_to_file: bool = False, +) -> Dict[str, Any]: + """ + Runs the CDSeq algorithm to deconvolve bulk RNA-Seq data. + + This tool estimates cell-type-specific gene expression profiles (GEPs) and + sample-specific cell-type proportions simultaneously from bulk sequencing data. + + Args: + bulk_data: Path to the input bulk RNA-Seq read counts data (e.g., CSV or TSV). + Rows should be genes and columns should be samples. + cell_type_number: A string representing the number of cell types to estimate. + Can be a single integer (e.g., "6"), a range (e.g., "2:10"), + or a comma-separated list (e.g., "2,4,6"). + output_gep_path: Path to save the estimated cell-type-specific GEPs (CSV format). + output_prop_path: Path to save the estimated cell-type proportions (CSV format). + mcmc_iterations: Number of MCMC iterations. Recommended: 700-2000. + dilution_factor: Dilution factor for the model. Recommended: 2-10. + block_number: Number of blocks for the Gibbs sampler. Recommended: >5. + beta: Hyperparameter for the Dirichlet distribution over cell types. + alpha: Hyperparameter for the Dirichlet distribution over genes. + gene_length: Optional path to a file containing gene lengths. + reference_gep: Optional path to a reference gene expression profile of pure cell lines. + gene_subset_size: Optional integer for the number of genes to subset for faster computation. + cpu_number: Number of CPU cores to use for parallel processing. + print_progress_msg_to_file: If True, prints progress messages to a file. + + Returns: + A dictionary containing the executed command, stdout, stderr, and paths to output files. + """ + # Input validation + if not bulk_data.is_file(): + raise FileNotFoundError(f"Input file not found: {bulk_data}") + if gene_length and not gene_length.is_file(): + raise FileNotFoundError(f"Gene length file not found: {gene_length}") + if reference_gep and not reference_gep.is_file(): + raise FileNotFoundError(f"Reference GEP file not found: {reference_gep}") + if mcmc_iterations <= 0: + raise ValueError("mcmc_iterations must be a positive integer.") + if cpu_number <= 0: + raise ValueError("cpu_number must be a positive integer.") + + # Ensure output directories exist + output_gep_path.parent.mkdir(parents=True, exist_ok=True) + output_prop_path.parent.mkdir(parents=True, exist_ok=True) + + # R script to be executed + r_script_content = f""" + library(optparse) + library(CDSeq) + + # Define command-line options + option_list <- list( + make_option("--bulk_data", type="character", help="Path to bulk data file"), + make_option("--cell_type_number", type="character", help="Cell type number(s)"), + make_option("--output_gep", type="character", help="Output path for estimated GEP"), + make_option("--output_prop", type="character", help="Output path for estimated proportions"), + make_option("--mcmc_iterations", type="integer", default={mcmc_iterations}), + make_option("--dilution_factor", type="integer", default={dilution_factor}), + make_option("--block_number", type="integer", default={block_number}), + make_option("--beta", type="double", default={beta}), + make_option("--alpha", type="double", default={alpha}), + make_option("--gene_length", type="character", default=NULL), + make_option("--reference_gep", type="character", default=NULL), + make_option("--gene_subset_size", type="integer", default=NULL), + make_option("--cpu_number", type="integer", default={cpu_number}), + make_option("--print_progress", type="logical", default={"TRUE" if print_progress_msg_to_file else "FALSE"}) + ) + + # Create a dummy parser to pass arguments directly + parser <- OptionParser(option_list=option_list) + args <- list( + bulk_data = "{bulk_data.resolve()}", + cell_type_number = "{cell_type_number}", + output_gep = "{output_gep_path.resolve()}", + output_prop = "{output_prop_path.resolve()}", + mcmc_iterations = {mcmc_iterations}, + dilution_factor = {dilution_factor}, + block_number = {block_number}, + beta = {beta}, + alpha = {alpha}, + gene_length = {"NULL" if gene_length is None else f"'{gene_length.resolve()}'"}, + reference_gep = {"NULL" if reference_gep is None else f"'{reference_gep.resolve()}'"}, + gene_subset_size = {"NULL" if gene_subset_size is None else gene_subset_size}, + cpu_number = {cpu_number}, + print_progress = {"TRUE" if print_progress_msg_to_file else "FALSE"} + ) + + # Load data - assuming CSV with row names as first column + bulk_data_matrix <- as.matrix(read.csv(args$bulk_data, row.names=1, check.names=FALSE)) + + # Parse cell_type_number + if (grepl(":", args$cell_type_number)) {{ + parts <- as.integer(strsplit(args$cell_type_number, ":")[[1]]) + cell_type_vector <- seq(parts[1], parts[2]) + }} else if (grepl(",", args$cell_type_number)) {{ + cell_type_vector <- as.integer(unlist(strsplit(args$cell_type_number, ","))) + }} else {{ + cell_type_vector <- as.integer(args$cell_type_number) + }} + + # Load optional data + gene_length_data <- NULL + if (!is.null(args$gene_length) && args$gene_length != "NULL") {{ + gene_length_data <- as.vector(read.csv(args$gene_length, header=FALSE)[[1]]) + }} + + reference_gep_data <- NULL + if (!is.null(args$reference_gep) && args$reference_gep != "NULL") {{ + reference_gep_data <- as.matrix(read.csv(args$reference_gep, row.names=1, check.names=FALSE)) + }} + + # Run CDSeq + result <- CDSeq( + bulk_data = bulk_data_matrix, + cell_type_number = cell_type_vector, + mcmc_iterations = args$mcmc_iterations, + dilution_factor = args$dilution_factor, + block_number = args$block_number, + beta = args$beta, + alpha = args$alpha, + gene_length = gene_length_data, + reference_gep = reference_gep_data, + gene_subset_size = args$gene_subset_size, + cpu_number = args$cpu_number, + print_progress_msg_to_file = args$print_progress + ) + + # Save results + write.csv(result$estGEP, file=args$output_gep) + write.csv(result$estProp, file=args$output_prop) + + print("CDSeq execution completed successfully.") + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = r_script_file.name + + cmd = ["Rscript", r_script_path] + command_executed = " ".join(cmd) + + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + "error": "CDSeq execution failed.", + } + finally: + Path(r_script_path).unlink() + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": { + "estimated_gep": str(output_gep_path), + "estimated_proportions": str(output_prop_path), + }, + } + +@mcp.tool +def cell_type_assign_scrna( + cdseq_gep: Path, + cdseq_prop: Path, + sc_gep: Path, + sc_annotation: Path, + output_dir: Path, + sc_pt_size: int = 3, + cdseq_pt_size: int = 6, + seurat_nfeatures: int = 100, + seurat_npcs: int = 50, + seurat_dims: str = "1:5", + plot_umap: bool = True, + plot_tsne: bool = False, +) -> Dict[str, Any]: + """ + Annotates CDSeq-estimated cell types using single-cell RNA-seq data. + + This tool aligns the estimated GEPs from CDSeq with a reference single-cell + dataset to assign identities to the deconvolved cell types. + + Args: + cdseq_gep: Path to CDSeq-estimated cell-type-specific GEPs (CSV format). + cdseq_prop: Path to CDSeq-estimated cell type proportions (CSV format). + sc_gep: Path to the single-cell RNA-seq reference GEP data (e.g., CSV). + sc_annotation: Path to the single-cell RNA-seq reference annotations (e.g., CSV). + output_dir: Directory to save the output plots and assignment results. + sc_pt_size: Point size for single-cell data in plots. + cdseq_pt_size: Point size for CDSeq data in plots. + seurat_nfeatures: Number of variable features to select in Seurat. + seurat_npcs: Number of principal components to use in Seurat. + seurat_dims: A string representing the dimensions to use for clustering, e.g., "1:5". + plot_umap: If True, generate and save a UMAP plot. + plot_tsne: If True, generate and save a t-SNE plot. + + Returns: + A dictionary containing the executed command, stdout, stderr, and paths to output files. + """ + # Input validation + if not cdseq_gep.is_file(): + raise FileNotFoundError(f"CDSeq GEP file not found: {cdseq_gep}") + if not cdseq_prop.is_file(): + raise FileNotFoundError(f"CDSeq proportions file not found: {cdseq_prop}") + if not sc_gep.is_file(): + raise FileNotFoundError(f"Single-cell GEP file not found: {sc_gep}") + if not sc_annotation.is_file(): + raise FileNotFoundError(f"Single-cell annotation file not found: {sc_annotation}") + if seurat_nfeatures <= 0 or seurat_npcs <= 0: + raise ValueError("Seurat features and NPCs must be positive integers.") + + # Ensure output directory exists + output_dir.mkdir(parents=True, exist_ok=True) + + # R script to be executed + r_script_content = f""" + library(CDSeq) + library(ggplot2) + + # Load inputs + cdseq_gep_data <- as.matrix(read.csv("{cdseq_gep.resolve()}", row.names=1, check.names=FALSE)) + cdseq_prop_data <- as.matrix(read.csv("{cdseq_prop.resolve()}", row.names=1, check.names=FALSE)) + sc_gep_data <- as.matrix(read.csv("{sc_gep.resolve()}", row.names=1, check.names=FALSE)) + sc_annotation_data <- read.csv("{sc_annotation.resolve()}", header=TRUE, row.names=1) + + # Parse seurat_dims + dims_parts <- as.integer(strsplit("{seurat_dims}", ":")[[1]]) + seurat_dims_vec <- seq(dims_parts[1], dims_parts[2]) + + # Run cell type assignment + cdseq_result_celltypeassign <- cellTypeAssignSCRNA( + cdseq_gep = cdseq_gep_data, + cdseq_prop = cdseq_prop_data, + sc_gep = sc_gep_data, + sc_annotation = sc_annotation_data, + sc_pt_size = {sc_pt_size}, + cdseq_pt_size = {cdseq_pt_size}, + seurat_nfeatures = {seurat_nfeatures}, + seurat_npcs = {seurat_npcs}, + seurat_dims = seurat_dims_vec, + plot_umap = {"TRUE" if plot_umap else "FALSE"}, + plot_tsne = {"TRUE" if plot_tsne else "FALSE"} + ) + + # Save outputs + output_files <- list() + if ({str(plot_umap).upper()}) {{ + umap_path <- file.path("{output_dir.resolve()}", "umap_plot.pdf") + ggsave(umap_path, plot = cdseq_result_celltypeassign$UMAP, device = "pdf") + output_files[["umap_plot"]] <- umap_path + }} + if ({str(plot_tsne).upper()}) {{ + tsne_path <- file.path("{output_dir.resolve()}", "tsne_plot.pdf") + ggsave(tsne_path, plot = cdseq_result_celltypeassign$tSNE, device = "pdf") + output_files[["tsne_plot"]] <- tsne_path + }} + + # Save the assignment results table + assignments_path <- file.path("{output_dir.resolve()}", "cell_type_assignments.csv") + write.csv(cdseq_result_celltypeassign$cellTypeMappings, file = assignments_path) + output_files[["assignments_table"]] <- assignments_path + + print("cellTypeAssignSCRNA execution completed successfully.") + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script_file: + r_script_file.write(r_script_content) + r_script_path = r_script_file.name + + cmd = ["Rscript", r_script_path] + command_executed = " ".join(cmd) + + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + "error": "cellTypeAssignSCRNA execution failed.", + } + finally: + Path(r_script_path).unlink() + + # Collect output file paths + output_files_list: List[str] = [] + if plot_umap: + output_files_list.append(str(output_dir / "umap_plot.pdf")) + if plot_tsne: + output_files_list.append(str(output_dir / "tsne_plot.pdf")) + output_files_list.append(str(output_dir / "cell_type_assignments.csv")) + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": { + "directory": str(output_dir), + "files": output_files_list + }, + } \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-cdseq/app/r-cdseq_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-cdseq/app/r-cdseq_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e715c3058871e9abee9162c68429cd5ba7d7d417 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-cdseq/app/r-cdseq_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_r-cdseq/app/r-cdseq_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_r_cdseq' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-cdseq/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-cdseq/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-cdseq/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-cdseq/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-cdseq/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..835db45cf42d96b7d807d42bc677eca5a72ed50c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-cdseq/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-r-cdseq: + build: . + image: mcp-r-cdseq:latest + container_name: mcp-r-cdseq + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=r-cdseq + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-cdseq/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-cdseq/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6c11becc02421803a142b94b203f7b9e5fc7d65b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-cdseq/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - r-cdseq + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-cdseq/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-cdseq/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-cdseq/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-sceasy/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-sceasy/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4fe16d19726de622200dc23a9d15203ecb07ea36 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-sceasy/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install r-sceasy via conda (e.g., from bioconda) +RUN conda install -c bioconda r-sceasy -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/r-sceasy_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/r-sceasy_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/r-sceasy_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-sceasy/app/__pycache__/r-sceasy_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-sceasy/app/__pycache__/r-sceasy_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a4b5af4a345aba1af7a99ba9e0d89b5f14f4f9f Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-sceasy/app/__pycache__/r-sceasy_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-sceasy/app/r-sceasy_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-sceasy/app/r-sceasy_server.py new file mode 100644 index 0000000000000000000000000000000000000000..15aca11c796dfc9feb47e76f0cacb7063627aad9 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-sceasy/app/r-sceasy_server.py @@ -0,0 +1,151 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Dict, List, Literal, Union + +# @mcp.tool() decorator is commented out as per the instructions +# to only provide the function body for the final output. +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_r_sceasy' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def convert_format( + input_file: Path, + from_format: Literal["seurat", "anndata", "sce", "loom"], + to_format: Literal["anndata", "seurat", "sce", "loom"], + out_file: Path, +) -> Dict[str, Union[str, List[str]]]: + """ + Converts single-cell data between different formats using the r-sceasy R package. + + This tool wraps the `sceasy::convertFormat` R function to convert between + Seurat (.rds), AnnData (.h5ad), SingleCellExperiment (sce, .rds), and Loom (.loom) formats. + + Args: + input_file: Path to the input single-cell data file. + from_format: The format of the input file. + to_format: The desired format for the output file. + out_file: Path to the output file. The extension should match the `to_format`. + + Returns: + A dictionary containing the execution details and output file path. + """ + # 1. Input Validation + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + if out_file.is_dir(): + raise IsADirectoryError(f"Output file path cannot be a directory: {out_file}") + + if not out_file.parent.exists(): + out_file.parent.mkdir(parents=True, exist_ok=True) + + if from_format == to_format: + raise ValueError("from_format and to_format cannot be the same.") + + valid_conversions = { + ("seurat", "anndata"), + ("anndata", "seurat"), + ("seurat", "sce"), + ("sce", "anndata"), + ("sce", "loom"), + ("loom", "anndata"), + ("loom", "sce"), + } + if (from_format, to_format) not in valid_conversions: + raise ValueError( + f"Conversion from '{from_format}' to '{to_format}' is not a supported " + "path in sceasy. Valid conversions are: seurat<->anndata, seurat->sce, " + "sce->anndata, sce->loom, loom->anndata, loom->sce." + ) + + # 2. R Script Generation + # The R script loads the necessary libraries, reads the input object + # (either from an .rds file or by using the path directly for .h5ad/.loom), + # and then calls the conversion function. + r_script_content = f""" + # Suppress package startup messages for cleaner output + suppressPackageStartupMessages(library(sceasy)) + suppressPackageStartupMessages(library(Seurat)) + suppressPackageStartupMessages(library(SingleCellExperiment)) + + # Define paths and formats from arguments + input_path <- "{input_file.resolve()}" + output_path <- "{out_file.resolve()}" + from_format <- "{from_format}" + to_format <- "{to_format}" + + # Load input object if it's an R object format (.rds) + if (from_format %in% c("seurat", "sce")) {{ + message(paste("Loading R object from:", input_path)) + input_object <- readRDS(input_path) + }} else {{ + # For anndata (.h5ad) and loom (.loom), the path itself is the input object + message(paste("Using file path as input:", input_path)) + input_object <- input_path + }} + + # Perform the conversion with error handling + message(paste("Converting from", from_format, "to", to_format)) + tryCatch({{ + sceasy::convertFormat( + obj = input_object, + from = from_format, + to = to_format, + outFile = output_path + ) + message(paste("Conversion complete. Output saved to:", output_path)) + }}, error = function(e) {{ + # Print error message and exit with a non-zero status code + message("An error occurred during conversion:") + message(conditionMessage(e)) + quit(status = 1, save = "no") + }}) + """ + + # 3. Subprocess Execution + command_executed = "" + stdout_str = "" + stderr_str = "" + + try: + with tempfile.NamedTemporaryFile( + mode="w", suffix=".R", delete=True, dir="." + ) as tmp_script: + tmp_script.write(r_script_content) + tmp_script.flush() + + command = ["Rscript", tmp_script.name] + command_executed = " ".join(command) + + process = subprocess.run( + command, capture_output=True, text=True, check=True + ) + stdout_str = process.stdout + stderr_str = process.stderr + + except subprocess.CalledProcessError as e: + # R script is designed to print errors to stdout via message(), + # so we combine stdout and stderr for a complete error report. + error_message = ( + f"R script execution failed with exit code {e.returncode}.\n" + f"Command: {command_executed}\n" + f"--- STDOUT ---\n{e.stdout}\n" + f"--- STDERR ---\n{e.stderr}" + ) + raise RuntimeError(error_message) from e + + # 4. Structured Result Return + output_files = [str(out_file.resolve())] if out_file.exists() else [] + + return { + "command_executed": command_executed, + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": output_files, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-sceasy/app/r-sceasy_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-sceasy/app/r-sceasy_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e9a48a90587cd40d5681a18da0c797ad3de3e122 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-sceasy/app/r-sceasy_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_r-sceasy/app/r-sceasy_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_r_sceasy' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-sceasy/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-sceasy/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-sceasy/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-sceasy/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-sceasy/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c5a5d80ed8a3179820255a84a492c79becccf0e0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-sceasy/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-r-sceasy: + build: . + image: mcp-r-sceasy:latest + container_name: mcp-r-sceasy + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=r-sceasy + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-sceasy/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-sceasy/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a24c7819a38a3eae96ae31e8c20eae98c006647c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-sceasy/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - r-sceasy + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-sceasy/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-sceasy/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-sceasy/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-scopfunctions/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-scopfunctions/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cb7fa323882d8ffc4d4d856482105ea355ee93fb --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-scopfunctions/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install r-scopfunctions via conda (e.g., from bioconda) +RUN conda install -c bioconda r-scopfunctions -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/r-scopfunctions_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/r-scopfunctions_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/r-scopfunctions_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-scopfunctions/app/__pycache__/r-scopfunctions_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-scopfunctions/app/__pycache__/r-scopfunctions_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..7d0f823e5ced60ff55b742b63738e1a3c408adfd Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-scopfunctions/app/__pycache__/r-scopfunctions_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-scopfunctions/app/r-scopfunctions_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-scopfunctions/app/r-scopfunctions_server.py new file mode 100644 index 0000000000000000000000000000000000000000..521f5fcc476a52850f9c74175ce7aa00693056db --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-scopfunctions/app/r-scopfunctions_server.py @@ -0,0 +1,719 @@ +import subprocess +import tempfile +import shutil +from pathlib import Path +from typing import Optional, List + +# @mcp.tool() decorator is commented out as per instructions +# but is intended to be used in a real MCP environment. + + +def _run_r_script(r_script: str, args: List[str]) -> subprocess.CompletedProcess: + """ + Helper function to run an R script using a temporary file. + + Args: + r_script: A string containing the R code to execute. + args: A list of command-line arguments for the R script. + + Returns: + A CompletedProcess object. + """ + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_script: + tmp_script.write(r_script) + script_path = tmp_script.name + + try: + command = ["Rscript", script_path] + args + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + return result + finally: + Path(script_path).unlink() + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_r_scopfunctions' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def prep_hto_q_area_plot( + seurat_obj_path: Path, + output_plot_path: Path, + quantile_range: str = "0.8,0.99,0.01", + n_cores: Optional[int] = None +): + """ + Generates an area plot showing how proportions of singlets, doublets, and negatives vary with the positive quantile. + + Args: + seurat_obj_path: Path to the input Seurat object file (.rds). + output_plot_path: Path to save the output plot file (e.g., plot.pdf or plot.png). + quantile_range: A string representing the sequence of quantiles to test, in the format "start,end,step". + n_cores: Maximum number of cores to use. If None, uses all available cores. + """ + if not seurat_obj_path.is_file(): + raise FileNotFoundError(f"Input Seurat object not found at {seurat_obj_path}") + + r_script = """ + library(SCOPfunctions) + library(Seurat) + library(ggplot2) + + args <- commandArgs(trailingOnly = TRUE) + seurat_obj_path <- args[1] + output_plot_path <- args[2] + quantile_range_str <- args[3] + n_cores_str <- args[4] + + seurat_obj <- readRDS(seurat_obj_path) + + q_params <- as.numeric(strsplit(quantile_range_str, ",")[[1]]) + if (length(q_params) != 3) { + stop("quantile_range must be a string of three comma-separated numbers: start,end,step") + } + vec_range_quantile <- seq(q_params[1], q_params[2], q_params[3]) + + n_cores_max <- if (n_cores_str == "None") Inf else as.integer(n_cores_str) + + p_quantile <- SCOPfunctions::prep_HTO_q_area_plot( + seurat_obj = seurat_obj, + vec_range_quantile = vec_range_quantile, + n_cores_max = n_cores_max + ) + + ggsave(output_plot_path, plot = p_quantile, width = 8, height = 6) + """ + + args = [ + str(seurat_obj_path), + str(output_plot_path), + quantile_range, + str(n_cores) + ] + + try: + result = _run_r_script(r_script, args) + return { + "command_executed": f"Rscript ... { ' '.join(args) }", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_plot_path)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript ... { ' '.join(args) }", + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } + + +@mcp.tool() +def prep_intrahash_doub( + seurat_obj_path: Path, + output_seurat_obj_path: Path, + assay: str = "RNA", + npcs: int = 20, + random_seed: int = 12345 +): + """ + Infers intra-hash doublets using inter-hash doublets from a demultiplexed Seurat object. + + Args: + seurat_obj_path: Path to the input Seurat object file (.rds). + output_seurat_obj_path: Path to save the updated Seurat object file (.rds). + assay: The assay to use for the analysis. + npcs: Number of principal components to use. + random_seed: Random seed for reproducibility. + """ + if not seurat_obj_path.is_file(): + raise FileNotFoundError(f"Input Seurat object not found at {seurat_obj_path}") + if npcs <= 0: + raise ValueError("npcs must be a positive integer.") + + r_script = """ + library(SCOPfunctions) + library(Seurat) + + args <- commandArgs(trailingOnly = TRUE) + seurat_obj_path <- args[1] + output_seurat_obj_path <- args[2] + assay <- args[3] + npcs <- as.integer(args[4]) + random_seed <- as.integer(args[5]) + + seurat_obj <- readRDS(seurat_obj_path) + + updated_seurat_obj <- SCOPfunctions::prep_intrahash_doub( + seurat_obj = seurat_obj, + assay = assay, + npcs = npcs, + randomSeed = random_seed + ) + + saveRDS(updated_seurat_obj, file = output_seurat_obj_path) + """ + + args = [ + str(seurat_obj_path), + str(output_seurat_obj_path), + assay, + str(npcs), + str(random_seed) + ] + + try: + result = _run_r_script(r_script, args) + return { + "command_executed": f"Rscript ... { ' '.join(args) }", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_seurat_obj_path)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript ... { ' '.join(args) }", + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } + + +@mcp.tool() +def prep_qc_rna( + seurat_obj_path: Path, + output_seurat_obj_path: Path, + assay: str = "RNA" +): + """ + Performs standard quality control on the RNA assay of a Seurat object. + + Args: + seurat_obj_path: Path to the input Seurat object file (.rds). + output_seurat_obj_path: Path to save the updated Seurat object file (.rds). + assay: The RNA assay to perform QC on. + """ + if not seurat_obj_path.is_file(): + raise FileNotFoundError(f"Input Seurat object not found at {seurat_obj_path}") + + r_script = """ + library(SCOPfunctions) + library(Seurat) + + args <- commandArgs(trailingOnly = TRUE) + seurat_obj_path <- args[1] + output_seurat_obj_path <- args[2] + assay <- args[3] + + seurat_obj <- readRDS(seurat_obj_path) + + updated_seurat_obj <- SCOPfunctions::prep_qc_rna( + seurat_obj = seurat_obj, + assay = assay + ) + + saveRDS(updated_seurat_obj, file = output_seurat_obj_path) + """ + + args = [ + str(seurat_obj_path), + str(output_seurat_obj_path), + assay + ] + + try: + result = _run_r_script(r_script, args) + return { + "command_executed": f"Rscript ... { ' '.join(args) }", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_seurat_obj_path)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript ... { ' '.join(args) }", + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } + + +@mcp.tool() +def de_mast_re_seurat( + seurat_obj_path: Path, + output_csv_path: Path, + ident_1: str, + group_by: str, + random_effect_vars: Optional[str] = None, + test_use: str = "MAST" +): + """ + Finds differentially expressed genes using MAST with random effects. + + Args: + seurat_obj_path: Path to the input Seurat object file (.rds). + output_csv_path: Path to save the output CSV file with DE results. + ident_1: The identity class to test (e.g., a cluster ID). + group_by: The metadata column containing the cell groups (e.g., 'seurat_clusters'). + random_effect_vars: Comma-separated string of metadata variables to use as random effects. + test_use: The differential expression test to use. + """ + if not seurat_obj_path.is_file(): + raise FileNotFoundError(f"Input Seurat object not found at {seurat_obj_path}") + + r_script = """ + library(SCOPfunctions) + library(Seurat) + + args <- commandArgs(trailingOnly = TRUE) + seurat_obj_path <- args[1] + output_csv_path <- args[2] + ident_1 <- args[3] + group_by <- args[4] + random_effect_vars_str <- args[5] + test_use <- args[6] + + seurat_obj <- readRDS(seurat_obj_path) + + random_effect.vars <- if (random_effect_vars_str == "None") NULL else strsplit(random_effect_vars_str, ",")[[1]] + + df_DE <- SCOPfunctions::DE_MAST_RE_seurat( + object = seurat_obj, + ident.1 = ident_1, + group.by = group_by, + random_effect.vars = random_effect.vars, + test.use = test_use + ) + + write.csv(df_DE, file = output_csv_path, row.names = TRUE) + """ + + args = [ + str(seurat_obj_path), + str(output_csv_path), + ident_1, + group_by, + str(random_effect_vars), + test_use + ] + + try: + result = _run_r_script(r_script, args) + return { + "command_executed": f"Rscript ... { ' '.join(args) }", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_csv_path)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript ... { ' '.join(args) }", + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } + + +@mcp.tool() +def geneset_embed_list_seurat( + seurat_obj_path: Path, + geneset_list_path: Path, + output_seurat_obj_path: Path, + assay: str = "SCT", + slot: str = "scale.data", + min_feats_present: int = 5, + n_cores: Optional[int] = None +): + """ + Calculates activity values (embeddings) for a list of genesets and adds them to the Seurat object. + + Args: + seurat_obj_path: Path to the input Seurat object file (.rds). + geneset_list_path: Path to a 3-column TSV/CSV file (geneset, gene, weight) defining the genesets. + output_seurat_obj_path: Path to save the updated Seurat object file (.rds). + assay: Assay to use for expression data. + slot: Slot in the assay to use for expression data. + min_feats_present: Minimum number of genes from a set that must be present in the data. + n_cores: Maximum number of cores to use. If None, uses all available cores. + """ + if not seurat_obj_path.is_file(): + raise FileNotFoundError(f"Input Seurat object not found at {seurat_obj_path}") + if not geneset_list_path.is_file(): + raise FileNotFoundError(f"Geneset list file not found at {geneset_list_path}") + if min_feats_present < 1: + raise ValueError("min_feats_present must be at least 1.") + + r_script = """ + library(SCOPfunctions) + library(Seurat) + library(data.table) + + args <- commandArgs(trailingOnly = TRUE) + seurat_obj_path <- args[1] + geneset_list_path <- args[2] + output_seurat_obj_path <- args[3] + assay <- args[4] + slot <- args[5] + min_feats_present <- as.integer(args[6]) + n_cores_str <- args[7] + + seurat_obj <- readRDS(seurat_obj_path) + + geneset_df <- fread(geneset_list_path) + if (ncol(geneset_df) != 3) { + stop("geneset_list_path file must have 3 columns: geneset, gene, weight") + } + list_vec_geneWeights <- split( + setNames(geneset_df[[3]], geneset_df[[2]]), + geneset_df[[1]] + ) + + n_cores_max <- if (n_cores_str == "None") Inf else as.integer(n_cores_str) + + updated_seurat_obj <- geneset_embed_list_seurat( + seurat_obj = seurat_obj, + list_vec_geneWeights = list_vec_geneWeights, + slot = slot, + assay = assay, + min_feats_present = min_feats_present, + n_cores_max = n_cores_max + ) + + saveRDS(updated_seurat_obj, file = output_seurat_obj_path) + """ + + args = [ + str(seurat_obj_path), + str(geneset_list_path), + str(output_seurat_obj_path), + assay, + slot, + str(min_feats_present), + str(n_cores) + ] + + try: + result = _run_r_script(r_script, args) + return { + "command_executed": f"Rscript ... { ' '.join(args) }", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_seurat_obj_path)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript ... { ' '.join(args) }", + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } + + +@mcp.tool() +def plot_bar_ident_group( + seurat_obj_path: Path, + output_plot_path: Path, + var_ident: str, + var_group: str, + color_palette: Optional[str] = "RdYlBu" +): + """ + Plots the distribution of cell identities (e.g., samples) across different groups (e.g., clusters). + + Args: + seurat_obj_path: Path to the input Seurat object file (.rds). + output_plot_path: Path to save the output plot file (e.g., plot.pdf or plot.png). + var_ident: Metadata variable for identity (e.g., 'sample_ID'). + var_group: Metadata variable for grouping (e.g., 'cluster'). + color_palette: Name of an RColorBrewer palette to use for coloring. + """ + if not seurat_obj_path.is_file(): + raise FileNotFoundError(f"Input Seurat object not found at {seurat_obj_path}") + + r_script = """ + library(SCOPfunctions) + library(Seurat) + library(ggplot2) + library(RColorBrewer) + + args <- commandArgs(trailingOnly = TRUE) + seurat_obj_path <- args[1] + output_plot_path <- args[2] + var_ident <- args[3] + var_group <- args[4] + color_palette_name <- args[5] + + seurat_obj <- readRDS(seurat_obj_path) + + f_color_func <- NULL + if (color_palette_name != "None") { + max_colors <- brewer.pal.info[color_palette_name, "maxcolors"] + f_color_func <- colorRampPalette(brewer.pal(n = max_colors, name = color_palette_name)) + } + + plot_obj <- plot_barIdentGroup( + seurat_obj = seurat_obj, + var_ident = var_ident, + var_group = var_group, + vec_group_colors = NULL, + f_color = f_color_func, + do_plot = FALSE + ) + + ggsave(output_plot_path, plot = plot_obj, width = 10, height = 7) + """ + + args = [ + str(seurat_obj_path), + str(output_plot_path), + var_ident, + var_group, + str(color_palette) + ] + + try: + result = _run_r_script(r_script, args) + return { + "command_executed": f"Rscript ... { ' '.join(args) }", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_plot_path)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript ... { ' '.join(args) }", + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } + + +@mcp.tool() +def plot_vln_grid( + seurat_obj_path: Path, + output_plot_path: Path, + features: str, + var_group: str, + slot: str = "data", + color_palette: Optional[str] = "RdYlBu" +): + """ + Plots a grid of violin plots showing gene expression across cell groups. + + Args: + seurat_obj_path: Path to the input Seurat object file (.rds). + output_plot_path: Path to save the output plot file (e.g., plot.pdf or plot.png). + features: A comma-separated string of features (genes) to plot. + var_group: Metadata variable for grouping (e.g., 'cluster'). + slot: Data slot to use for expression values. + color_palette: Name of an RColorBrewer palette to use for coloring. + """ + if not seurat_obj_path.is_file(): + raise FileNotFoundError(f"Input Seurat object not found at {seurat_obj_path}") + + r_script = """ + library(SCOPfunctions) + library(Seurat) + library(ggplot2) + library(RColorBrewer) + + args <- commandArgs(trailingOnly = TRUE) + seurat_obj_path <- args[1] + output_plot_path <- args[2] + features_str <- args[3] + var_group <- args[4] + slot <- args[5] + color_palette_name <- args[6] + + seurat_obj <- readRDS(seurat_obj_path) + + vec_features <- strsplit(features_str, ",")[[1]] + + f_color_func <- NULL + if (color_palette_name != "None") { + max_colors <- brewer.pal.info[color_palette_name, "maxcolors"] + f_color_func <- colorRampPalette(brewer.pal(n = max_colors, name = color_palette_name)) + } + + plot_obj <- plot_vlnGrid( + seurat_obj = seurat_obj, + slot = slot, + var_group = var_group, + vec_features = vec_features, + vec_group_colors = NULL, + f_color = f_color_func + ) + + n_features <- length(vec_features) + plot_height <- 3 * ceiling(n_features / 3) + plot_width <- 12 + + ggsave(output_plot_path, plot = plot_obj, width = plot_width, height = plot_height, limitsize = FALSE) + """ + + args = [ + str(seurat_obj_path), + str(output_plot_path), + features, + var_group, + slot, + str(color_palette) + ] + + try: + result = _run_r_script(r_script, args) + return { + "command_executed": f"Rscript ... { ' '.join(args) }", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_plot_path)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript ... { ' '.join(args) }", + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } + + +@mcp.tool() +def plot_network( + seurat_obj_path: Path, + gene_importance_path: Path, + output_plot_path: Path, + assay: str = "RNA", + slot: str = "data", + genes_to_highlight: Optional[str] = None, + max_genes: int = 50, + layout_algorithm: str = "drl", + label_font: str = "bold.italic", + edge_color: str = "grey70", + edge_thickness: float = 1.0 +): + """ + Generates a network plot of co-expressed features. + + Args: + seurat_obj_path: Path to the input Seurat object file (.rds). + gene_importance_path: Path to a 2-column TSV/CSV file (gene, importance) for weighting genes in the network. + output_plot_path: Path to save the output plot file (e.g., plot.pdf or plot.png). + assay: Assay to use for expression data. + slot: Slot in the assay to use for expression data. + genes_to_highlight: Comma-separated string of gene names to highlight in the plot. + max_genes: Maximum number of genes to include in the network plot. + layout_algorithm: The igraph layout algorithm to use (e.g., 'drl', 'fr', 'kk'). + label_font: Font face for labels (e.g., 'plain', 'bold', 'italic', 'bold.italic'). + edge_color: Color of the network edges. + edge_thickness: Thickness of the network edges. + """ + if not seurat_obj_path.is_file(): + raise FileNotFoundError(f"Input Seurat object not found at {seurat_obj_path}") + if not gene_importance_path.is_file(): + raise FileNotFoundError(f"Gene importance file not found at {gene_importance_path}") + if max_genes <= 0: + raise ValueError("max_genes must be a positive integer.") + + output_suffix = output_plot_path.suffix.lower() + if output_suffix not in ['.pdf', '.png']: + raise ValueError("output_plot_path must have a .pdf or .png extension.") + output_format = output_suffix[1:] + + r_script = """ + library(SCOPfunctions) + library(Seurat) + library(data.table) + + args <- commandArgs(trailingOnly = TRUE) + seurat_obj_path <- args[1] + gene_importance_path <- args[2] + output_plot_path <- args[3] + assay <- args[4] + slot <- args[5] + genes_to_highlight_str <- args[6] + max_genes <- as.integer(args[7]) + layout_algorithm <- args[8] + label_font <- args[9] + edge_color <- args[10] + edge_thickness <- as.numeric(args[11]) + output_format <- args[12] + + seurat_obj <- readRDS(seurat_obj_path) + + gene_importance_df <- fread(gene_importance_path) + if (ncol(gene_importance_df) != 2) { + stop("gene_importance_path file must have 2 columns: gene, importance") + } + vec_geneImportance <- setNames(gene_importance_df[[2]], gene_importance_df[[1]]) + + mat_datExpr <- as.matrix(GetAssayData(seurat_obj, slot = slot, assay = assay)) + + vec_genes_highlight <- if (genes_to_highlight_str == "None") c() else strsplit(genes_to_highlight_str, ",")[[1]] + + if (output_format == "png") { + png(output_plot_path, width = 10, height = 10, units = "in", res = 300) + } else { + pdf(output_plot_path, width = 10, height = 10) + } + + SCOPfunctions::plot_network( + mat_datExpr = mat_datExpr, + vec_geneImportance = vec_geneImportance, + vec_genes_highlight = vec_genes_highlight, + n_max_genes = max_genes, + igraph_algorithm = layout_algorithm, + fontface_labels = label_font, + color_edge = edge_color, + edge_thickness = edge_thickness + ) + dev.off() + """ + + args = [ + str(seurat_obj_path), + str(gene_importance_path), + str(output_plot_path), + assay, + slot, + str(genes_to_highlight), + str(max_genes), + layout_algorithm, + label_font, + edge_color, + str(edge_thickness), + output_format + ] + + try: + result = _run_r_script(r_script, args) + return { + "command_executed": f"Rscript ... { ' '.join(args) }", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_plot_path)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript ... { ' '.join(args) }", + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-scopfunctions/app/r-scopfunctions_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-scopfunctions/app/r-scopfunctions_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e08e15a31da8e47209cff1df6a6d7ea5647c43c2 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-scopfunctions/app/r-scopfunctions_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_r-scopfunctions/app/r-scopfunctions_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_r_scopfunctions' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-scopfunctions/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-scopfunctions/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-scopfunctions/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-scopfunctions/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-scopfunctions/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..41e95ba8beb36159f0335cdb59330caaa3d7e935 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-scopfunctions/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-r-scopfunctions: + build: . + image: mcp-r-scopfunctions:latest + container_name: mcp-r-scopfunctions + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=r-scopfunctions + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-scopfunctions/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-scopfunctions/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3aaeafcf554ff0d9f092deb65711815cfbb2ad7a --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-scopfunctions/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - r-scopfunctions + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-scopfunctions/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-scopfunctions/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-scopfunctions/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-seurat/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-seurat/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..76344dfbe56dfa5f0cc9c6e2a91db9442b7e7892 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-seurat/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install r-seurat via conda (e.g., from bioconda) +RUN conda install -c bioconda r-seurat -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY r-seurat_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/r-seurat_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/r-seurat_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-seurat/app/__pycache__/r-seurat_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-seurat/app/__pycache__/r-seurat_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95d4fac2d49762ab0b1c0ce99e8e9bd0b0bf2d31 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-seurat/app/__pycache__/r-seurat_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-seurat/app/r-seurat_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-seurat/app/r-seurat_server.py new file mode 100644 index 0000000000000000000000000000000000000000..182f4daa9eb08061771a5818836dc3ffbecdc744 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-seurat/app/r-seurat_server.py @@ -0,0 +1,271 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +def run_r_command(script: str) -> Dict[str, Any]: + """Helper to execute R code via Rscript and handle errors.""" + try: + # We use -e to execute the expression directly + result = subprocess.run( + ["Rscript", "-e", script], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"Rscript -e \"{script}\"", + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript -e \"{script}\"", + "stdout": e.stdout, + "stderr": e.stderr, + "status": "error", + "error_message": str(e) + } + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_r_seurat' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def seurat_create_from_csv( + input_csv: str, + output_rds: str, + project_name: str = "SeuratProject", + min_cells: int = 3, + min_features: int = 200, +): + """ + Initialize a Seurat object from a CSV count matrix (genes as rows, cells as columns). + """ + input_path = Path(input_csv) + output_path = Path(output_rds) + + if not input_path.exists(): + return {"error": f"Input file {input_csv} not found."} + + r_code = ( + f"library(Seurat); " + f"counts <- read.csv('{input_path}', row.names = 1, check.names = FALSE); " + f"obj <- CreateSeuratObject(counts = counts, project = '{project_name}', " + f"min.cells = {min_cells}, min.features = {min_features}); " + f"saveRDS(obj, '{output_path}')" + ) + + result = run_r_command(r_code) + result["output_files"] = [str(output_path)] if output_path.exists() else [] + return result + +@mcp.tool() +def seurat_normalize_data( + input_rds: str, + output_rds: str, + normalization_method: str = "LogNormalize", + scale_factor: int = 10000, +): + """ + Normalize the Seurat object data. + """ + input_path = Path(input_rds) + output_path = Path(output_rds) + + if not input_path.exists(): + return {"error": f"Input RDS {input_rds} not found."} + + r_code = ( + f"library(Seurat); " + f"obj <- readRDS('{input_path}'); " + f"obj <- NormalizeData(obj, normalization.method = '{normalization_method}', " + f"scale.factor = {scale_factor}); " + f"saveRDS(obj, '{output_path}')" + ) + + result = run_r_command(r_code) + result["output_files"] = [str(output_path)] if output_path.exists() else [] + return result + +@mcp.tool() +def seurat_find_variable_features( + input_rds: str, + output_rds: str, + selection_method: str = "vst", + n_features: int = 2000, +): + """ + Identify highly variable features in the dataset. + """ + input_path = Path(input_rds) + output_path = Path(output_rds) + + if not input_path.exists(): + return {"error": f"Input RDS {input_rds} not found."} + + r_code = ( + f"library(Seurat); " + f"obj <- readRDS('{input_path}'); " + f"obj <- FindVariableFeatures(obj, selection.method = '{selection_method}', " + f"nfeatures = {n_features}); " + f"saveRDS(obj, '{output_path}')" + ) + + result = run_r_command(r_code) + result["output_files"] = [str(output_path)] if output_path.exists() else [] + return result + +@mcp.tool() +def seurat_scale_and_pca( + input_rds: str, + output_rds: str, + npcs: int = 50, + vars_to_regress: Optional[List[str]] = None, +): + """ + Scales data and runs Principal Component Analysis (PCA). + """ + input_path = Path(input_rds) + output_path = Path(output_rds) + + if not input_path.exists(): + return {"error": f"Input RDS {input_rds} not found."} + + regress_cmd = "NULL" + if vars_to_regress: + regress_cmd = "c(" + ",".join([f"'{v}'" for v in vars_to_regress]) + ")" + + r_code = ( + f"library(Seurat); " + f"obj <- readRDS('{input_path}'); " + f"obj <- ScaleData(obj, vars.to.regress = {regress_cmd}); " + f"obj <- RunPCA(obj, npcs = {npcs}, verbose = FALSE); " + f"saveRDS(obj, '{output_path}')" + ) + + result = run_r_command(r_code) + result["output_files"] = [str(output_path)] if output_path.exists() else [] + return result + +@mcp.tool() +def seurat_cluster_and_umap( + input_rds: str, + output_rds: str, + dims_to_use: int = 20, + resolution: float = 0.5, + run_umap: bool = True, + run_tsne: bool = False, +): + """ + Find neighbors, identify clusters, and run UMAP/tSNE dimensionality reduction. + """ + input_path = Path(input_rds) + output_path = Path(output_rds) + + if not input_path.exists(): + return {"error": f"Input RDS {input_rds} not found."} + + umap_cmd = "obj <- RunUMAP(obj, dims = 1:dims_to_use);" if run_umap else "" + tsne_cmd = "obj <- RunTSNE(obj, dims = 1:dims_to_use);" if run_tsne else "" + + r_code = ( + f"library(Seurat); " + f"obj <- readRDS('{input_path}'); " + f"dims_to_use <- {dims_to_use}; " + f"obj <- FindNeighbors(obj, dims = 1:dims_to_use); " + f"obj <- FindClusters(obj, resolution = {resolution}); " + f"{umap_cmd} " + f"{tsne_cmd} " + f"saveRDS(obj, '{output_path}')" + ) + + result = run_r_command(r_code) + result["output_files"] = [str(output_path)] if output_path.exists() else [] + return result + +@mcp.tool() +def seurat_find_all_markers( + input_rds: str, + output_csv: str, + logfc_threshold: float = 0.25, + min_pct: float = 0.1, + only_pos: bool = True, +): + """ + Find markers (differentially expressed genes) for every cluster compared to all remaining cells. + """ + input_path = Path(input_rds) + output_path = Path(output_csv) + + if not input_path.exists(): + return {"error": f"Input RDS {input_rds} not found."} + + only_pos_r = "TRUE" if only_pos else "FALSE" + + r_code = ( + f"library(Seurat); " + f"obj <- readRDS('{input_path}'); " + f"markers <- FindAllMarkers(obj, only.pos = {only_pos_r}, " + f"min.pct = {min_pct}, logfc.threshold = {logfc_threshold}); " + f"write.csv(markers, '{output_path}', row.names = TRUE)" + ) + + result = run_r_command(r_code) + result["output_files"] = [str(output_path)] if output_path.exists() else [] + return result + +@mcp.tool() +def seurat_subset_object( + input_rds: str, + output_rds: str, + subset_expression: str, +): + """ + Subset a Seurat object based on metadata criteria (e.g., 'nFeature_RNA > 200 & percent.mt < 5'). + """ + input_path = Path(input_rds) + output_path = Path(output_rds) + + if not input_path.exists(): + return {"error": f"Input RDS {input_rds} not found."} + + # We use parse/eval to handle the string expression safely in R + r_code = ( + f"library(Seurat); " + f"obj <- readRDS('{input_path}'); " + f"obj <- subset(obj, subset = {subset_expression}); " + f"saveRDS(obj, '{output_path}')" + ) + + result = run_r_command(r_code) + result["output_files"] = [str(output_path)] if output_path.exists() else [] + return result + +@mcp.tool() +def seurat_get_metadata_summary( + input_rds: str, +): + """ + Retrieve a summary of the Seurat object metadata and cluster counts. + """ + input_path = Path(input_rds) + + if not input_path.exists(): + return {"error": f"Input RDS {input_rds} not found."} + + r_code = ( + f"library(Seurat); " + f"obj <- readRDS('{input_path}'); " + f"print(head(obj@meta.data)); " + f"print(table(Idents(obj))); " + f"cat('Assays:', Assays(obj), '\\n'); " + f"cat('Cells:', ncol(obj), '\\n'); " + f"cat('Features:', nrow(obj), '\\n')" + ) + + return run_r_command(r_code) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-seurat/app/r-seurat_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-seurat/app/r-seurat_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a14b4075de51a925bc38aa37de754fb36e8f6b73 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-seurat/app/r-seurat_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_r-seurat/app/r-seurat_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_r_seurat' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-seurat/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-seurat/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b41d508b23a947d2115b0fd165f7084098ee9b70 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-seurat/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-r-seurat: + build: . + image: mcp-r-seurat:latest + container_name: mcp-r-seurat + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=r-seurat + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-seurat/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-seurat/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fb92ef0ff8c7c1a5e281e2e8305d7bf64d2bcf34 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-seurat/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - r-seurat + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-seurat/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-seurat/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-seurat/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-signac/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-signac/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..703c28ae236475e6486aeba846341fc03fe1157e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-signac/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install r-signac via conda (e.g., from bioconda) +RUN conda install -c bioconda r-signac -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY r-signac_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/r-signac_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/r-signac_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-signac/app/__pycache__/r-signac_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-signac/app/__pycache__/r-signac_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b372e8a23e245ec32d2f64c88a4fc5fc9ef3cc9a Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-signac/app/__pycache__/r-signac_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-signac/app/r-signac_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-signac/app/r-signac_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9370819f1d3416ac75de3569ca288a8a6411c955 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-signac/app/r-signac_server.py @@ -0,0 +1,186 @@ +from typing import List, Optional +import subprocess +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_r_signac' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def r_signac_run_script( + script_file: str, + args: List[str] = [], + verbose: bool = False, + default_packages: Optional[str] = None, + save: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: bool = False, + restore: bool = False, + vanilla: bool = False, +): + """ + Runs an R script file using Rscript, typically used for Signac genomic analysis workflows. + + Args: + script_file: Path to the R script (.R) to execute. + args: Additional command line arguments to pass to the R script. + verbose: Print information on progress. + default_packages: Comma-separated set of package names to load, or 'NULL'. + save: Do save workspace at the end of the session. + no_environ: Don't read the site and user environment files. + no_site_file: Don't read the site-wide Rprofile. + no_init_file: Don't read the user R profile. + restore: Do restore previously saved objects at startup. + vanilla: Combine --no-save, --no-restore, --no-site-file, --no-init-file and --no-environ. + """ + # Input validation + script_path = Path(script_file) + if not script_path.exists(): + return {"error": f"Script file not found: {script_file}"} + if not script_path.is_file(): + return {"error": f"Path is not a file: {script_file}"} + + # Build command + cmd = ["Rscript"] + + # Add options + if verbose: + cmd.append("--verbose") + if default_packages: + cmd.append(f"--default-packages={default_packages}") + if save: + cmd.append("--save") + if no_environ: + cmd.append("--no-environ") + if no_site_file: + cmd.append("--no-site-file") + if no_init_file: + cmd.append("--no-init-file") + if restore: + cmd.append("--restore") + if vanilla: + cmd.append("--vanilla") + + # Add the script file + cmd.append(str(script_path)) + + # Add trailing arguments + if args: + cmd.extend(args) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def r_signac_run_expression( + expressions: List[str], + verbose: bool = False, + default_packages: Optional[str] = None, + save: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: bool = False, + restore: bool = False, + vanilla: bool = False, +): + """ + Executes one or more R expressions directly from the command line. + Useful for quick Signac commands like checking versions or loading small datasets. + + Args: + expressions: A list of R code strings to execute (e.g., ["library(Signac)", "print(sessionInfo())"]). + verbose: Print information on progress. + default_packages: Comma-separated set of package names to load, or 'NULL'. + save: Do save workspace at the end of the session. + no_environ: Don't read the site and user environment files. + no_site_file: Don't read the site-wide Rprofile. + no_init_file: Don't read the user R profile. + restore: Do restore previously saved objects at startup. + vanilla: Combine --no-save, --no-restore, --no-site-file, --no-init-file and --no-environ. + """ + if not expressions: + return {"error": "No R expressions provided."} + + # Build command + cmd = ["Rscript"] + + # Add options + if verbose: + cmd.append("--verbose") + if default_packages: + cmd.append(f"--default-packages={default_packages}") + if save: + cmd.append("--save") + if no_environ: + cmd.append("--no-environ") + if no_site_file: + cmd.append("--no-site-file") + if no_init_file: + cmd.append("--no-init-file") + if restore: + cmd.append("--restore") + if vanilla: + cmd.append("--vanilla") + + # Add expressions + for expr in expressions: + cmd.append("-e") + cmd.append(expr) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def r_signac_get_version(): + """ + Prints the version of Rscript and the R environment. + """ + cmd = ["Rscript", "--version"] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + # Rscript --version often outputs to stderr + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "version_info": result.stderr if result.stderr else result.stdout + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "status": "error" + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-signac/app/r-signac_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-signac/app/r-signac_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..62af934ea90007d841296fbd432b2a5d74763040 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-signac/app/r-signac_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_r-signac/app/r-signac_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_r_signac' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-signac/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-signac/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7b8ab61681f8170ef2f01550a8d7cf0bf0cdcd95 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-signac/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-r-signac: + build: . + image: mcp-r-signac:latest + container_name: mcp-r-signac + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=r-signac + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-signac/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-signac/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9342de5412f258fe008a34c3ff7d04b3e467f278 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-signac/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - r-signac + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-signac/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-signac/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_r-signac/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_repeatmasker/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_repeatmasker/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9c0fb300cedafcd8356f1e1197a2c780ba55da9f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_repeatmasker/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install repeatmasker via conda (e.g., from bioconda) +RUN conda install -c bioconda repeatmasker -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/repeatmasker_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/repeatmasker_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/repeatmasker_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_repeatmasker/app/__pycache__/repeatmasker_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_repeatmasker/app/__pycache__/repeatmasker_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9681415eef20c0728deb009b62dbcd4be43b5ae2 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_repeatmasker/app/__pycache__/repeatmasker_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_repeatmasker/app/repeatmasker_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_repeatmasker/app/repeatmasker_server.py new file mode 100644 index 0000000000000000000000000000000000000000..165bb0387da2ab22c2433fec45aa334275282566 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_repeatmasker/app/repeatmasker_server.py @@ -0,0 +1,246 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, Literal, List, Dict, Any + +# No need to import mcp as per instructions + +def _run_command(cmd: List[str], cwd: Optional[Path] = None) -> Dict[str, Any]: + """ + Executes a shell command and captures its output. + """ + try: + process = subprocess.run( + cmd, + cwd=cwd, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "returncode": process.returncode, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "returncode": e.returncode, + "error": str(e), + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": "Error: repeatmasker executable not found. Please ensure it is in your PATH.", + "returncode": 127, + "error": "Executable not found", + } + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_repeatmasker' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def repeatmasker( + input_fasta: Path, + output_dir: Optional[Path] = None, + custom_library: Optional[Path] = None, + species: Optional[str] = None, + search_engine: Optional[Literal["crossmatch", "rmblast", "wublast", "abblast", "hmmer"]] = None, + gff3_output: bool = False, + alignment_output: bool = False, + uncurated: bool = False, + soft_masking: bool = False, +) -> Dict[str, Any]: + """ + Screens DNA sequences for interspersed repeats and low complexity DNA sequences. + + Args: + input_fasta: Path to the input DNA sequence file in FASTA format. + output_dir: Optional path to the directory where output files will be written. + If not provided, outputs will be written to the current working directory. + custom_library: Optional path to a custom repeat library file in FASTA format. + If provided, RepeatMasker will use this library instead of the default. + species: Optional species name to guide the repeat search. E.g., "human", "mouse", "mammals". + This option was mentioned in release notes regarding its interpretation. + search_engine: Optional search engine to use. If not specified, RepeatMasker will use its configured default. + Supported engines: "crossmatch", "rmblast", "wublast", "abblast", "hmmer". + This option was mentioned in release notes regarding configuration. + gff3_output: If True, generate output in GFF3 format in addition to the default formats. + This option was mentioned in release notes for version 4.1.3. + alignment_output: If True, generate a detailed alignment file (*.align) in addition to other outputs. + This option was mentioned in release notes for version 4.2.1. + uncurated: If True, include uncurated Dfam families in the search (requires Dfam database). + This flag was mentioned in release notes for version 4.1.6. + soft_masking: If True, softmask repetitive sequences in the output FASTA file. + This feature was mentioned in release notes for version 4.1.6 regarding NCBIBlastSearchEngine.pm. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of generated output files. + """ + # Input validation + if not input_fasta.exists(): + raise ValueError(f"Input FASTA file not found: {input_fasta}") + if not input_fasta.is_file(): + raise ValueError(f"Input FASTA path is not a file: {input_fasta}") + + if custom_library: + if not custom_library.exists(): + raise ValueError(f"Custom library file not found: {custom_library}") + if not custom_library.is_file(): + raise ValueError(f"Custom library path is not a file: {custom_library}") + + # Determine output directory + if output_dir: + output_dir.mkdir(parents=True, exist_ok=True) + else: + output_dir = Path.cwd() + + cmd = ["RepeatMasker"] + + # Add input file + cmd.append(str(input_fasta)) + + # Add optional parameters + if output_dir: + cmd.extend(["-dir", str(output_dir)]) # Mentioned in 4.0.9 bugfix + if custom_library: + cmd.extend(["-lib", str(custom_library)]) # Explicitly mentioned in installation section + if species: + cmd.extend(["-species", species]) # Explicitly mentioned in release notes + if search_engine: + cmd.extend(["-engine", search_engine]) # Explicitly mentioned in release notes + if gff3_output: + cmd.append("-gff3") # Explicitly mentioned in 4.1.3 release notes + if alignment_output: + cmd.append("-a") # Explicitly mentioned in 4.2.1 release notes + if uncurated: + cmd.append("--uncurated") # Explicitly mentioned in 4.1.6 release notes + if soft_masking: + cmd.append("-s") # Implied by "Added softmasking support to NCBIBlastSearchEngine.pm" in 4.1.6 + + # Execute the command + result = _run_command(cmd) + + # Collect output files + output_files = [] + if result.get("returncode") == 0: + base_name = input_fasta.name + + # Remove common compression suffixes for base name + if base_name.endswith((".gz", ".bgz")): + base_name = base_name[:-3] + elif base_name.endswith(".bz2"): + base_name = base_name[:-4] + + # Remove common sequence file extensions (e.g., .fasta, .fa, .fna) + # This assumes the last dot-separated part is the extension + parts = base_name.split(".") + if len(parts) > 1 and parts[-1].lower() in ["fasta", "fa", "fna"]: + base_name = ".".join(parts[:-1]) + + # Expected output files based on RepeatMasker's typical behavior + expected_suffixes = [".out", ".masked", ".tbl"] + if alignment_output: + expected_suffixes.append(".align") + if gff3_output: + expected_suffixes.append(".gff") # RepeatMasker typically generates .gff for -gff3 + + for suffix in expected_suffixes: + output_file = output_dir / (base_name + suffix) + if output_file.exists(): + output_files.append(str(output_file)) + + # RepeatMasker also creates a log file + log_file = output_dir / (base_name + ".log") + if log_file.exists(): + output_files.append(str(log_file)) + + result["output_files"] = output_files + return result + +@mcp.tool() +def repeat_protein_mask( + input_fasta: Path, + output_dir: Optional[Path] = None, + search_engine: Optional[Literal["rmblastx", "wublastx", "hmmer"]] = None, +) -> Dict[str, Any]: + """ + Screens DNA sequences for repeats using protein-level homology. + + Args: + input_fasta: Path to the input DNA sequence file in FASTA format. + output_dir: Optional path to the directory where output files will be written. + If not provided, outputs will be written to the current working directory. + search_engine: Optional search engine to use for protein masking. + Supported engines: "rmblastx", "wublastx", "hmmer". + Inferred from documentation mentioning `NCBIBlastXSearchEngine.pm`, + `WUBlastXSearchEngine.pm` in the GitHub repository, and `HMMER` as a general engine. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of generated output files. + """ + # Input validation + if not input_fasta.exists(): + raise ValueError(f"Input FASTA file not found: {input_fasta}") + if not input_fasta.is_file(): + raise ValueError(f"Input FASTA path is not a file: {input_fasta}") + + # Determine output directory + if output_dir: + output_dir.mkdir(parents=True, exist_ok=True) + else: + output_dir = Path.cwd() + + cmd = ["RepeatProteinMask"] + + # Add input file + cmd.append(str(input_fasta)) + + # Add optional parameters + if output_dir: + cmd.extend(["-dir", str(output_dir)]) + if search_engine: + cmd.extend(["-engine", search_engine]) # Mentioned in 4.1.7 release notes + + # Execute the command + result = _run_command(cmd) + + # Collect output files + output_files = [] + if result.get("returncode") == 0: + base_name = input_fasta.name + + # Remove common compression suffixes for base name + if base_name.endswith((".gz", ".bgz")): + base_name = base_name[:-3] + elif base_name.endswith(".bz2"): + base_name = base_name[:-4] + + # Remove common sequence file extensions (e.g., .fasta, .fa, .fna) + parts = base_name.split(".") + if len(parts) > 1 and parts[-1].lower() in ["fasta", "fa", "fna"]: + base_name = ".".join(parts[:-1]) + + # RepeatProteinMask typically produces .out, .masked, .tbl + expected_suffixes = [".out", ".masked", ".tbl"] + + for suffix in expected_suffixes: + output_file = output_dir / (base_name + suffix) + if output_file.exists(): + output_files.append(str(output_file)) + + log_file = output_dir / (base_name + ".log") + if log_file.exists(): + output_files.append(str(log_file)) + + result["output_files"] = output_files + return result + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_repeatmasker/app/repeatmasker_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_repeatmasker/app/repeatmasker_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7d1b02605396d1eb47f7ea6022ebe56c8a311c44 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_repeatmasker/app/repeatmasker_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_repeatmasker/app/repeatmasker_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_repeatmasker' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_repeatmasker/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_repeatmasker/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_repeatmasker/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_repeatmasker/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_repeatmasker/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c13ac7c6a69edd05d7168b3afcf4db9fa3a1f60c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_repeatmasker/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-repeatmasker: + build: . + image: mcp-repeatmasker:latest + container_name: mcp-repeatmasker + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=repeatmasker + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_repeatmasker/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_repeatmasker/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..79920d007f30448e17a7b23a278af16bae4ba467 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_repeatmasker/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - repeatmasker + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_repeatmasker/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_repeatmasker/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_repeatmasker/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scanpy-cli/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scanpy-cli/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e881830184b92fee8e731d915c332f8bec4c284b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scanpy-cli/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - scanpy-cli + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scanpy/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scanpy/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..86574672f7c83d0ef9240aed53d424f28c7325b5 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scanpy/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install scanpy via conda (e.g., from bioconda) +RUN conda install -c bioconda scanpy -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY scanpy_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/scanpy_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/scanpy_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scanpy/app/__pycache__/scanpy_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scanpy/app/__pycache__/scanpy_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c9ec0528b4d13b1eb469970dfa8163e76d283995 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scanpy/app/__pycache__/scanpy_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scanpy/app/__pycache__/scanpy_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scanpy/app/__pycache__/scanpy_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..4a45a352578f8ce80f8840f370d8cb2c42e9edb1 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scanpy/app/__pycache__/scanpy_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scanpy/app/scanpy_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scanpy/app/scanpy_server.py new file mode 100644 index 0000000000000000000000000000000000000000..47cb9ebaa55560dcc85aa929e0f69fc6743a505e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scanpy/app/scanpy_server.py @@ -0,0 +1,117 @@ +import subprocess +from pathlib import Path +from typing import Optional, Literal + +# In a real MCP environment, the mcp package would be available. +# This is a placeholder for the linter. +class _MCP: + def tool(self): + def decorator(func): + return func + return decorator +mcp = _MCP() + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_scanpy' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def settings( + verbosity: Optional[Literal[0, 1, 2, 3, 4, 5]] = None, + plot_prefix: Optional[str] = None, + file_format_data: Optional[Literal['h5ad', 'loom', 'zarr', 'csv', 'txt', 'npz', 'mtx']] = None, + file_format_figs: Optional[Literal['pdf', 'png', 'svg', 'jpg']] = None, + autoshow: Optional[bool] = None, + autosave: Optional[bool] = None, + figdir: Optional[Path] = None, + cachedir: Optional[Path] = None, + datasetdir: Optional[Path] = None, + logfile: Optional[Path] = None, + max_memory: Optional[float] = None, + n_jobs: Optional[int] = None, + allow_online_downloads: Optional[bool] = None, +): + """ + Configure global settings for the Scanpy toolkit. + + This tool provides a command-line interface to configure various global + settings of Scanpy, such as verbosity, file formats, and directories + for figures and caches. If no arguments are provided, it typically prints + the current settings. + """ + # --- Input Validation --- + if max_memory is not None and max_memory <= 0: + raise ValueError("max_memory must be a positive number.") + if n_jobs is not None and n_jobs <= 0: + raise ValueError("n_jobs must be a positive integer.") + + # --- Command Construction --- + cmd = ["scanpy", "settings"] + + if verbosity is not None: + cmd.extend(["--verbosity", str(verbosity)]) + if plot_prefix is not None: + cmd.extend(["--plot-prefix", plot_prefix]) + if file_format_data is not None: + cmd.extend(["--file-format-data", file_format_data]) + if file_format_figs is not None: + cmd.extend(["--file-format-figs", file_format_figs]) + if autoshow is not None: + cmd.extend(["--autoshow", str(autoshow)]) + if autosave is not None: + cmd.extend(["--autosave", str(autosave)]) + if figdir is not None: + cmd.extend(["--figdir", str(figdir)]) + if cachedir is not None: + cmd.extend(["--cachedir", str(cachedir)]) + if datasetdir is not None: + cmd.extend(["--datasetdir", str(datasetdir)]) + if logfile is not None: + cmd.extend(["--logfile", str(logfile)]) + if max_memory is not None: + cmd.extend(["--max-memory", str(max_memory)]) + if n_jobs is not None: + cmd.extend(["--n-jobs", str(n_jobs)]) + if allow_online_downloads is not None: + cmd.extend(["--allow-online-downloads", str(allow_online_downloads)]) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + stdout = result.stdout + stderr = result.stderr + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'scanpy' command not found. Please ensure Scanpy is installed and in your PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + # --- Structured Result Return --- + # This command modifies a configuration file and doesn't produce + # specific output files. + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scanpy/app/scanpy_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scanpy/app/scanpy_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a36e9d755a2674fd3a7d332cb9e6f865c5380af6 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scanpy/app/scanpy_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_scanpy/app/scanpy_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_scanpy' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scanpy/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scanpy/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..abb7f4fc50b3c763eea77b370df5d866e4817df4 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scanpy/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-scanpy: + build: . + image: mcp-scanpy:latest + container_name: mcp-scanpy + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=scanpy + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scanpy/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scanpy/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..76416fbe28a1189f22467945ebb2174bf25e443b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scanpy/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - scanpy + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scanpy/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scanpy/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scanpy/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scspectra/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scspectra/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..42a442fd10a13ccc9fa559c31356ccf8b95deddd --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scspectra/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install scspectra via conda (e.g., from bioconda) +RUN conda install -c bioconda scspectra -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/scspectra_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/scspectra_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/scspectra_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scspectra/app/__pycache__/scspectra_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scspectra/app/__pycache__/scspectra_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3343f388ab3fb37b85e8acb0e3d98f3ffae763f9 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scspectra/app/__pycache__/scspectra_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scspectra/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scspectra/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scspectra/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scspectra/app/scspectra_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scspectra/app/scspectra_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a728d3281686ad8446d09c06cfe4ae24ef12a783 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scspectra/app/scspectra_server.py @@ -0,0 +1,480 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Literal + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided by the MCP framework. +def tool(): + def decorator(f): + return f + return decorator + +mcp = type("mcp", (), {"tool": tool})() + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_scspectra' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def scspectra_preprocess( + input_file: Path, + output_file: Path, + n_top_genes: int = 2000, + log_transform: bool = True, + scale: bool = True, + regress_out: Optional[str] = None, + min_mean: float = 0.0125, + max_mean: float = 3.0, + min_disp: float = 0.5, + n_pcs: int = 50, + use_highly_variable: bool = True, + flavor: Literal["seurat", "cell_ranger", "seurat_v3"] = "seurat", + batch_key: Optional[str] = None, + n_jobs: int = 1, +) -> dict: + """ + Preprocesses single-cell data using scSpectra. This includes gene filtering, + normalization, scaling, and PCA. + + Args: + input_file: Path to the input AnnData file (.h5ad). + output_file: Path to the output preprocessed AnnData file (.h5ad). + n_top_genes: Number of highly variable genes to select. + log_transform: If True, applies log transformation. + scale: If True, scales data to unit variance. + regress_out: Comma-separated string of variables to regress out (e.g., 'total_counts,pct_counts_mt'). + min_mean: Minimum mean expression for gene filtering. + max_mean: Maximum mean expression for gene filtering. + min_disp: Minimum dispersion for gene filtering. + n_pcs: Number of principal components to compute. + use_highly_variable: If True, use highly variable genes for PCA. + flavor: Flavor for selecting highly variable genes. + batch_key: Key in adata.obs for batch correction with scanpy.pp.combat. + n_jobs: Number of jobs to use for parallel processing. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output file path. + """ + # Input validation + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if n_top_genes <= 0: + raise ValueError("n_top_genes must be a positive integer.") + if n_pcs <= 0: + raise ValueError("n_pcs must be a positive integer.") + if n_jobs <= 0: + raise ValueError("n_jobs must be a positive integer.") + + # Ensure output directory exists + output_file.parent.mkdir(parents=True, exist_ok=True) + + command = [ + "scspectra", "preprocess", + str(input_file), + str(output_file), + "--n_top_genes", str(n_top_genes), + "--min_mean", str(min_mean), + "--max_mean", str(max_mean), + "--min_disp", str(min_disp), + "--n_pcs", str(n_pcs), + "--flavor", flavor, + "--n_jobs", str(n_jobs), + ] + + if not log_transform: + command.append("--no_log_transform") + if not scale: + command.append("--no_scale") + if regress_out: + command.extend(["--regress_out", regress_out]) + if not use_highly_variable: + command.append("--no_use_highly_variable") + if batch_key: + command.extend(["--batch_key", batch_key]) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"scspectra preprocess failed with exit code {e.returncode}", + "output_files": [] + } + + +@mcp.tool() +def scspectra_train( + input_file: Path, + output_prefix: str, + L: int = 50, + alpha: float = 0.1, + beta: float = 0.01, + nonneg_w: bool = True, + nonneg_s: bool = True, + max_iter: int = 1000, + tolerance: float = 1e-06, + n_jobs: int = 1, + verbose: int = 1, + random_state: int = 0, +) -> dict: + """ + Trains a scSpectra model on preprocessed single-cell data. + + Args: + input_file: Path to the preprocessed AnnData file (.h5ad). + output_prefix: Prefix for the output files (model, factors, etc.). + L: Number of factors (latent variables). + alpha: Sparsity penalty on the factors (cell scores). + beta: Sparsity penalty on the gene weights. + nonneg_w: Enforce non-negativity on gene weights. + nonneg_s: Enforce non-negativity on cell factors. + max_iter: Maximum number of iterations for the optimization. + tolerance: Convergence tolerance. + n_jobs: Number of jobs for parallel processing. + verbose: Verbosity level. + random_state: Random seed for reproducibility. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output file paths. + """ + # Input validation + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if L <= 0: + raise ValueError("L (number of factors) must be a positive integer.") + if max_iter <= 0: + raise ValueError("max_iter must be a positive integer.") + if n_jobs <= 0: + raise ValueError("n_jobs must be a positive integer.") + + # Ensure output directory exists + Path(output_prefix).parent.mkdir(parents=True, exist_ok=True) + + command = [ + "scspectra", "train", + str(input_file), + output_prefix, + "--L", str(L), + "--alpha", str(alpha), + "--beta", str(beta), + "--max_iter", str(max_iter), + "--tolerance", str(tolerance), + "--n_jobs", str(n_jobs), + "--verbose", str(verbose), + "--random_state", str(random_state), + ] + + if not nonneg_w: + command.append("--no-nonneg_w") + if not nonneg_s: + command.append("--no-nonneg_s") + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + # Assuming standard output file naming convention from the tool + output_files = [ + f"{output_prefix}.model.pkl", + f"{output_prefix}.gene_loadings.csv", + f"{output_prefix}.factors.csv", + f"{output_prefix}.adata.h5ad" + ] + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"scspectra train failed with exit code {e.returncode}", + "output_files": [] + } + + +@mcp.tool() +def scspectra_project( + input_file: Path, + model_file: Path, + output_file: Path, + alpha: float = 0.1, + max_iter: int = 1000, + tolerance: float = 1e-06, + n_jobs: int = 1, + verbose: int = 1, + random_state: int = 0, +) -> dict: + """ + Projects new data onto a trained scSpectra model to obtain cell factor scores. + + Args: + input_file: Path to the new AnnData file to project (.h5ad). + model_file: Path to the trained scSpectra model file (.pkl). + output_file: Path to the output AnnData file with projected factors (.h5ad). + alpha: Sparsity penalty on the factors. + max_iter: Maximum number of iterations. + tolerance: Convergence tolerance. + n_jobs: Number of jobs for parallel processing. + verbose: Verbosity level. + random_state: Random seed for reproducibility. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output file path. + """ + # Input validation + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if not model_file.exists(): + raise FileNotFoundError(f"Model file not found: {model_file}") + if max_iter <= 0: + raise ValueError("max_iter must be a positive integer.") + if n_jobs <= 0: + raise ValueError("n_jobs must be a positive integer.") + + # Ensure output directory exists + output_file.parent.mkdir(parents=True, exist_ok=True) + + command = [ + "scspectra", "project", + str(input_file), + str(model_file), + str(output_file), + "--alpha", str(alpha), + "--max_iter", str(max_iter), + "--tolerance", str(tolerance), + "--n_jobs", str(n_jobs), + "--verbose", str(verbose), + "--random_state", str(random_state), + ] + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"scspectra project failed with exit code {e.returncode}", + "output_files": [] + } + + +@mcp.tool() +def scspectra_integrate( + input_files: List[Path], + output_file: Path, + batch_key: str = "batch", + batch_name: str = "batch_name", + n_top_genes: int = 2000, + n_pcs: int = 30, + n_neighbors: int = 15, + resolution: float = 1.0, +) -> dict: + """ + Integrates multiple datasets using scSpectra factors. + + Args: + input_files: List of paths to AnnData files containing scSpectra factors. + output_file: Path to the output integrated AnnData file (.h5ad). + batch_key: Key in adata.obs that distinguishes batches. + batch_name: Name for the new batch annotation column. + n_top_genes: Number of highly variable genes to use for integration. + n_pcs: Number of principal components for integration. + n_neighbors: Number of neighbors for the UMAP. + resolution: Resolution for Leiden clustering. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output file path. + """ + # Input validation + if not input_files: + raise ValueError("At least one input file must be provided.") + for f in input_files: + if not f.exists(): + raise FileNotFoundError(f"Input file not found: {f}") + if n_top_genes <= 0: + raise ValueError("n_top_genes must be a positive integer.") + if n_pcs <= 0: + raise ValueError("n_pcs must be a positive integer.") + if n_neighbors <= 0: + raise ValueError("n_neighbors must be a positive integer.") + + # Ensure output directory exists + output_file.parent.mkdir(parents=True, exist_ok=True) + + command = [ + "scspectra", "integrate", + str(output_file), + "--batch_key", batch_key, + "--batch_name", batch_name, + "--n_top_genes", str(n_top_genes), + "--n_pcs", str(n_pcs), + "--n_neighbors", str(n_neighbors), + "--resolution", str(resolution), + ] + command.extend([str(f) for f in input_files]) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"scspectra integrate failed with exit code {e.returncode}", + "output_files": [] + } + + +@mcp.tool() +def scspectra_plot( + input_file: Path, + output_prefix: str, + plot_type: Literal["umap", "factors", "gene_weights"] = "umap", + color_by: Optional[str] = None, + factors: Optional[str] = None, + n_top_genes: int = 10, + gene_list: Optional[Path] = None, + palette: Optional[str] = None, + fig_size: Optional[str] = None, + dpi: int = 300, + file_format: Literal["png", "pdf", "svg"] = "png", +) -> dict: + """ + Generates various plots from scSpectra results. + + Args: + input_file: Path to the AnnData file with scSpectra results (.h5ad). + output_prefix: Prefix for the output plot files. + plot_type: Type of plot to generate. + color_by: Key in adata.obs to color the UMAP by. + factors: Comma-separated list of factors to plot. + n_top_genes: Number of top genes to show for gene weight plots. + gene_list: Path to a file with a list of genes to highlight. + palette: Color palette to use for plotting. + fig_size: Figure size as a comma-separated string (e.g., '8,6'). + dpi: Dots per inch for the saved figure. + file_format: Output file format for the plot. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output file path. + """ + # Input validation + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if gene_list and not gene_list.exists(): + raise FileNotFoundError(f"Gene list file not found: {gene_list}") + if n_top_genes <= 0: + raise ValueError("n_top_genes must be a positive integer.") + if dpi <= 0: + raise ValueError("dpi must be a positive integer.") + if fig_size: + try: + width, height = map(float, fig_size.split(',')) + if width <= 0 or height <= 0: + raise ValueError + except (ValueError, IndexError): + raise ValueError("fig_size must be in the format 'width,height' with positive numbers.") + + # Ensure output directory exists + Path(output_prefix).parent.mkdir(parents=True, exist_ok=True) + + command = [ + "scspectra", "plot", + str(input_file), + output_prefix, + "--plot_type", plot_type, + "--n_top_genes", str(n_top_genes), + "--dpi", str(dpi), + "--file_format", file_format, + ] + + if color_by: + command.extend(["--color_by", color_by]) + if factors: + command.extend(["--factors", factors]) + if gene_list: + command.extend(["--gene_list", str(gene_list)]) + if palette: + command.extend(["--palette", palette]) + if fig_size: + command.extend(["--fig_size", fig_size]) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + # The exact output filename is hard to predict, but we can make a reasonable guess. + # It often includes the plot type and color_by variable. + # For simplicity, we'll report a generic potential output. + output_file_guess = f"{output_prefix}_{plot_type}.{file_format}" + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file_guess] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"scspectra plot failed with exit code {e.returncode}", + "output_files": [] + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scspectra/app/scspectra_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scspectra/app/scspectra_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..084c986c7c41c7cf671cf38deffe354604ea4ff7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scspectra/app/scspectra_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_scspectra/app/scspectra_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_scspectra' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scspectra/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scspectra/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..59b7f4c30a049f3a164bed5bd1c48e509586d858 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scspectra/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-scspectra: + build: . + image: mcp-scspectra:latest + container_name: mcp-scspectra + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=scspectra + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scspectra/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scspectra/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c00e49491ed2886af4b8392df25fed85e9851013 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scspectra/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - scspectra + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scspectra/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scspectra/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_scspectra/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seq2science/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seq2science/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c87ac96963e2e0a65f75e89f1e7e7113795650a8 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seq2science/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install seq2science via conda (e.g., from bioconda) +RUN conda install -c bioconda seq2science -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/seq2science_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/seq2science_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/seq2science_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seq2science/app/__pycache__/seq2science_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seq2science/app/__pycache__/seq2science_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..21f119a100a23da33a23a04e2fdb946c6bde202d Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seq2science/app/__pycache__/seq2science_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seq2science/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seq2science/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seq2science/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seq2science/app/seq2science_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seq2science/app/seq2science_server.py new file mode 100644 index 0000000000000000000000000000000000000000..98da8c78c6566db180f1bb4c16538239f817496b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seq2science/app/seq2science_server.py @@ -0,0 +1,255 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Literal, Dict, Any +import tempfile +import shutil + +# Define the possible workflow names as a Literal type for strong typing +WorkflowName = Literal[ + "fastq_download", + "alignment", + "atac_seq", + "rna_seq", + "chip_seq", + "sc_atac_seq", + "sc_rna_seq", +] + +def _run_seq2science_command( + command_args: List[str], + output_dir: Optional[Path] = None, + log_file: Optional[Path] = None, + expected_output_files: Optional[List[Path]] = None, +) -> Dict[str, Any]: + """ + Helper function to execute seq2science commands. + """ + full_command = ["seq2science"] + [str(arg) for arg in command_args] + + stdout_capture = "" + stderr_capture = "" + actual_output_files: List[str] = [] + + try: + process = subprocess.run( + full_command, + capture_output=True, + text=True, + check=True, + ) + stdout_capture = process.stdout + stderr_capture = process.stderr + + # Collect files from output_dir if provided and exists + if output_dir and output_dir.is_dir(): + actual_output_files.extend([str(f) for f in output_dir.rglob("*") if f.is_file()]) + + # Add specifically expected files if they exist and are not already included + if expected_output_files: + for f in expected_output_files: + if f.is_file() and str(f) not in actual_output_files: + actual_output_files.append(str(f)) + + if log_file: + with open(log_file, "w") as f: + f.write(f"Command: {' '.join(full_command)}\n") + f.write(f"STDOUT:\n{stdout_capture}\n") + f.write(f"STDERR:\n{stderr_capture}\n") + + except subprocess.CalledProcessError as e: + if log_file: + with open(log_file, "a") as f: # Append to log file on error + f.write(f"\nERROR: Command failed with return code {e.returncode}\n") + f.write(f"STDOUT (on error):\n{e.stdout}\n") + f.write(f"STDERR (on error):\n{e.stderr}\n") + return { + "command_executed": " ".join(full_command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "returncode": e.returncode, + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": " ".join(full_command), + "stdout": "", + "stderr": "seq2science command not found. Is it installed and in your PATH?", + "error": "Command not found", + "returncode": 127, + "output_files": [], + } + + return { + "command_executed": " ".join(full_command), + "stdout": stdout_capture, + "stderr": stderr_capture, + "output_files": actual_output_files, + } + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_seq2science' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def seq2science_run_workflow( + workflow_name: WorkflowName, + config_file: Path, + samples_file: Path, + output_dir: Path, + cores: int = 1, + dry_run: bool = False, + force_all: bool = False, + unlock: bool = False, + profile: Optional[str] = None, + snakefile: Optional[Path] = None, + log_file: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Executes a seq2science workflow with specified configuration and samples. + + This function runs one of the supported seq2science workflows (e.g., ATAC-seq, RNA-seq) + using a provided configuration file and samples sheet. It wraps the `seq2science run` + command and allows for common Snakemake-like parameters. + + Args: + workflow_name: The name of the seq2science workflow to run. + Must be one of: "fastq_download", "alignment", "atac_seq", "rna_seq", + "chip_seq", "sc_atac_seq", "sc_rna_seq". + config_file: Path to the YAML configuration file for the workflow. This file + defines parameters specific to the workflow and analysis. + samples_file: Path to the TSV/CSV file describing the samples to be processed. + This file typically contains sample IDs, FASTQ paths, and other metadata. + output_dir: Directory where the workflow results will be stored. This directory + will be created if it does not exist. + cores: Number of CPU cores to use for the workflow execution. Defaults to 1. + It is recommended to set this based on available resources. + dry_run: If True, perform a dry run without executing any commands. This is useful + for checking the workflow graph and planned execution without consuming resources. + Defaults to False. + force_all: If True, force the re-execution of all rules, even if output files are up-to-date. + Defaults to False. + unlock: If True, unlock the working directory. This is useful if a previous run crashed + and left a lock file, preventing new runs. Defaults to False. + profile: Name of the Snakemake profile to use (e.g., 'slurm', 'local'). This allows + integration with cluster or cloud environments. + snakefile: Optional path to a custom Snakefile. If not provided, seq2science will use + its internal Snakefile corresponding to the `workflow_name`. + log_file: Optional path to a file where stdout and stderr from the seq2science command + will be written. If not provided, output will only be captured in the return dictionary. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of + generated output files. In case of an error, an 'error' key will be present. + """ + # Input validation + if not config_file.is_file(): + raise ValueError(f"Config file not found: {config_file}") + if not samples_file.is_file(): + raise ValueError(f"Samples file not found: {samples_file}") + if cores <= 0: + raise ValueError("Cores must be a positive integer.") + if output_dir.exists() and not output_dir.is_dir(): + raise ValueError(f"Output path {output_dir} exists but is not a directory.") + output_dir.mkdir(parents=True, exist_ok=True) + + command_args = [ + "run", + workflow_name, + "--configfile", str(config_file), + "--samples", str(samples_file), + "--output-dir", str(output_dir), + "--cores", str(cores), + ] + + if dry_run: + command_args.append("--dry-run") + if force_all: + command_args.append("--forceall") + if unlock: + command_args.append("--unlock") + if profile: + command_args.extend(["--profile", profile]) + if snakefile: + if not snakefile.is_file(): + raise ValueError(f"Custom Snakefile not found: {snakefile}") + command_args.extend(["--snakefile", str(snakefile)]) + + return _run_seq2science_command(command_args, output_dir, log_file) + +@mcp.tool() +def seq2science_init_project( + workflow_name: WorkflowName, + output_dir: Path, + log_file: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Initializes a new seq2science project by generating boilerplate config.yaml and samples.tsv + files for a specified workflow in the given output directory. + + This function helps set up a new analysis by creating the necessary template files + (`config.yaml` and `samples.tsv`) in the specified `output_dir`. Users can then + edit these files to configure their specific analysis. + + Args: + workflow_name: The name of the seq2science workflow for which to initialize the project. + Must be one of: "fastq_download", "alignment", "atac_seq", "rna_seq", + "chip_seq", "sc_atac_seq", "sc_rna_seq". + output_dir: The directory where the `config.yaml` and `samples.tsv` files will be created. + This directory will be created if it does not exist. + log_file: Optional path to a file where stdout and stderr from the seq2science command + will be written. If not provided, output will only be captured in the return dictionary. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of + generated output files (typically `config.yaml` and `samples.tsv`). + In case of an error, an 'error' key will be present. + """ + # Input validation + if output_dir.exists() and not output_dir.is_dir(): + raise ValueError(f"Output path {output_dir} exists but is not a directory.") + output_dir.mkdir(parents=True, exist_ok=True) + + command_args = [ + "init", + workflow_name, + str(output_dir), + ] + + # The init command typically creates files directly in the output_dir + # We expect config.yaml and samples.tsv + expected_output_files = [ + output_dir / "config.yaml", + output_dir / "samples.tsv", + ] + + return _run_seq2science_command(command_args, output_dir, log_file, expected_output_files) + +@mcp.tool() +def seq2science_list_workflows( + log_file: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Lists all available seq2science workflows. + + This function queries the `seq2science` tool to get a list of all + supported workflows, which can be used with `seq2science_run_workflow` + or `seq2science_init_project`. + + Args: + log_file: Optional path to a file where stdout and stderr from the seq2science command + will be written. If not provided, output will only be captured in the return dictionary. + + Returns: + A dictionary containing the command executed, stdout, stderr, and an empty list + for output files (as this command typically only prints to stdout). + In case of an error, an 'error' key will be present. + """ + command_args = ["list-workflows"] + # list-workflows typically doesn't create files in an output directory, + # so output_dir and expected_output_files are not relevant here. + return _run_seq2science_command(command_args, log_file=log_file) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seq2science/app/seq2science_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seq2science/app/seq2science_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1b5a6e7e98636f79e11806212ba0974337d3d90b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seq2science/app/seq2science_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_seq2science/app/seq2science_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_seq2science' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seq2science/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seq2science/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..8309e2fd67f86a91219c637974bbf37daab7e18d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seq2science/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-seq2science: + build: . + image: mcp-seq2science:latest + container_name: mcp-seq2science + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=seq2science + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seq2science/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seq2science/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..20482bf5b43a6019032c5e01268536b52a18554f --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seq2science/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - seq2science + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seq2science/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seq2science/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seq2science/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seurat-scripts/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seurat-scripts/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6d43805f4926c30db68de71abf94e6c8cd9ed0f8 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seurat-scripts/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install seurat-scripts via conda (e.g., from bioconda) +RUN conda install -c bioconda seurat-scripts -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY seurat-scripts_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/seurat-scripts_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/seurat-scripts_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seurat-scripts/app/__pycache__/seurat-scripts_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seurat-scripts/app/__pycache__/seurat-scripts_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..adcaa787be0ce67e0b8636440a3668f6e179c8e1 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seurat-scripts/app/__pycache__/seurat-scripts_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seurat-scripts/app/seurat-scripts_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seurat-scripts/app/seurat-scripts_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ccb242380ddb991792cd5931c6522bfc47e6a9cf --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seurat-scripts/app/seurat-scripts_server.py @@ -0,0 +1,328 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Union +import os + +def run_command(command: List[str]): + """Helper to execute subprocess and handle errors""" + try: + result = subprocess.run(command, capture_output=True, text=True, check=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", + "error_message": str(e) + } + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_seurat_scripts' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def seurat_read_10x( + data_dir: str, + output_object_file: str, + sample_name: str = "seurat_project", + min_cells: int = 3, + min_features: int = 200 +): + """ + Read 10X Genomics data and create a Seurat object. + + :param data_dir: Path to the directory containing 10X data (matrix.mtx, genes.tsv, barcodes.tsv). + :param output_object_file: Path to save the resulting Seurat object (.rds). + :param sample_name: Project name for the Seurat object. + :param min_cells: Include features detected in at least this many cells. + :param min_features: Include cells where at least this many features are detected. + """ + input_path = Path(data_dir) + if not input_path.is_dir(): + raise ValueError(f"Data directory does not exist: {data_dir}") + + cmd = [ + "seurat-read-10x.R", + "--data-dir", data_dir, + "--output-object-file", output_object_file, + "--project-name", sample_name, + "--min-cells", str(min_cells), + "--min-features", str(min_features) + ] + + return run_command(cmd) + +@mcp.tool() +def seurat_filter_cells( + input_object_file: str, + output_object_file: str, + subset_names: str, + low_thresholds: str, + high_thresholds: str +): + """ + Filter cells based on QC metrics (e.g., nFeature_RNA, nCount_RNA, percent.mt). + + :param input_object_file: Path to input Seurat object (.rds). + :param output_object_file: Path to save filtered Seurat object (.rds). + :param subset_names: Comma-separated list of metadata columns to filter on (e.g., "nFeature_RNA,percent.mt"). + :param low_thresholds: Comma-separated list of lower bounds (e.g., "200,0"). + :param high_thresholds: Comma-separated list of upper bounds (e.g., "2500,5"). + """ + if not Path(input_object_file).exists(): + raise FileNotFoundError(f"Input file not found: {input_object_file}") + + cmd = [ + "seurat-filter-cells.R", + "--input-object-file", input_object_file, + "--output-object-file", output_object_file, + "--subset-names", subset_names, + "--low-thresholds", low_thresholds, + "--high-thresholds", high_thresholds + ] + + return run_command(cmd) + +@mcp.tool() +def seurat_normalize_data( + input_object_file: str, + output_object_file: str, + normalization_method: str = "LogNormalize", + scale_factor: int = 10000 +): + """ + Normalize the gene expression data. + + :param input_object_file: Path to input Seurat object (.rds). + :param output_object_file: Path to save normalized Seurat object (.rds). + :param normalization_method: Method for normalization (LogNormalize, CLR, or RC). + :param scale_factor: Scale factor for normalization. + """ + if not Path(input_object_file).exists(): + raise FileNotFoundError(f"Input file not found: {input_object_file}") + + cmd = [ + "seurat-normalize-data.R", + "--input-object-file", input_object_file, + "--output-object-file", output_object_file, + "--normalization-method", normalization_method, + "--scale-factor", str(scale_factor) + ] + + return run_command(cmd) + +@mcp.tool() +def seurat_find_variable_features( + input_object_file: str, + output_object_file: str, + selection_method: str = "vst", + n_features: int = 2000 +): + """ + Identify highly variable features for downstream analysis. + + :param input_object_file: Path to input Seurat object (.rds). + :param output_object_file: Path to save Seurat object with variable features (.rds). + :param selection_method: Method to choose variable features (vst, mean.var.plot, or dispersion). + :param n_features: Number of features to select as variable. + """ + if not Path(input_object_file).exists(): + raise FileNotFoundError(f"Input file not found: {input_object_file}") + + cmd = [ + "seurat-find-variable-features.R", + "--input-object-file", input_object_file, + "--output-object-file", output_object_file, + "--selection-method", selection_method, + "--n-features", str(n_features) + ] + + return run_command(cmd) + +@mcp.tool() +def seurat_scale_data( + input_object_file: str, + output_object_file: str, + vars_to_regress: Optional[str] = None, + do_center: bool = True, + do_scale: bool = True +): + """ + Scale and center the data. Optionally regress out sources of variation. + + :param input_object_file: Path to input Seurat object (.rds). + :param output_object_file: Path to save scaled Seurat object (.rds). + :param vars_to_regress: Comma-separated variables to regress out (e.g., "nCount_RNA,percent.mt"). + :param do_center: Whether to center the data. + :param do_scale: Whether to scale the data. + """ + if not Path(input_object_file).exists(): + raise FileNotFoundError(f"Input file not found: {input_object_file}") + + cmd = [ + "seurat-scale-data.R", + "--input-object-file", input_object_file, + "--output-object-file", output_object_file, + "--do-center", str(do_center).upper(), + "--do-scale", str(do_scale).upper() + ] + + if vars_to_regress: + cmd.extend(["--vars-to-regress", vars_to_regress]) + + return run_command(cmd) + +@mcp.tool() +def seurat_run_pca( + input_object_file: str, + output_object_file: str, + npcs: int = 50, + features: Optional[str] = None +): + """ + Run Principal Component Analysis (PCA). + + :param input_object_file: Path to input Seurat object (.rds). + :param output_object_file: Path to save Seurat object with PCA (.rds). + :param npcs: Number of PCs to compute. + :param features: Comma-separated list of features to use for PCA (defaults to variable features). + """ + if not Path(input_object_file).exists(): + raise FileNotFoundError(f"Input file not found: {input_object_file}") + + cmd = [ + "seurat-run-pca.R", + "--input-object-file", input_object_file, + "--output-object-file", output_object_file, + "--npcs", str(npcs) + ] + + if features: + cmd.extend(["--features", features]) + + return run_command(cmd) + +@mcp.tool() +def seurat_find_neighbors( + input_object_file: str, + output_object_file: str, + dims: str = "1:20", + reduction: str = "pca" +): + """ + Compute the Shared Nearest Neighbor (SNN) graph. + + :param input_object_file: Path to input Seurat object (.rds). + :param output_object_file: Path to save Seurat object with SNN graph (.rds). + :param dims: Dimensions of reduction to use as input (e.g., "1:20"). + :param reduction: Which reduction to use (e.g., "pca"). + """ + if not Path(input_object_file).exists(): + raise FileNotFoundError(f"Input file not found: {input_object_file}") + + cmd = [ + "seurat-find-neighbors.R", + "--input-object-file", input_object_file, + "--output-object-file", output_object_file, + "--dims", dims, + "--reduction", reduction + ] + + return run_command(cmd) + +@mcp.tool() +def seurat_find_clusters( + input_object_file: str, + output_object_file: str, + resolution: float = 0.5, + algorithm: int = 1 +): + """ + Cluster cells using the Louvain or other algorithms. + + :param input_object_file: Path to input Seurat object (.rds). + :param output_object_file: Path to save Seurat object with clusters (.rds). + :param resolution: Value of the resolution parameter (higher values = more clusters). + :param algorithm: Algorithm for modularity optimization (1 = Louvain; 2 = Louvain with multilevel refinement; 3 = SLM; 4 = Leiden). + """ + if not Path(input_object_file).exists(): + raise FileNotFoundError(f"Input file not found: {input_object_file}") + + cmd = [ + "seurat-find-clusters.R", + "--input-object-file", input_object_file, + "--output-object-file", output_object_file, + "--resolution", str(resolution), + "--algorithm", str(algorithm) + ] + + return run_command(cmd) + +@mcp.tool() +def seurat_run_umap( + input_object_file: str, + output_object_file: str, + dims: str = "1:20", + reduction: str = "pca" +): + """ + Run Uniform Manifold Approximation and Projection (UMAP) for visualization. + + :param input_object_file: Path to input Seurat object (.rds). + :param output_object_file: Path to save Seurat object with UMAP (.rds). + :param dims: Dimensions of reduction to use as input (e.g., "1:20"). + :param reduction: Which reduction to use (e.g., "pca"). + """ + if not Path(input_object_file).exists(): + raise FileNotFoundError(f"Input file not found: {input_object_file}") + + cmd = [ + "seurat-run-umap.R", + "--input-object-file", input_object_file, + "--output-object-file", output_object_file, + "--dims", dims, + "--reduction", reduction + ] + + return run_command(cmd) + +@mcp.tool() +def seurat_find_markers( + input_object_file: str, + output_text_file: str, + min_pct: float = 0.1, + logfc_threshold: float = 0.25, + test_use: str = "wilcox" +): + """ + Find differentially expressed features (markers) for all clusters. + + :param input_object_file: Path to input Seurat object (.rds). + :param output_text_file: Path to save the markers table (TSV/CSV). + :param min_pct: Only test genes that are detected in a minimum fraction of cells in either of the two populations. + :param logfc_threshold: Limit testing to genes which show, on average, at least X-fold difference (log-scale) between the two groups. + :param test_use: Denotes which test to use (e.g., wilcox, MAST, DESeq2). + """ + if not Path(input_object_file).exists(): + raise FileNotFoundError(f"Input file not found: {input_object_file}") + + cmd = [ + "seurat-find-markers.R", + "--input-object-file", input_object_file, + "--output-text-file", output_text_file, + "--min-pct", str(min_pct), + "--logfc-threshold", str(logfc_threshold), + "--test-use", test_use + ] + + return run_command(cmd) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seurat-scripts/app/seurat-scripts_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seurat-scripts/app/seurat-scripts_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..885fdc76e5e5674ad6166dee2368e29914891669 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seurat-scripts/app/seurat-scripts_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_seurat-scripts/app/seurat-scripts_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_seurat_scripts' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seurat-scripts/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seurat-scripts/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..ed75cf1ec1ee0553f9ff714d32562473577e60cf --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seurat-scripts/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-seurat-scripts: + build: . + image: mcp-seurat-scripts:latest + container_name: mcp-seurat-scripts + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=seurat-scripts + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seurat-scripts/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seurat-scripts/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e0aaae18e5ef24136d839a0d8210e0c11560b4a0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seurat-scripts/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - seurat-scripts + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seurat-scripts/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seurat-scripts/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_seurat-scripts/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sevenbridges-python/app/sevenbridges-python_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sevenbridges-python/app/sevenbridges-python_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c0d53dc7e6d189a58277bfe83efa1aff7cf6b7a0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sevenbridges-python/app/sevenbridges-python_server.py @@ -0,0 +1,535 @@ +import subprocess +import json +from pathlib import Path +from typing import Optional, List, Dict, Any +import os +import tempfile + +# --- Start of sevenbridges-python library placeholder --- +# This section simulates the sevenbridges-python library for demonstration purposes. +# In a real MCP environment, the actual 'sevenbridges' library would be installed +# and imported directly. This placeholder allows the code to be runnable +# without the actual library being present. + +class SbgError(Exception): + """Base exception for Seven Bridges API errors.""" + def __init__(self, message: str, status_code: Optional[int] = None, response_data: Optional[Dict[str, Any]] = None): + super().__init__(message) + self.status_code = status_code + self.response_data = response_data + def __str__(self): + status_str = f" (Status: {self.status_code})" if self.status_code else "" + return f"Seven Bridges API Error{status_str}: {self.args[0]}" + +class Config: + def __init__(self, url: Optional[str] = None, token: Optional[str] = None, profile: Optional[str] = None): + self.url = url + self.token = token + self.profile = profile + + if profile: + # Simulate loading from a config file based on profile + if profile == 'cgc': + self.url = 'https://cgc-api.sbgenomics.com/v2' + self.token = 'MOCK_CGC_TOKEN_FROM_PROFILE' + elif profile == 'cavatica': + self.url = 'https://cavatica-api.sbgenomics.com/v2' + self.token = 'MOCK_CAVATICA_TOKEN_FROM_PROFILE' + elif profile == 'default': + self.url = 'https://api.sbgenomics.com/v2' + self.token = 'MOCK_DEFAULT_TOKEN_FROM_PROFILE' + else: + raise SbgError(f"Unknown profile: {profile}. Valid profiles are 'default', 'cgc', 'cavatica'.") + elif not self.url or not self.token: + # Attempt to load from environment variables if no explicit params or profile + self.url = os.environ.get('SB_API_ENDPOINT', self.url) + self.token = os.environ.get('SB_AUTH_TOKEN', self.token) + if not self.url or not self.token: + raise SbgError("API URL and token must be provided explicitly, via environment variables (SB_API_ENDPOINT, SB_AUTH_TOKEN), or a profile specified.") + +class User: + def __init__(self, id: str, username: str, email: str): + self.id = id + self.username = username + self.email = email + + def to_dict(self) -> Dict[str, str]: + return {"id": self.id, "username": self.username, "email": self.email} + +class Project: + def __init__(self, id: str, name: str, owner: str, description: Optional[str] = None): + self.id = id + self.name = name + self.owner = owner + self.description = description + self._files: List['File'] = [] # Simulate files for this project + + def to_dict(self) -> Dict[str, Optional[str]]: + return { + "id": self.id, + "name": self.name, + "owner": self.owner, + "description": self.description + } + + def get_files(self, limit: int = 100, offset: int = 0) -> List['File']: + # Simulate fetching files for a project + if not self._files: + # Populate some mock files if empty + self._files = [ + File(f"file-{self.id}-{i}", f"sample_data_{i}.fastq.gz", 1024 * (i + 1), "FASTQ", self.id) + for i in range(5) + ] + return self._files[offset:offset + limit] + +class File: + def __init__(self, id: str, name: str, size: int, file_type: str, project_id: str): + self.id = id + self.name = name + self.size = size + self.type = file_type + self.project_id = project_id + + def to_dict(self) -> Dict[str, Any]: + return { + "id": self.id, + "name": self.name, + "size": self.size, + "type": self.type, + "project_id": self.project_id + } + + def download(self, path: Path) -> Path: + # Simulate file download + try: + with open(path, 'w') as f: + f.write(f"Mock content for file {self.name} (ID: {self.id}) from project {self.project_id}\n") + return path + except IOError as e: + raise SbgError(f"Failed to write file to {path}: {e}") + +class Users: + def me(self) -> User: + # Simulate fetching current user + return User("user-123", "testuser", "test@example.com") + +class Projects: + def __init__(self): + self._projects = [ + Project("proj-abc", "My First Project", "testuser", "A project for testing."), + Project("proj-def", "Genomics Data", "testuser", "Contains various genomics datasets."), + Project("proj-ghi", "RNA-seq Analysis", "anotheruser", "RNA-seq results."), + ] + + def query(self, limit: int = 100, offset: int = 0) -> List[Project]: + # Simulate querying projects + return self._projects[offset:offset + limit] + + def get(self, project_id: str) -> Project: + for p in self._projects: + if p.id == project_id: + return p + raise SbgError(f"Project with ID '{project_id}' not found.", status_code=404) + +class FilesManager: # Renamed to avoid conflict with File class + def __init__(self, projects_manager: Projects): + self._projects_manager = projects_manager + self._all_files: List[File] = [] + # Populate mock files from projects + for p in self._projects_manager._projects: + self._all_files.extend(p.get_files()) + + def get(self, file_id: str) -> File: + for f in self._all_files: + if f.id == file_id: + return f + raise SbgError(f"File with ID '{file_id}' not found.", status_code=404) + +class Api: + def __init__(self, config: Optional[Config] = None, url: Optional[str] = None, token: Optional[str] = None): + if config: + self.config = config + else: + self.config = Config(url=url, token=token) + + # Simulate API resources + self.users = Users() + self.projects = Projects() + self.files = FilesManager(self.projects) # Use FilesManager + +# Alias for the simulated library +sevenbridges = Api +sevenbridges.Config = Config +sevenbridges.Api = Api +sevenbridges.SbgError = SbgError +# --- End of sevenbridges-python library placeholder --- + + +def _initialize_sevenbridges_api(api_url: Optional[str], auth_token: Optional[str], profile: Optional[str]) -> sevenbridges.Api: + """ + Helper function to initialize the Seven Bridges API object. + Handles different authentication methods. + """ + if profile: + if api_url is not None or auth_token is not None: + raise ValueError("Cannot specify both 'profile' and explicit 'api_url'/'auth_token'.") + config = sevenbridges.Config(profile=profile) + elif api_url is not None and auth_token is not None: + config = sevenbridges.Config(url=api_url, token=auth_token) + else: + # Attempt to use environment variables if no explicit params or profile + config = sevenbridges.Config() # This will try to load from env vars internally + + return sevenbridges.Api(config=config) + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_sevenbridges_python' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def sbg_get_current_user( + api_url: Optional[str] = None, + auth_token: Optional[str] = None, + profile: Optional[str] = None, +) -> Dict[str, Any]: + """ + Retrieves information about the currently authenticated Seven Bridges Platform user. + + Authentication can be provided explicitly via `api_url` and `auth_token`, + by specifying a `profile` from the $HOME/.sevenbridges/credentials file, + or implicitly via environment variables (SB_API_ENDPOINT, SB_AUTH_TOKEN). + """ + stdout_lines: List[str] = [] + stderr_lines: List[str] = [] + command_executed = "sevenbridges.Api().users.me()" + + try: + api = _initialize_sevenbridges_api(api_url, auth_token, profile) + user = api.users.me() + user_info = user.to_dict() + stdout_lines.append(json.dumps(user_info, indent=2)) + return { + "command_executed": command_executed, + "stdout": "\n".join(stdout_lines), + "stderr": "", + "output_files": [], + "user_info": user_info # Structured output + } + except ValueError as e: + stderr_lines.append(f"Input validation error: {e}") + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "\n".join(stderr_lines), + "output_files": [], + "error": str(e) + } + except sevenbridges.SbgError as e: + stderr_lines.append(f"Seven Bridges API Error: {e}") + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "\n".join(stderr_lines), + "output_files": [], + "error": str(e), + "status_code": e.status_code, + "response_data": e.response_data + } + except Exception as e: + stderr_lines.append(f"An unexpected error occurred: {e}") + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "\n".join(stderr_lines), + "output_files": [], + "error": str(e) + } + + +@mcp.tool() +def sbg_list_projects( + api_url: Optional[str] = None, + auth_token: Optional[str] = None, + profile: Optional[str] = None, + limit: int = 100, + offset: int = 0, +) -> Dict[str, Any]: + """ + Lists projects accessible to the authenticated Seven Bridges Platform user. + + Authentication can be provided explicitly via `api_url` and `auth_token`, + by specifying a `profile` from the $HOME/.sevenbridges/credentials file, + or implicitly via environment variables (SB_API_ENDPOINT, SB_AUTH_TOKEN). + + Args: + limit: The maximum number of projects to return. Must be a positive integer. + offset: The number of projects to skip before starting to return results. Must be a non-negative integer. + """ + stdout_lines: List[str] = [] + stderr_lines: List[str] = [] + command_executed = f"sevenbridges.Api().projects.query(limit={limit}, offset={offset})" + + # Input validation + if not isinstance(limit, int) or limit <= 0: + stderr_lines.append("Error: 'limit' must be a positive integer.") + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "\n".join(stderr_lines), + "output_files": [], + "error": "'limit' must be a positive integer." + } + if not isinstance(offset, int) or offset < 0: + stderr_lines.append("Error: 'offset' must be a non-negative integer.") + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "\n".join(stderr_lines), + "output_files": [], + "error": "'offset' must be a non-negative integer." + } + + try: + api = _initialize_sevenbridges_api(api_url, auth_token, profile) + projects = api.projects.query(limit=limit, offset=offset) + project_list = [p.to_dict() for p in projects] + stdout_lines.append(json.dumps(project_list, indent=2)) + return { + "command_executed": command_executed, + "stdout": "\n".join(stdout_lines), + "stderr": "", + "output_files": [], + "projects": project_list # Structured output + } + except ValueError as e: + stderr_lines.append(f"Input validation error: {e}") + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "\n".join(stderr_lines), + "output_files": [], + "error": str(e) + } + except sevenbridges.SbgError as e: + stderr_lines.append(f"Seven Bridges API Error: {e}") + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "\n".join(stderr_lines), + "output_files": [], + "error": str(e), + "status_code": e.status_code, + "response_data": e.response_data + } + except Exception as e: + stderr_lines.append(f"An unexpected error occurred: {e}") + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "\n".join(stderr_lines), + "output_files": [], + "error": str(e) + } + + +@mcp.tool() +def sbg_list_project_files( + project_id: str, + api_url: Optional[str] = None, + auth_token: Optional[str] = None, + profile: Optional[str] = None, + limit: int = 100, + offset: int = 0, +) -> Dict[str, Any]: + """ + Lists files within a specific Seven Bridges Platform project. + + Authentication can be provided explicitly via `api_url` and `auth_token`, + by specifying a `profile` from the $HOME/.sevenbridges/credentials file, + or implicitly via environment variables (SB_API_ENDPOINT, SB_AUTH_TOKEN). + + Args: + project_id: The ID of the project to list files from. + limit: The maximum number of files to return. Must be a positive integer. + offset: The number of files to skip before starting to return results. Must be a non-negative integer. + """ + stdout_lines: List[str] = [] + stderr_lines: List[str] = [] + command_executed = f"sevenbridges.Api().projects.get('{project_id}').get_files(limit={limit}, offset={offset})" + + # Input validation + if not project_id: + stderr_lines.append("Error: 'project_id' cannot be empty.") + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "\n".join(stderr_lines), + "output_files": [], + "error": "'project_id' cannot be empty." + } + if not isinstance(limit, int) or limit <= 0: + stderr_lines.append("Error: 'limit' must be a positive integer.") + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "\n".join(stderr_lines), + "output_files": [], + "error": "'limit' must be a positive integer." + } + if not isinstance(offset, int) or offset < 0: + stderr_lines.append("Error: 'offset' must be a non-negative integer.") + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "\n".join(stderr_lines), + "output_files": [], + "error": "'offset' must be a non-negative integer." + } + + try: + api = _initialize_sevenbridges_api(api_url, auth_token, profile) + project = api.projects.get(project_id) + files = project.get_files(limit=limit, offset=offset) + file_list = [f.to_dict() for f in files] + stdout_lines.append(json.dumps(file_list, indent=2)) + return { + "command_executed": command_executed, + "stdout": "\n".join(stdout_lines), + "stderr": "", + "output_files": [], + "files": file_list # Structured output + } + except ValueError as e: + stderr_lines.append(f"Input validation error: {e}") + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "\n".join(stderr_lines), + "output_files": [], + "error": str(e) + } + except sevenbridges.SbgError as e: + stderr_lines.append(f"Seven Bridges API Error: {e}") + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "\n".join(stderr_lines), + "output_files": [], + "error": str(e), + "status_code": e.status_code, + "response_data": e.response_data + } + except Exception as e: + stderr_lines.append(f"An unexpected error occurred: {e}") + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "\n".join(stderr_lines), + "output_files": [], + "error": str(e) + } + + +@mcp.tool() +def sbg_download_file( + file_id: str, + output_path: Path, + api_url: Optional[str] = None, + auth_token: Optional[str] = None, + profile: Optional[str] = None, +) -> Dict[str, Any]: + """ + Downloads a specific file from the Seven Bridges Platform to a local path. + + Authentication can be provided explicitly via `api_url` and `auth_token`, + by specifying a `profile` from the $HOME/.sevenbridges/credentials file, + or implicitly via environment variables (SB_API_ENDPOINT, SB_AUTH_TOKEN). + + Args: + file_id: The ID of the file to download. + output_path: The local path where the file should be saved. + """ + stdout_lines: List[str] = [] + stderr_lines: List[str] = [] + command_executed = f"sevenbridges.Api().files.get('{file_id}').download(path='{output_path}')" + + # Input validation + if not file_id: + stderr_lines.append("Error: 'file_id' cannot be empty.") + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "\n".join(stderr_lines), + "output_files": [], + "error": "'file_id' cannot be empty." + } + if not isinstance(output_path, Path): + stderr_lines.append("Error: 'output_path' must be a pathlib.Path object.") + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "\n".join(stderr_lines), + "output_files": [], + "error": "'output_path' must be a pathlib.Path object." + } + + # Ensure parent directory exists + try: + output_path.parent.mkdir(parents=True, exist_ok=True) + except OSError as e: + stderr_lines.append(f"Error creating output directory '{output_path.parent}': {e}") + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "\n".join(stderr_lines), + "output_files": [], + "error": f"Failed to create output directory: {e}" + } + + try: + api = _initialize_sevenbridges_api(api_url, auth_token, profile) + sbg_file = api.files.get(file_id) + downloaded_path = sbg_file.download(output_path) + + stdout_lines.append(f"Successfully downloaded file '{sbg_file.name}' (ID: {file_id}) to '{downloaded_path}'") + return { + "command_executed": command_executed, + "stdout": "\n".join(stdout_lines), + "stderr": "", + "output_files": [str(downloaded_path)], + "downloaded_file_info": sbg_file.to_dict() # Structured output + } + except ValueError as e: + stderr_lines.append(f"Input validation error: {e}") + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "\n".join(stderr_lines), + "output_files": [], + "error": str(e) + } + except sevenbridges.SbgError as e: + stderr_lines.append(f"Seven Bridges API Error: {e}") + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "\n".join(stderr_lines), + "output_files": [], + "error": str(e), + "status_code": e.status_code, + "response_data": e.response_data + } + except Exception as e: + stderr_lines.append(f"An unexpected error occurred: {e}") + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "\n".join(stderr_lines), + "output_files": [], + "error": str(e) + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sina/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sina/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2badc059aa16bc8124a8a198d3c2a1c4f7dd58fe --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sina/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install sina via conda (e.g., from bioconda) +RUN conda install -c bioconda sina -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/sina_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/sina_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/sina_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sina/app/__pycache__/sina_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sina/app/__pycache__/sina_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..92489e2edb12dc4b61709f596811087b94d204e4 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sina/app/__pycache__/sina_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sina/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sina/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sina/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sina/app/sina_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sina/app/sina_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5203d2492158993b5205f3f434076609b47c3ea1 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sina/app/sina_server.py @@ -0,0 +1,252 @@ +from pathlib import Path +import subprocess +from typing import Optional, List, Union + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_sina' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def sina( + in_file: str, + out_file: str, + db: str, + threads: int = 1, + search: bool = False, + search_db: Optional[str] = None, + lca_tax: bool = False, + lca_quorum: float = 0.8, + min_identity: float = 0.7, + turn: str = "yes", + prealigned: bool = False, + intype: str = "fasta", + outtype: str = "fasta", + fs_min_identity: float = 0.7, + fs_mismatch: int = 2, + fs_gap_open: int = 5, + fs_gap_extend: int = 2, + overhang: str = "attach", + insertion: str = "all", + remove_unaligned: bool = False, + sample_id: Optional[str] = None, +): + """ + SINA: Reference-based multiple sequence alignment, homology search, and LCA-based classification. + + SINA aligns nucleotide sequences to match a pre-existing MSA using a graph-based alignment algorithm. + It is particularly optimized for ribosomal RNA genes (SSU/LSU). + + Args: + in_file: Path to the input sequence file (FASTA, FASTQ, or ARB). + out_file: Path to the output file. + db: Path to the reference database (ARB format or FASTA). + threads: Number of threads to use for processing. + search: Enable homology search against the reference database. + search_db: Path to a separate search database (if different from alignment db). + lca_tax: Enable LCA (Lowest Common Ancestor) based taxonomic classification. + lca_quorum: Fraction of search results that must agree for a classification (0.0-1.0). + min_identity: Minimum identity threshold for search results. + turn: Try reverse complement of sequences. Options: 'yes', 'no', 'all'. + prealigned: Set to True if input sequences are already aligned. + intype: Input file format ('fasta', 'fastq', 'arb'). + outtype: Output file format ('fasta', 'arb'). + fs_min_identity: Minimum identity for the alignment stage. + fs_mismatch: Mismatch penalty for alignment. + fs_gap_open: Gap open penalty for alignment. + fs_gap_extend: Gap extension penalty for alignment. + overhang: How to handle overhangs ('attach', 'edge', 'remove'). + insertion: How to handle insertions ('all', 'none', 'upper'). + remove_unaligned: If True, sequences that fail to align will be excluded from output. + sample_id: Optional identifier for the run. + """ + # Input validation + input_path = Path(in_file) + if not input_path.exists(): + return {"error": f"Input file not found: {in_file}"} + + db_path = Path(db) + if not db_path.exists(): + return {"error": f"Reference database not found: {db}"} + + output_path = Path(out_file) + output_path.parent.mkdir(parents=True, exist_ok=True) + + # Construct command + cmd = [ + "sina", + "--in", str(input_path), + "--out", str(output_path), + "--db", str(db_path), + "--threads", str(threads), + "--intype", intype, + "--outtype", outtype, + "--turn", turn, + "--overhang", overhang, + "--insertion", insertion, + "--min-identity", str(min_identity), + "--fs-min-identity", str(fs_min_identity), + "--fs-mismatch", str(fs_mismatch), + "--fs-gap-open", str(fs_gap_open), + "--fs-gap-extend", str(fs_gap_extend) + ] + + # Boolean flags + if search: + cmd.append("--search") + if lca_tax: + cmd.append("--lca-tax") + if prealigned: + cmd.append("--prealigned") + if remove_unaligned: + cmd.append("--remove-unaligned") + + # Optional parameters with values + if search_db: + sdb_path = Path(search_db) + if not sdb_path.exists(): + return {"error": f"Search database not found: {search_db}"} + cmd.extend(["--search-db", str(sdb_path)]) + + if lca_tax: + cmd.extend(["--lca-quorum", str(lca_quorum)]) + + if sample_id: + cmd.extend(["--sample-id", sample_id]) + + 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": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def sina_search( + in_file: str, + db: str, + out_file: str, + threads: int = 1, + min_identity: float = 0.7, + max_parents: int = 10, + search_kmer_candidates: int = 1000, + lca_tax: bool = False, +): + """ + Perform only a homology search and/or classification using SINA without full alignment. + + Args: + in_file: Path to the input sequence file. + db: Path to the reference database (ARB or FASTA). + out_file: Path to save search results. + threads: Number of threads. + min_identity: Minimum identity for search hits. + max_parents: Maximum number of search neighbors to report. + search_kmer_candidates: Number of k-mer candidates to consider. + lca_tax: Enable LCA classification based on search results. + """ + input_path = Path(in_file) + db_path = Path(db) + output_path = Path(out_file) + + if not input_path.exists(): + return {"error": f"Input file not found: {in_file}"} + if not db_path.exists(): + return {"error": f"Database not found: {db}"} + + cmd = [ + "sina", + "--in", str(input_path), + "--out", str(output_path), + "--db", str(db_path), + "--threads", str(threads), + "--search", + "--no-align", # Skip alignment stage + "--min-identity", str(min_identity), + "--search-max-parents", str(max_parents), + "--search-kmer-candidates", str(search_kmer_candidates) + ] + + if lca_tax: + cmd.append("--lca-tax") + + 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": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def sina_convert( + in_file: str, + out_file: str, + intype: str = "arb", + outtype: str = "fasta", + filter_aligned: bool = False, +): + """ + Use SINA to convert between sequence formats (ARB, FASTA, FASTQ). + + Args: + in_file: Input file path. + out_file: Output file path. + intype: Input format ('arb', 'fasta', 'fastq'). + outtype: Output format ('arb', 'fasta', 'fastq'). + filter_aligned: If True, only export sequences that have an alignment. + """ + input_path = Path(in_file) + output_path = Path(out_file) + + if not input_path.exists(): + return {"error": f"Input file not found: {in_file}"} + + cmd = [ + "sina", + "--in", str(input_path), + "--out", str(output_path), + "--intype", intype, + "--outtype", outtype, + "--no-align", + "--no-search" + ] + + if filter_aligned: + cmd.append("--filter-aligned") + + 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": [str(output_path)] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sina/app/sina_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sina/app/sina_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4511300958db1799c3956228ec5d22b717f28c0e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sina/app/sina_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_sina/app/sina_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_sina' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sina/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sina/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..3024c6eb460f5a2949619f05f07d167f8caeffc7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sina/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-sina: + build: . + image: mcp-sina:latest + container_name: mcp-sina + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=sina + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sina/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sina/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..aa22f5bf431ed27a18928d711f2145146afe1631 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sina/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - sina + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sina/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sina/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_sina/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-interface-report-plugins/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-interface-report-plugins/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3ed6afe83f4ba4c68732169e03e0eb4f10a5c53d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-interface-report-plugins/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install snakemake-interface-report-plugins via conda (e.g., from bioconda) +RUN conda install -c bioconda snakemake-interface-report-plugins -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/snakemake-interface-report-plugins_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/snakemake-interface-report-plugins_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/snakemake-interface-report-plugins_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-interface-report-plugins/app/__pycache__/snakemake-interface-report-plugins_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-interface-report-plugins/app/__pycache__/snakemake-interface-report-plugins_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a2ce49d2fda1e39c169fcb44f1cc0ad3c9197207 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-interface-report-plugins/app/__pycache__/snakemake-interface-report-plugins_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-interface-report-plugins/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-interface-report-plugins/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-interface-report-plugins/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-interface-report-plugins/app/snakemake-interface-report-plugins_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-interface-report-plugins/app/snakemake-interface-report-plugins_server.py new file mode 100644 index 0000000000000000000000000000000000000000..00fd6f024ec89cc04695ff7826da5acdf436b969 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-interface-report-plugins/app/snakemake-interface-report-plugins_server.py @@ -0,0 +1,297 @@ +import subprocess +import sys +import json +from pathlib import Path +from typing import Optional, Dict, Any, List + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_snakemake_interface_report_plugins' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def list_snakemake_report_plugins() -> Dict[str, Any]: + """ + List all currently installed Snakemake report plugins. + This tool queries the Snakemake report plugin registry to identify available reporters. + """ + python_script = """ +import json +from snakemake_interface_report_plugins.registry import ReportPluginRegistry +try: + registry = ReportPluginRegistry() + plugins = list(registry.get_plugins().keys()) + print(json.dumps({"plugins": plugins})) +except Exception as e: + print(json.dumps({"error": str(e)})) + """ + + command = [sys.executable, "-c", python_script] + + try: + result = subprocess.run(command, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "output": json.loads(result.stdout) + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to list report plugins" + } + except json.JSONDecodeError: + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "error": "Failed to parse plugin registry output" + } + +@mcp.tool() +def get_snakemake_report_plugin_info(plugin_name: str) -> Dict[str, Any]: + """ + Get detailed information about a specific Snakemake report plugin. + + Args: + plugin_name: The name of the report plugin (e.g., 'default', 'html'). + """ + if not plugin_name: + return {"error": "plugin_name is required"} + + python_script = f""" +import json +import dataclasses +from snakemake_interface_report_plugins.registry import ReportPluginRegistry + +try: + registry = ReportPluginRegistry() + plugin_name = "{plugin_name}" + if plugin_name not in registry.get_plugins(): + print(json.dumps({{"error": f"Plugin {{plugin_name}} not found"}})) + else: + plugin = registry.get_plugin(plugin_name) + settings = [] + if plugin.settings_cls: + for field in dataclasses.fields(plugin.settings_cls): + settings.append({{ + "name": field.name, + "type": str(field.type), + "default": str(field.default) if field.default is not dataclasses.MISSING else "Required", + "help": field.metadata.get("help", ""), + "required": field.metadata.get("required", False), + "env_var": field.metadata.get("env_var", False) + }}) + + print(json.dumps({{ + "name": plugin.name, + "description": plugin.reporter_cls.__doc__ or "No description available", + "settings": settings, + "reporter_class": plugin.reporter_cls.__name__ + }})) +except Exception as e: + print(json.dumps({{"error": str(e)}})) + """ + + command = [sys.executable, "-c", python_script] + + try: + result = subprocess.run(command, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "output": json.loads(result.stdout) + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Failed to get info for plugin: {plugin_name}" + } + +@mcp.tool() +def validate_snakemake_report_plugin_settings( + plugin_name: str, + settings_json: str +) -> Dict[str, Any]: + """ + Validate a set of settings against a Snakemake report plugin's requirements. + + Args: + plugin_name: The name of the report plugin. + settings_json: A JSON string containing the settings to validate (e.g., '{"myparam": 10}'). + """ + # Input validation + try: + json.loads(settings_json) + except json.JSONDecodeError: + return {"error": "settings_json must be a valid JSON string"} + + python_script = f""" +import json +import dataclasses +from snakemake_interface_report_plugins.registry import ReportPluginRegistry + +try: + registry = ReportPluginRegistry() + plugin_name = "{plugin_name}" + settings_dict = json.loads('{settings_json}') + + if plugin_name not in registry.get_plugins(): + print(json.dumps({{"valid": False, "error": f"Plugin {{plugin_name}} not found"}})) + else: + plugin = registry.get_plugin(plugin_name) + if not plugin.settings_cls: + print(json.dumps({{"valid": True, "message": "Plugin has no settings to validate"}})) + else: + # Attempt to instantiate the settings class + try: + # Filter settings to only those defined in the class + valid_fields = {{f.name for f in dataclasses.fields(plugin.settings_cls)}} + filtered_settings = {{k: v for k, v in settings_dict.items() if k in valid_fields}} + + # Check for missing required fields + missing = [] + for field in dataclasses.fields(plugin.settings_cls): + if field.metadata.get("required") and field.name not in settings_dict: + missing.append(field.name) + + if missing: + print(json.dumps({{"valid": False, "error": f"Missing required settings: {{', '.join(missing)}}"}})) + else: + # Try instantiation + instance = plugin.settings_cls(**filtered_settings) + print(json.dumps({{"valid": True, "message": "Settings are valid"}})) + except Exception as ve: + print(json.dumps({{"valid": False, "error": str(ve)}})) +except Exception as e: + print(json.dumps({{"error": str(e)}})) + """ + + command = [sys.executable, "-c", python_script] + + try: + result = subprocess.run(command, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "output": json.loads(result.stdout) + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Validation process failed" + } + +@mcp.tool() +def get_report_plugin_interface_skeleton() -> Dict[str, Any]: + """ + Returns the Python code skeleton required to implement a new Snakemake report plugin. + This is useful for developers creating new plugins that comply with the interface. + """ + skeleton = """ +from dataclasses import dataclass, field +from typing import Optional +from snakemake_interface_report_plugins.reporter import ReporterBase +from snakemake_interface_report_plugins.settings import ReportSettingsBase + +@dataclass +class ReportSettings(ReportSettingsBase): + # Define additional settings for your reporter. + # They will occur in the Snakemake CLI as --report-- + myparam: Optional[int] = field( + default=None, + metadata={ + "help": "Some help text", + "env_var": False, # Set to True for passwords/usernames + "required": False + } + ) + +class Reporter(ReporterBase): + def __post_init__(self): + # Initialize additional attributes. + # Settings are accessible via self.settings. + pass + + def render(self): + # Render the report, using attributes of the base class. + # See ReporterBase for available attributes like self.dag, self.results, etc. + pass + """ + return { + "description": "Skeleton for Snakemake Report Plugin implementation", + "code": skeleton.strip(), + "requirements": ["snakemake-interface-report-plugins", "snakemake-interface-common"] + } + +@mcp.tool() +def check_report_plugin_compatibility(plugin_module_path: str) -> Dict[str, Any]: + """ + Check if a local Python module correctly implements the Snakemake report plugin interface. + + Args: + plugin_module_path: Absolute path to the Python file containing the plugin implementation. + """ + path = Path(plugin_module_path) + if not path.exists(): + return {"error": f"File not found: {plugin_module_path}"} + if not path.suffix == ".py": + return {"error": "Plugin must be a .py file"} + + python_script = f""" +import importlib.util +import sys +import json +from snakemake_interface_report_plugins.reporter import ReporterBase +from snakemake_interface_report_plugins.settings import ReportSettingsBase + +def check(): + try: + spec = importlib.util.spec_from_file_location("plugin_test", "{plugin_module_path}") + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + + has_reporter = hasattr(module, "Reporter") and issubclass(module.Reporter, ReporterBase) + has_settings = hasattr(module, "ReportSettings") and issubclass(module.ReportSettings, ReportSettingsBase) + + print(json.dumps({{ + "is_compatible": has_reporter, + "has_reporter_class": has_reporter, + "has_settings_class": has_settings, + "details": "Reporter class must inherit from ReporterBase" if not has_reporter else "Compatible" + }})) + except Exception as e: + print(json.dumps({{"is_compatible": False, "error": str(e)}})) + +check() + """ + + command = [sys.executable, "-c", python_script] + + try: + result = subprocess.run(command, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "output": json.loads(result.stdout) + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Compatibility check failed" + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-interface-report-plugins/app/snakemake-interface-report-plugins_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-interface-report-plugins/app/snakemake-interface-report-plugins_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..be6c42d2ab38a34d47e95a32eb173e773bc25e5b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-interface-report-plugins/app/snakemake-interface-report-plugins_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_snakemake-interface-report-plugins/app/snakemake-interface-report-plugins_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_snakemake_interface_report_plugins' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-interface-report-plugins/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-interface-report-plugins/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..42821ca4cb750f3c67411bb4e7991670c14e7227 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-interface-report-plugins/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-snakemake-interface-report-plugins: + build: . + image: mcp-snakemake-interface-report-plugins:latest + container_name: mcp-snakemake-interface-report-plugins + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=snakemake-interface-report-plugins + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-interface-report-plugins/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-interface-report-plugins/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fdfb0960ddbcbe26966e6a3b94ba5cb1698c5a81 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-interface-report-plugins/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - snakemake-interface-report-plugins + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-interface-report-plugins/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-interface-report-plugins/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_snakemake-interface-report-plugins/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spatialleiden/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spatialleiden/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fb60c428cb9a3e54fed8df15cd05fa626887f438 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spatialleiden/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install spatialleiden via conda (e.g., from bioconda) +RUN conda install -c bioconda spatialleiden -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/spatialleiden_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/spatialleiden_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/spatialleiden_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spatialleiden/app/__pycache__/spatialleiden_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spatialleiden/app/__pycache__/spatialleiden_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5cd12da7ca72e390cd6dd3c015be6f7bc58400c5 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spatialleiden/app/__pycache__/spatialleiden_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spatialleiden/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spatialleiden/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spatialleiden/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spatialleiden/app/spatialleiden_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spatialleiden/app/spatialleiden_server.py new file mode 100644 index 0000000000000000000000000000000000000000..759d8d86700296eb0f63bed0f1a276fb4fe5a594 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spatialleiden/app/spatialleiden_server.py @@ -0,0 +1,128 @@ +import subprocess +from pathlib import Path +from typing import Literal +import logging + +# It is assumed that the @mcp.tool decorator is available in the execution environment. +# We define the function as if 'mcp' is already imported. + +# Set up a logger for better debugging +logger = logging.getLogger(__name__) + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_spatialleiden' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_spatialleiden( + input_file: Path, + output_file: Path, + resolution: float = 1.0, + n_neighbors: int = 10, + metric: Literal["euclidean", "manhattan", "cosine"] = "euclidean", + weight: float = 1.0, + seed: int = 0, + verbose: bool = False, +): + """ + Performs spatial Leiden clustering on spatial transcriptomics data. + + This tool identifies clusters of cells by considering both gene expression similarity + and spatial proximity, saving the results to a new AnnData file. + + Args: + input_file: Path to the input AnnData file (.h5ad). + output_file: Path to the output AnnData file (.h5ad) where results will be saved. + resolution: Resolution parameter for the Leiden algorithm. Higher values lead to more clusters. + n_neighbors: Number of neighbors to use for building the spatial graph. + metric: Metric to use for computing distances between spots. + weight: Weight of the spatial graph relative to the expression graph. + seed: Random seed for reproducibility. + verbose: If True, enables verbose output from the tool. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # --- 1. Input Validation --- + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found at: {input_file}") + + if output_file.is_dir(): + raise IsADirectoryError(f"The specified output path '{output_file}' is a directory. Please provide a file path.") + + if resolution <= 0: + raise ValueError("The 'resolution' parameter must be a positive float.") + + if n_neighbors <= 0: + raise ValueError("The 'n_neighbors' parameter must be a positive integer.") + + if weight < 0: + raise ValueError("The 'weight' parameter must be non-negative.") + + # --- 2. File Path Handling --- + # Ensure the output directory exists before running the tool + output_file.parent.mkdir(parents=True, exist_ok=True) + + # --- 3. Command Construction --- + command = [ + "spatialleiden", + "--input", str(input_file), + "--output", str(output_file), + "--resolution", str(resolution), + "--n_neighbors", str(n_neighbors), + "--metric", metric, + "--weight", str(weight), + "--seed", str(seed), + ] + + if verbose: + command.append("--verbose") + + command_str = " ".join(command) + logger.info(f"Executing command: {command_str}") + + # --- 4. Subprocess Execution and Error Handling --- + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + + # --- 5. Structured Result Return --- + # Verify that the output file was created successfully + output_files_list = [str(output_file)] if output_file.exists() else [] + if not output_files_list: + logger.warning(f"Output file '{output_file}' was not created by the tool.") + + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files_list, + } + except FileNotFoundError: + error_message = "Error: 'spatialleiden' command not found. Please ensure the tool is installed and in your system's PATH." + logger.error(error_message) + # Return a structured error if the tool itself is not found + return { + "command_executed": command_str, + "stdout": "", + "stderr": error_message, + "output_files": [], + } + except subprocess.CalledProcessError as e: + # This block catches errors from the tool itself (non-zero exit codes) + logger.error(f"spatialleiden execution failed with return code {e.returncode}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spatialleiden/app/spatialleiden_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spatialleiden/app/spatialleiden_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f3539cc700eebf8da0fbfa55093d30df316f3100 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spatialleiden/app/spatialleiden_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_spatialleiden/app/spatialleiden_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_spatialleiden' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spatialleiden/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spatialleiden/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..2f29c4698db91f16d5097ebdbf851390d51a8b69 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spatialleiden/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-spatialleiden: + build: . + image: mcp-spatialleiden:latest + container_name: mcp-spatialleiden + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=spatialleiden + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spatialleiden/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spatialleiden/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2071ccbb294d55dd95afc763d07751d4a32b2923 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spatialleiden/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - spatialleiden + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spatialleiden/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spatialleiden/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_spatialleiden/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tirank/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tirank/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..485cff2676a8af2e82690780e99e77ccf68b1f81 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tirank/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install tirank via conda (e.g., from bioconda) +RUN conda install -c bioconda tirank -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/tirank_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/tirank_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/tirank_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tirank/app/__pycache__/tirank_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tirank/app/__pycache__/tirank_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..acc51ba15ab93ed928487ed43e947e61f99fa8aa Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tirank/app/__pycache__/tirank_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tirank/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tirank/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tirank/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tirank/app/tirank_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tirank/app/tirank_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f125f0ed1c9f4c9513fa79efd398636b3f2ef2f2 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tirank/app/tirank_server.py @@ -0,0 +1,322 @@ +import subprocess +import tempfile +import shutil +import os +from pathlib import Path +from typing import Optional, List, Dict, Any + +# No need to import mcp as per instructions, it's assumed to be available. + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_tirank' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_sc_classification_skcm( + tirank_repo_root: Path, + data_input_dir: Path, + output_dir: Path, +) -> Dict[str, Any]: + """ + Performs scRNA-seq to bulk classification for melanoma response using TiRank. + + This function wraps the 'Example/SC-Response-SKCM.py' script from the TiRank + repository, which integrates scRNA-seq data with bulk RNA-seq for phenotype + transfer and classification. The script expects 'dataPath' and 'savePath' + variables to be set internally, which this wrapper handles by generating + a temporary script. + + Args: + tirank_repo_root: Path to the root directory of the cloned TiRank repository. + This is crucial for locating the example script + (e.g., 'TiRank/Example/SC-Response-SKCM.py'). + This directory must exist. + data_input_dir: Path to the input data directory containing scRNA-seq + (e.g., GSE120575.h5ad) and bulk data (e.g., Liu2019_meta.csv, + Liu2019_exp.csv). This directory must exist. + output_dir: Path to the directory where all analysis results will be saved. + This directory will be created if it does not exist. + + Returns: + A dictionary containing execution details: + - command_executed: The command string that was run. + - stdout: Standard output from the command. + - stderr: Standard error from the command. + - output_files: A list of paths to generated output files, including + 'spot_predict_score.csv' and other key analysis outputs. + + Raises: + ValueError: If input paths are invalid or required files are missing. + RuntimeError: If the TiRank script execution fails. + """ + # Input validation + if not tirank_repo_root.is_dir(): + raise ValueError(f"TiRank repository root not found: {tirank_repo_root}") + if not data_input_dir.is_dir(): + raise ValueError(f"Input data directory not found: {data_input_dir}") + + # Ensure output directory exists + output_dir.mkdir(parents=True, exist_ok=True) + + script_path = tirank_repo_root / "Example" / "SC-Response-SKCM.py" + if not script_path.is_file(): + raise ValueError(f"TiRank example script not found: {script_path}. " + "Ensure 'tirank_repo_root' points to the correct repository clone " + "and contains the 'Example/SC-Response-SKCM.py' script.") + + command_executed = "" + stdout = "" + stderr = "" + output_files: List[Path] = [] + temp_script_path: Optional[Path] = None + + try: + # Create a temporary Python script to set dataPath and savePath + # and then execute the original script. + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.py') as temp_script_file: + temp_script_file.write(f""" +import sys +import os +from pathlib import Path + +# Set the dataPath and savePath variables as expected by the original script +dataPath = Path("{data_input_dir.resolve()}") +savePath = Path("{output_dir.resolve()}") + +# Add the directory containing the original script to sys.path +# This is important for any relative imports the original script might have. +sys.path.insert(0, str(Path("{script_path.parent.resolve()}"))) + +# Execute the original script's content in the current namespace. +# This makes dataPath and savePath available to it. +with open("{script_path.resolve()}", 'r') as f: + script_code = f.read() +exec(script_code, globals()) +""") + temp_script_path = Path(temp_script_file.name) + + # Execute the temporary script using the system's python interpreter + # The documentation states to run from the repo root. + cmd = ["python", str(temp_script_path)] + command_executed = " ".join(cmd) + + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + cwd=tirank_repo_root.resolve() # Run from repo root as per docs + ) + stdout = process.stdout + stderr = process.stderr + + # Identify expected output files based on the documentation's output structure + final_result_file = output_dir / "3_Analysis" / "spot_predict_score.csv" + if final_result_file.is_file(): + output_files.append(final_result_file) + + # Collect all files generated within the expected output subdirectories + for sub_dir_name in ["1_loaddata", "2_preprocessing", "3_Analysis"]: + current_sub_dir = output_dir / sub_dir_name + if current_sub_dir.is_dir(): + for f in current_sub_dir.rglob("*"): + if f.is_file(): + output_files.append(f) + + except subprocess.CalledProcessError as e: + stdout = e.stdout + stderr = e.stderr + raise RuntimeError( + f"TiRank SC classification failed with exit code {e.returncode}.\n" + f"Command: {command_executed}\n" + f"Stdout: {stdout}\n" + f"Stderr: {stderr}" + ) from e + except Exception as e: + raise RuntimeError(f"An unexpected error occurred during execution: {e}") from e + finally: + # Clean up the temporary script + if temp_script_path and temp_script_path.is_file(): + temp_script_path.unlink() + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [str(f) for f in output_files], + } + + +@mcp.tool() +def run_st_survival_crc( + tirank_repo_root: Path, + data_input_dir: Path, + output_dir: Path, + pretrained_model_file: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Performs spatial transcriptomics to bulk Cox survival analysis for CRC using TiRank. + + This function wraps the 'Example/ST-Cox-CRC.py' script from the TiRank + repository, which integrates spatial transcriptomics data with bulk RNA-seq + for phenotype transfer and survival analysis. The script expects 'dataPath' + and 'savePath' variables to be set internally, which this wrapper handles + by generating a temporary script. It also manages the placement of the + pretrained model file. + + Args: + tirank_repo_root: Path to the root directory of the cloned TiRank repository. + This is crucial for locating the example script + (e.g., 'TiRank/Example/ST-Cox-CRC.py'). + This directory must exist. + data_input_dir: Path to the input data directory containing spatial + transcriptomics data (e.g., SN048_A121573_Rep1/) and + bulk data (e.g., GSE39582_clinical_os.csv, + GSE39582_exp_os.csv). This directory must exist. + output_dir: Path to the directory where all analysis results will be saved. + This directory will be created if it does not exist. + pretrained_model_file: Optional path to the 'ctranspath.pth' pretrained model. + If provided, this file will be copied to the expected + default location: + '/data/pretrainModel/ctranspath.pth' + before execution. If not provided, the tool assumes + the model is already present at that default location. + This model is required for Spatial Transcriptomics analysis. + + Returns: + A dictionary containing execution details: + - command_executed: The command string that was run. + - stdout: Standard output from the command. + - stderr: Standard error from the command. + - output_files: A list of paths to generated output files, including + 'spot_predict_score.csv' and other key analysis outputs. + + Raises: + ValueError: If input paths are invalid, required files are missing, + or the pretrained model is not found. + RuntimeError: If the TiRank script execution fails or model copying fails. + """ + # Input validation + if not tirank_repo_root.is_dir(): + raise ValueError(f"TiRank repository root not found: {tirank_repo_root}") + if not data_input_dir.is_dir(): + raise ValueError(f"Input data directory not found: {data_input_dir}") + + # Ensure output directory exists + output_dir.mkdir(parents=True, exist_ok=True) + + script_path = tirank_repo_root / "Example" / "ST-Cox-CRC.py" + if not script_path.is_file(): + raise ValueError(f"TiRank example script not found: {script_path}. " + "Ensure 'tirank_repo_root' points to the correct repository clone " + "and contains the 'Example/ST-Cox-CRC.py' script.") + + # Handle pretrained model file as per documentation + model_target_dir = tirank_repo_root / "data" / "pretrainModel" + model_target_file = model_target_dir / "ctranspath.pth" + + if pretrained_model_file: + if not pretrained_model_file.is_file(): + raise ValueError(f"Pretrained model file not found: {pretrained_model_file}") + model_target_dir.mkdir(parents=True, exist_ok=True) + try: + # Copy the user-provided model to the expected location + shutil.copy(pretrained_model_file, model_target_file) + except Exception as e: + raise RuntimeError(f"Failed to copy pretrained model from {pretrained_model_file} " + f"to {model_target_file}: {e}") from e + elif not model_target_file.is_file(): + # If no model provided by user and it's not at the default location, raise an error + raise ValueError(f"Pretrained model 'ctranspath.pth' is required for Spatial Transcriptomics analysis " + f"but was not provided and not found at the default location: {model_target_file}. " + "Please provide 'pretrained_model_file' or ensure it's placed at " + f"'{model_target_dir.relative_to(tirank_repo_root)}/ctranspath.pth' within the TiRank repository.") + + command_executed = "" + stdout = "" + stderr = "" + output_files: List[Path] = [] + temp_script_path: Optional[Path] = None + + try: + # Create a temporary Python script to set dataPath and savePath + # and then execute the original script. + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.py') as temp_script_file: + temp_script_file.write(f""" +import sys +import os +from pathlib import Path + +# Set the dataPath and savePath variables as expected by the original script +dataPath = Path("{data_input_dir.resolve()}") +savePath = Path("{output_dir.resolve()}") + +# Add the directory containing the original script to sys.path +# This is important for any relative imports the original script might have. +sys.path.insert(0, str(Path("{script_path.parent.resolve()}"))) + +# Execute the original script's content in the current namespace. +# This makes dataPath and savePath available to it. +with open("{script_path.resolve()}", 'r') as f: + script_code = f.read() +exec(script_code, globals()) +""") + temp_script_path = Path(temp_script_file.name) + + # Execute the temporary script using the system's python interpreter + # The documentation states to run from the repo root. + cmd = ["python", str(temp_script_path)] + command_executed = " ".join(cmd) + + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + cwd=tirank_repo_root.resolve() # Run from repo root as per docs + ) + stdout = process.stdout + stderr = process.stderr + + # Identify expected output files based on the documentation's output structure + final_result_file = output_dir / "3_Analysis" / "spot_predict_score.csv" + if final_result_file.is_file(): + output_files.append(final_result_file) + + # Collect all files generated within the expected output subdirectories + for sub_dir_name in ["1_loaddata", "2_preprocessing", "3_Analysis"]: + current_sub_dir = output_dir / sub_dir_name + if current_sub_dir.is_dir(): + for f in current_sub_dir.rglob("*"): + if f.is_file(): + output_files.append(f) + + except subprocess.CalledProcessError as e: + stdout = e.stdout + stderr = e.stderr + raise RuntimeError( + f"TiRank ST survival analysis failed with exit code {e.returncode}.\n" + f"Command: {command_executed}\n" + f"Stdout: {stdout}\n" + f"Stderr: {stderr}" + ) from e + except Exception as e: + raise RuntimeError(f"An unexpected error occurred during execution: {e}") from e + finally: + # Clean up the temporary script + if temp_script_path and temp_script_path.is_file(): + temp_script_path.unlink() + # Note: The copied pretrained model is left in place as it might be + # expected for subsequent runs or user inspection. If strict cleanup + # is needed, additional logic would be required here. + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [str(f) for f in output_files], + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tirank/app/tirank_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tirank/app/tirank_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f4ee513edfb4aad978369c8e8070d125acf6ef2d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tirank/app/tirank_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_tirank/app/tirank_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_tirank' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tirank/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tirank/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..258e51889acff8c2fb75a4cb740ea129640c1f62 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tirank/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-tirank: + build: . + image: mcp-tirank:latest + container_name: mcp-tirank + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=tirank + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tirank/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tirank/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3b9fac993a0590ca8a47173cbc351fdba4418485 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tirank/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - tirank + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tirank/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tirank/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_tirank/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trimal/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trimal/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trimal/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trinity/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trinity/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..47e8b427a1a84c19f2b82d30eb3b92cbef0b652d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trinity/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install trinity via conda (e.g., from bioconda) +RUN conda install -c bioconda trinity -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/trinity_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/trinity_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/trinity_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trinity/app/__pycache__/trinity_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trinity/app/__pycache__/trinity_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..494e1dfb60144d06cdf2837528deb25027c6517c Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trinity/app/__pycache__/trinity_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trinity/app/trinity_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trinity/app/trinity_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6a35f1afb4af5712da8ad392f85b7d908f21f531 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trinity/app/trinity_server.py @@ -0,0 +1,283 @@ +from typing import Optional, List +import subprocess +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_trinity' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def run_trinity( + seq_type: str, + max_memory: str, + left: Optional[List[str]] = None, + right: Optional[List[str]] = None, + single: Optional[List[str]] = None, + cpu: int = 2, + ss_lib_type: Optional[str] = None, + output_dir: str = "trinity_out_dir", + trimmomatic: bool = False, + no_normalize_reads: bool = False, + full_cleanup: bool = False, + genome_guided_bam: Optional[str] = None, + genome_guided_max_intron: int = 10000, + min_contig_length: int = 200, + long_reads: Optional[str] = None, + jellyfish_memory: str = "2G", +): + """ + Assembles transcript sequences from Illumina RNA-Seq data using Trinity. + + Args: + seq_type: Type of reads ('fa' or 'fq'). + max_memory: Maximum memory for Trinity (e.g., '10G', '1000M'). + left: List of paths to left/forward reads (paired-end). + right: List of paths to right/reverse reads (paired-end). + single: List of paths to single-end reads. + cpu: Number of CPUs to use (default: 2). + ss_lib_type: Strand-specific library type (F, R, FR, RF). + output_dir: Directory to store output (default: 'trinity_out_dir'). + trimmomatic: Run Trimmomatic to quality trim reads. + no_normalize_reads: Skip in silico normalization of reads. + full_cleanup: Delete all intermediate files after assembly. + genome_guided_bam: Path to coordinate-sorted BAM file for genome-guided assembly. + genome_guided_max_intron: Maximum intron length for genome-guided mode (default: 10000). + min_contig_length: Minimum assembled contig length to report (default: 200). + long_reads: Path to error-corrected or long reads (e.g., PacBio). + jellyfish_memory: Max memory used by jellyfish (default: '2G'). + """ + # Input validation + if seq_type not in ["fa", "fq"]: + return {"error": "seq_type must be 'fa' or 'fq'"} + + if not (max_memory.endswith('G') or max_memory.endswith('M')): + return {"error": "max_memory must be in format like '10G' or '2000M'"} + + if genome_guided_bam: + bam_path = Path(genome_guided_bam) + if not bam_path.exists(): + return {"error": f"Genome-guided BAM file not found: {genome_guided_bam}"} + else: + if not single and not (left and right): + return {"error": "Must provide either 'single' reads or both 'left' and 'right' reads for de novo assembly."} + + # Build command + cmd = [ + "Trinity", + "--seqType", seq_type, + "--max_memory", max_memory, + "--CPU", str(cpu), + "--output", output_dir, + "--min_contig_length", str(min_contig_length), + "--jellyfish_memory", jellyfish_memory + ] + + # Handle paired-end reads + if left and right: + # Validate files + for f in left + right: + if not Path(f).exists(): + return {"error": f"Read file not found: {f}"} + cmd.extend(["--left", ",".join(left)]) + cmd.extend(["--right", ",".join(right)]) + + # Handle single-end reads + if single: + for f in single: + if not Path(f).exists(): + return {"error": f"Read file not found: {f}"} + cmd.extend(["--single", ",".join(single)]) + + # Optional flags + if ss_lib_type: + cmd.extend(["--SS_lib_type", ss_lib_type]) + + if trimmomatic: + cmd.append("--trimmomatic") + + if no_normalize_reads: + cmd.append("--no_normalize_reads") + + if full_cleanup: + cmd.append("--full_cleanup") + + if genome_guided_bam: + cmd.extend(["--genome_guided_bam", genome_guided_bam]) + cmd.extend(["--genome_guided_max_intron", str(genome_guided_max_intron)]) + + if long_reads: + if not Path(long_reads).exists(): + return {"error": f"Long reads file not found: {long_reads}"} + cmd.extend(["--long_reads", long_reads]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + # Trinity main output is usually Trinity.fasta in the output directory + output_fasta = Path(output_dir) / "Trinity.fasta" + output_files = [str(output_fasta)] if output_fasta.exists() else [] + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def get_trinity_stats( + input_fasta: str, +): + """ + Calculates assembly statistics (N50, etc.) for a Trinity fasta file using TrinityStats.pl. + + Args: + input_fasta: Path to the Trinity.fasta file. + """ + fasta_path = Path(input_fasta) + if not fasta_path.exists(): + return {"error": f"Input fasta file not found: {input_fasta}"} + + # TrinityStats.pl is usually in the Trinity installation's util directory + # Assuming it's in the PATH as TrinityStats.pl + cmd = ["TrinityStats.pl", input_fasta] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + 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 run_trinity_gene_splice_modeler( + trinity_fasta: str, + samples_file: str, + output_dir: str = "splice_modeler_out", + min_isoform_pct: float = 10.0, +): + """ + Runs the Trinity gene splice modeler to identify splice variants. + + Args: + trinity_fasta: Path to the Trinity.fasta file. + samples_file: Path to the samples description file. + output_dir: Directory for output files. + min_isoform_pct: Minimum percent of gene expression for an isoform (default: 10.0). + """ + if not Path(trinity_fasta).exists(): + return {"error": f"Fasta file not found: {trinity_fasta}"} + if not Path(samples_file).exists(): + return {"error": f"Samples file not found: {samples_file}"} + + cmd = [ + "Trinity_gene_splice_modeler.py", + "--trinity_fasta", trinity_fasta, + "--samples_file", samples_file, + "--out_dir", output_dir, + "--min_isoform_pct", str(min_isoform_pct) + ] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_dir": output_dir + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def run_trinity_abundance_estimation( + transcripts: str, + seq_type: str, + left: Optional[List[str]] = None, + right: Optional[List[str]] = None, + single: Optional[List[str]] = None, + est_method: str = "salmon", + aln_method: str = "bowtie2", + thread_count: int = 2, + output_dir: str = "abundance_out", +): + """ + Estimates transcript abundance using Salmon, Kallisto, or RSEM via Trinity's utility script. + + Args: + transcripts: Path to the transcripts fasta file (Trinity.fasta). + seq_type: Type of reads ('fa' or 'fq'). + left: List of paths to left/forward reads (paired-end). + right: List of paths to right/reverse reads (paired-end). + single: List of paths to single-end reads. + est_method: Abundance estimation method ('salmon', 'kallisto', 'RSEM'). + aln_method: Alignment method ('bowtie2', 'bowtie') if using RSEM. + thread_count: Number of threads to use. + output_dir: Directory for output. + """ + if not Path(transcripts).exists(): + return {"error": f"Transcripts file not found: {transcripts}"} + + if est_method not in ["salmon", "kallisto", "RSEM"]: + return {"error": "est_method must be 'salmon', 'kallisto', or 'RSEM'"} + + cmd = [ + "align_and_estimate_abundance.pl", + "--transcripts", transcripts, + "--seqType", seq_type, + "--est_method", est_method, + "--thread_count", str(thread_count), + "--output_dir", output_dir + ] + + if left and right: + cmd.extend(["--left", ",".join(left)]) + cmd.extend(["--right", ",".join(right)]) + elif single: + cmd.extend(["--single", ",".join(single)]) + else: + return {"error": "Must provide either paired-end (left/right) or single-end reads."} + + if est_method == "RSEM": + cmd.extend(["--aln_method", aln_method]) + cmd.append("--prep_reference") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_dir": output_dir + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trinity/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trinity/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..a330ab72da8e032b9d4f3834114465219d116c1d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trinity/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-trinity: + build: . + image: mcp-trinity:latest + container_name: mcp-trinity + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=trinity + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trinity/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trinity/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..102533a01d4bf30e5fa49c78c8defdf2eeca267e --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trinity/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - trinity + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trinity/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trinity/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_trinity/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-twobittofa/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-twobittofa/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f6bce29a056e3950fbfed381b2b60b53663b281b --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-twobittofa/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install ucsc-twobittofa via conda (e.g., from bioconda) +RUN conda install -c bioconda ucsc-twobittofa -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/ucsc-twobittofa_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/ucsc-twobittofa_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/ucsc-twobittofa_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-twobittofa/app/__pycache__/ucsc-twobittofa_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-twobittofa/app/__pycache__/ucsc-twobittofa_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..14c6738c6f5e3880cadb4debde246ad8cdf72e7f Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-twobittofa/app/__pycache__/ucsc-twobittofa_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-twobittofa/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-twobittofa/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-twobittofa/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-twobittofa/app/ucsc-twobittofa_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-twobittofa/app/ucsc-twobittofa_server.py new file mode 100644 index 0000000000000000000000000000000000000000..70fc449b5e133f33985eba56640d8fce157ccb13 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-twobittofa/app/ucsc-twobittofa_server.py @@ -0,0 +1,165 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +# Assume mcp is imported from a library, no need to import it here as per instructions. +# from mcp import tool + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_ucsc_twobittofa' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def twobittofa( + input_2bit_file: Path, + output_fasta_file: Path, + sequence_name: Optional[str] = None, + chromosome: Optional[str] = None, + start_coordinate: Optional[int] = None, + end_coordinate: Optional[int] = None, + hard_mask: bool = False, + soft_mask: bool = False, + reverse_complement: bool = False, + no_names: bool = False, + to_upper: bool = False, + to_lower: bool = False, + verbose_level: int = 0, +) -> Dict[str, Any]: + """ + Convert all or part of a .2bit file to FASTA format. + + This tool converts a UCSC .2bit sequence file into a FASTA file. + It supports extracting specific sequences or regions, and various + masking and case conversion options. + + Note: The exact command-line parameters for ucsc-twobittofa were not + available in the provided documentation. Parameters are inferred based + on common conventions for UCSC command-line tools and the tool's description. + + Args: + input_2bit_file: Path to the input .2bit file. + output_fasta_file: Path to the output FASTA file. + sequence_name: Optional. Extract a specific sequence by name. Cannot be + used with `chromosome`, `start_coordinate`, or `end_coordinate`. + chromosome: Optional. Extract a specific chromosome. Requires `start_coordinate` + and `end_coordinate` if provided. Cannot be used with `sequence_name`. + start_coordinate: Optional. Start coordinate (0-based) for region extraction. + Requires `chromosome` and `end_coordinate`. + end_coordinate: Optional. End coordinate (0-based, exclusive) for region extraction. + Requires `chromosome` and `start_coordinate`. + hard_mask: If True, mask N's in the output. + soft_mask: If True, mask lower-case letters in the output. Cannot be used with `hard_mask`. + reverse_complement: If True, output the reverse complement of the sequence. + no_names: If True, do not include sequence names in the output FASTA headers. + to_upper: If True, convert all output sequence to upper case. Cannot be used with `to_lower`. + to_lower: If True, convert all output sequence to lower case. Cannot be used with `to_upper`. + verbose_level: Set the verbosity level (0-3, where 0 is silent). + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + + Raises: + FileNotFoundError: If the input .2bit file does not exist. + ValueError: If invalid parameter combinations or values are provided. + subprocess.CalledProcessError: If the ucsc-twobittofa command fails. + """ + # --- Input Validation --- + if not input_2bit_file.is_file(): + raise FileNotFoundError(f"Input .2bit file not found: {input_2bit_file}") + + if output_fasta_file.suffix.lower() not in [".fa", ".fasta", ".fna"]: + raise ValueError(f"Output file '{output_fasta_file}' must have a FASTA extension (.fa, .fasta, .fna).") + + output_fasta_file.parent.mkdir(parents=True, exist_ok=True) + + # Region/Sequence selection validation + region_params_set = any(p is not None for p in [chromosome, start_coordinate, end_coordinate]) + if sequence_name and region_params_set: + raise ValueError("Cannot specify both 'sequence_name' and region parameters ('chromosome', 'start_coordinate', 'end_coordinate').") + + if chromosome: + if start_coordinate is None or end_coordinate is None: + raise ValueError("If 'chromosome' is specified, 'start_coordinate' and 'end_coordinate' must also be provided.") + if start_coordinate < 0: + raise ValueError("'start_coordinate' must be a non-negative integer.") + if end_coordinate <= start_coordinate: + raise ValueError("'end_coordinate' must be greater than 'start_coordinate'.") + elif (start_coordinate is not None or end_coordinate is not None): + raise ValueError("If 'start_coordinate' or 'end_coordinate' is specified, 'chromosome' must also be provided.") + + # Masking options validation + if hard_mask and soft_mask: + raise ValueError("Cannot specify both 'hard_mask' and 'soft_mask'.") + + # Case conversion options validation + if to_upper and to_lower: + raise ValueError("Cannot specify both 'to_upper' and 'to_lower'.") + + if not (0 <= verbose_level <= 3): + raise ValueError("Verbose level must be between 0 and 3.") + + # --- Construct Command --- + cmd = ["ucsc-twobittofa"] + + if sequence_name: + cmd.append(f"-seq={sequence_name}") + elif chromosome: + cmd.append(f"-chrom={chromosome}") + cmd.append(f"-start={start_coordinate}") + cmd.append(f"-end={end_coordinate}") + + if hard_mask: + cmd.append("-hardmask") + if soft_mask: + cmd.append("-softmask") + if reverse_complement: + cmd.append("-rev") + if no_names: + cmd.append("-noNames") + if to_upper: + cmd.append("-upper") + if to_lower: + cmd.append("-lower") + + if verbose_level > 0: + cmd.append(f"-verbose={verbose_level}") + + cmd.extend([str(input_2bit_file), str(output_fasta_file)]) + + command_executed = " ".join(cmd) + stdout = "" + stderr = "" + output_files: List[Path] = [] + + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + output_files.append(output_fasta_file) + + except FileNotFoundError: + stderr = f"Error: 'ucsc-twobittofa' command not found. Please ensure it is installed and in your PATH." + raise + except subprocess.CalledProcessError as e: + stdout = e.stdout + stderr = e.stderr + raise RuntimeError(f"Command failed with exit code {e.returncode}: {e.cmd}\nStdout: {stdout}\nStderr: {stderr}") from e + except Exception as e: + stderr = f"An unexpected error occurred: {e}" + raise + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-twobittofa/app/ucsc-twobittofa_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-twobittofa/app/ucsc-twobittofa_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..eb0f8e9df389ba90bb933dc9caba3c038f00d39d --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-twobittofa/app/ucsc-twobittofa_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ucsc-twobittofa/app/ucsc-twobittofa_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_ucsc_twobittofa' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-twobittofa/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-twobittofa/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..2611cca3c1f976f99a40cfceefbe9ae8b1a6c26c --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-twobittofa/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-ucsc-twobittofa: + build: . + image: mcp-ucsc-twobittofa:latest + container_name: mcp-ucsc-twobittofa + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=ucsc-twobittofa + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-twobittofa/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-twobittofa/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..676b7bfcaaa8362db3989567d60345a099d498f7 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-twobittofa/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - ucsc-twobittofa + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-twobittofa/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-twobittofa/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_ucsc-twobittofa/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_vsearch/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_vsearch/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_vsearch/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_zol/Dockerfile b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_zol/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..09bfbd83ebff7ba78ac19660c6716ce8e5d060e3 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_zol/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install zol via conda (e.g., from bioconda) +RUN conda install -c bioconda zol -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/zol_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/zol_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/zol_server.py"] + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_zol/app/__pycache__/zol_shim_server.cpython-311.pyc b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_zol/app/__pycache__/zol_shim_server.cpython-311.pyc new file mode 100644 index 0000000000000000000000000000000000000000..fd8febfe9a0d2dd3f933d36deef9d6b2a62ec4c6 Binary files /dev/null and b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_zol/app/__pycache__/zol_shim_server.cpython-311.pyc differ diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_zol/app/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_zol/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_zol/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_zol/app/zol_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_zol/app/zol_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b8918ef7a9cb89018116eb458206b5f0fbb8fc79 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_zol/app/zol_server.py @@ -0,0 +1,570 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any + +# Note: The 'mcp' import is omitted as per the instructions. + +def _run_zol_suite_command( + program: str, + args: List[str], + output_directory: Path, + input_files_to_validate: Optional[List[Path]] = None, +) -> Dict[str, Any]: + """ + Helper function to execute zol-suite commands. + + Args: + program: The zol-suite subcommand to run (e.g., "prepTG", "fai"). + args: A list of command-line arguments specific to the subcommand. + output_directory: The directory where output files will be written. + input_files_to_validate: An optional list of input file paths to validate existence. + + Returns: + A dictionary containing execution details (command, stdout, stderr, output_files, error status). + """ + if not output_directory.is_dir(): + output_directory.mkdir(parents=True, exist_ok=True) + + command = ["zol-suite", program] + args + + # Validate input files + if input_files_to_validate: + for f in input_files_to_validate: + if not f.is_file(): + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": f"Error: Input file not found: {f}", + "output_files": [], + "error": True, + "message": f"Input file not found: {f}", + } + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + cwd=output_directory, # Run in output directory to capture generated files + ) + stdout = process.stdout + stderr = process.stderr + + # List files created in the output_directory. + # This is a generic approach; specific tools might have known output patterns. + output_files = [str(f.resolve()) for f in output_directory.iterdir() if f.is_file()] + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + "error": False, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": True, + "message": f"Command failed with exit code {e.returncode}", + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: 'zol-suite' command not found. Is zol installed and in PATH?", + "output_files": [], + "error": True, + "message": "'zol-suite' command not found.", + } + + +from mcp.server.fastmcp import FastMCP + +SERVER_NAME = 'local_zol' +mcp = FastMCP(SERVER_NAME) + +@mcp.tool() +def prep_tg( + input_genomes: List[Path], + output_database_dir: Path, + reference_proteome: Optional[Path] = None, + cli_args: Optional[List[str]] = None, +) -> Dict[str, Any]: + """ + Prepare a database of target genomes for searches using fai. + + This tool processes and performs gene-calling or gene-mapping on an input set of genomes. + It can take in as input either FASTA files or GenBank files with CDS features. + If FASTA files are provided, it will by default use pyrodigal to make gene calls. + If genomes are eukaryotic and a reference proteome is provided, miniprot will be used + to perform gene mapping. + + Note: Detailed command-line parameters for 'prepTG' are not available in the provided + documentation. The 'cli_args' parameter allows passing additional, undocumented + arguments directly to the 'prepTG' subcommand. + """ + # Input validation + if not input_genomes: + return { + "command_executed": "zol-suite prepTG ...", + "stdout": "", + "stderr": "Error: At least one input genome file is required.", + "output_files": [], + "error": True, + "message": "At least one input genome file is required.", + } + for genome_path in input_genomes: + if not genome_path.is_file(): + return { + "command_executed": "zol-suite prepTG ...", + "stdout": "", + "stderr": f"Error: Input genome file not found: {genome_path}", + "output_files": [], + "error": True, + "message": f"Input genome file not found: {genome_path}", + } + if reference_proteome and not reference_proteome.is_file(): + return { + "command_executed": "zol-suite prepTG ...", + "stdout": "", + "stderr": f"Error: Reference proteome file not found: {reference_proteome}", + "output_files": [], + "error": True, + "message": f"Reference proteome file not found: {reference_proteome}", + } + + args = [] + for genome_path in input_genomes: + args.extend(["-g", str(genome_path)]) # Assuming -g for genome input + args.extend(["-o", str(output_database_dir)]) # Assuming -o for output directory + if reference_proteome: + args.extend(["--ref-proteome", str(reference_proteome)]) # Inferred flag + + if cli_args: + args.extend(cli_args) + + input_files_to_validate = input_genomes + if reference_proteome: + input_files_to_validate.append(reference_proteome) + + return _run_zol_suite_command("prepTG", args, output_database_dir, input_files_to_validate) + + +@mcp.tool() +def fai( + query_gene_cluster: Path, + target_database: Path, + output_directory: Path, + cli_args: Optional[List[str]] = None, +) -> Dict[str, Any]: + """ + Find additional instances of gene clusters in a genome database. + + This tool searches for homologous/orthologous instances of a query gene cluster + in a database of (meta-)genomes, leveraging DIAMOND alignment. It can assess + syntenic similarity, allow looser criteria for fragmented clusters, and filter + secondary neighborhoods. + + Note: Detailed command-line parameters for 'fai' are not available in the provided + documentation. The 'cli_args' parameter allows passing additional, undocumented + arguments directly to the 'fai' subcommand. + """ + # Input validation + if not query_gene_cluster.is_file(): + return { + "command_executed": "zol-suite fai ...", + "stdout": "", + "stderr": f"Error: Query gene cluster file not found: {query_gene_cluster}", + "output_files": [], + "error": True, + "message": f"Query gene cluster file not found: {query_gene_cluster}", + } + if not target_database.is_dir(): # Assuming target_database is a directory created by prepTG + return { + "command_executed": "zol-suite fai ...", + "stdout": "", + "stderr": f"Error: Target database directory not found: {target_database}", + "output_files": [], + "error": True, + "message": f"Target database directory not found: {target_database}", + } + + args = [ + "-q", str(query_gene_cluster), # Inferred flag for query + "-d", str(target_database), # Inferred flag for database + "-o", str(output_directory / "fai_results"), # Inferred output prefix/file + ] + if cli_args: + args.extend(cli_args) + + return _run_zol_suite_command("fai", args, output_directory, [query_gene_cluster]) + + +@mcp.tool() +def zol( + input_gene_clusters: Path, + output_directory: Path, + cli_args: Optional[List[str]] = None, +) -> Dict[str, Any]: + """ + Perform comparative gene cluster analysis. + + This tool creates table reports showing ortholog group conservation, annotation, + and evolutionary statistics for gene clusters of interest. It performs de novo + ortholog group inference and can filter incomplete gene cluster instances. + It also has options for dereplication using skani and re-inflation with CD-HIT. + + Note: Detailed command-line parameters for 'zol' are not available in the provided + documentation. The 'cli_args' parameter allows passing additional, undocumented + arguments directly to the 'zol' subcommand. + """ + # Input validation + if not input_gene_clusters.is_file(): + return { + "command_executed": "zol-suite zol ...", + "stdout": "", + "stderr": f"Error: Input gene clusters file not found: {input_gene_clusters}", + "output_files": [], + "error": True, + "message": f"Input gene clusters file not found: {input_gene_clusters}", + } + + args = [ + "-i", str(input_gene_clusters), # Inferred flag for input + "-o", str(output_directory / "zol_report"), # Inferred output prefix/file + ] + if cli_args: + args.extend(cli_args) + + return _run_zol_suite_command("zol", args, output_directory, [input_gene_clusters]) + + +@mcp.tool() +def cgc( + input_zol_results: Path, + output_directory: Path, + cli_args: Optional[List[str]] = None, +) -> Dict[str, Any]: + """ + Visualize zol results along a consensus gene cluster sequence. + + This tool generates publication-quality figures, producing a collapsed gene cluster + with bar plots for quantitative statistics computed in zol atop a consensus + gene cluster representation. + + Note: Detailed command-line parameters for 'cgc' are not available in the provided + documentation. The 'cli_args' parameter allows passing additional, undocumented + arguments directly to the 'cgc' subcommand. + """ + # Input validation + if not input_zol_results.is_file(): + return { + "command_executed": "zol-suite cgc ...", + "stdout": "", + "stderr": f"Error: Input zol results file not found: {input_zol_results}", + "output_files": [], + "error": True, + "message": f"Input zol results file not found: {input_zol_results}", + } + + args = [ + "-i", str(input_zol_results), # Inferred flag for input + "-o", str(output_directory / "cgc_figure"), # Inferred output prefix/file + ] + if cli_args: + args.extend(cli_args) + + return _run_zol_suite_command("cgc", args, output_directory, [input_zol_results]) + + +@mcp.tool() +def cgcg( + input_zol_results: Path, + output_directory: Path, + cli_args: Optional[List[str]] = None, +) -> Dict[str, Any]: + """ + Visualize zol results as a graphical network. + + This tool generates publication-quality figures, producing a network visual of + ortholog groups (nodes) where edges represent information on syntenic ordering. + + Note: Detailed command-line parameters for 'cgcg' are not available in the provided + documentation. The 'cli_args' parameter allows passing additional, undocumented + arguments directly to the 'cgcg' subcommand. + """ + # Input validation + if not input_zol_results.is_file(): + return { + "command_executed": "zol-suite cgcg ...", + "stdout": "", + "stderr": f"Error: Input zol results file not found: {input_zol_results}", + "output_files": [], + "error": True, + "message": f"Input zol results file not found: {input_zol_results}", + } + + args = [ + "-i", str(input_zol_results), # Inferred flag for input + "-o", str(output_directory / "cgcg_network"), # Inferred output prefix/file + ] + if cli_args: + args.extend(cli_args) + + return _run_zol_suite_command("cgcg", args, output_directory, [input_zol_results]) + + +@mcp.tool() +def abon( + input_genome: Path, + output_directory: Path, + cli_args: Optional[List[str]] = None, +) -> Dict[str, Any]: + """ + Automated analysis of conservation/novelty for a sample's biosynthetic gene clusters (BGCs). + + This tool allows users to check if BGCs from their favorite strain/genome are + conserved or novel relative to other genomes available from the isolate's + respective genus. + + Note: Detailed command-line parameters for 'abon' are not available in the provided + documentation. The 'cli_args' parameter allows passing additional, undocumented + arguments directly to the 'abon' subcommand. + """ + # Input validation + if not input_genome.is_file(): + return { + "command_executed": "zol-suite abon ...", + "stdout": "", + "stderr": f"Error: Input genome file not found: {input_genome}", + "output_files": [], + "error": True, + "message": f"Input genome file not found: {input_genome}", + } + + args = [ + "-g", str(input_genome), # Inferred flag for genome input + "-o", str(output_directory / "abon_results"), # Inferred output prefix/file + ] + if cli_args: + args.extend(cli_args) + + return _run_zol_suite_command("abon", args, output_directory, [input_genome]) + + +@mcp.tool() +def atpoc( + input_genome: Path, + output_directory: Path, + cli_args: Optional[List[str]] = None, +) -> Dict[str, Any]: + """ + Automated analysis of conservation/novelty for a sample's prophages. + + This tool allows users to check if temperate phages from their favorite strain/genome + are conserved or novel relative to other genomes available from the isolate's + respective genus. + + Note: Detailed command-line parameters for 'atpoc' are not available in the provided + documentation. The 'cli_args' parameter allows passing additional, undocumented + arguments directly to the 'atpoc' subcommand. + """ + # Input validation + if not input_genome.is_file(): + return { + "command_executed": "zol-suite atpoc ...", + "stdout": "", + "stderr": f"Error: Input genome file not found: {input_genome}", + "output_files": [], + "error": True, + "message": f"Input genome file not found: {input_genome}", + } + + args = [ + "-g", str(input_genome), # Inferred flag for genome input + "-o", str(output_directory / "atpoc_results"), # Inferred output prefix/file + ] + if cli_args: + args.extend(cli_args) + + return _run_zol_suite_command("atpoc", args, output_directory, [input_genome]) + + +@mcp.tool() +def apos( + input_genome: Path, + output_directory: Path, + cli_args: Optional[List[str]] = None, +) -> Dict[str, Any]: + """ + Automated analysis of conservation/novelty for a sample's plasmids. + + This tool allows users to check if plasmids from their favorite strain/genome + are conserved or novel relative to other genomes available from the isolate's + respective genus. + + Note: Detailed command-line parameters for 'apos' are not available in the provided + documentation. The 'cli_args' parameter allows passing additional, undocumented + arguments directly to the 'apos' subcommand. + """ + # Input validation + if not input_genome.is_file(): + return { + "command_executed": "zol-suite apos ...", + "stdout": "", + "stderr": f"Error: Input genome file not found: {input_genome}", + "output_files": [], + "error": True, + "message": f"Input genome file not found: {input_genome}", + } + + args = [ + "-g", str(input_genome), # Inferred flag for genome input + "-o", str(output_directory / "apos_results"), # Inferred output prefix/file + ] + if cli_args: + args.extend(cli_args) + + return _run_zol_suite_command("apos", args, output_directory, [input_genome]) + + +@mcp.tool() +def salt( + input_fai_results: Path, + output_directory: Path, + cli_args: Optional[List[str]] = None, +) -> Dict[str, Any]: + """ + Assess support for lateral/horizontal transfer of gene clusters (experimental). + + This tool reports statistics such as codon usage dissimilarity, presence of + plasmid/virus-associated proteins on the same scaffold, and distance from transposons + for gene cluster instances detected by fai. + + Note: Detailed command-line parameters for 'salt' are not available in the provided + documentation. The 'cli_args' parameter allows passing additional, undocumented + arguments directly to the 'salt' subcommand. + """ + # Input validation + if not input_fai_results.is_file(): + return { + "command_executed": "zol-suite salt ...", + "stdout": "", + "stderr": f"Error: Input fai results file not found: {input_fai_results}", + "output_files": [], + "error": True, + "message": f"Input fai results file not found: {input_fai_results}", + } + + args = [ + "-i", str(input_fai_results), # Inferred flag for input + "-o", str(output_directory / "salt_report"), # Inferred output prefix/file + ] + if cli_args: + args.extend(cli_args) + + return _run_zol_suite_command("salt", args, output_directory, [input_fai_results]) + + +@mcp.tool() +def regex( + input_genome: Path, + scaffold_id: str, + start_coordinate: int, + end_coordinate: int, + output_directory: Path, + cli_args: Optional[List[str]] = None, +) -> Dict[str, Any]: + """ + Extract a genomic region (as GenBank) from a genome file (FASTA or GenBank) + based on scaffold and coordinate inputs (experimental). + + Note: Detailed command-line parameters for 'regex' are not available in the provided + documentation. The 'cli_args' parameter allows passing additional, undocumented + arguments directly to the 'regex' subcommand. + """ + # Input validation + if not input_genome.is_file(): + return { + "command_executed": "zol-suite regex ...", + "stdout": "", + "stderr": f"Error: Input genome file not found: {input_genome}", + "output_files": [], + "error": True, + "message": f"Input genome file not found: {input_genome}", + } + if not scaffold_id: + return { + "command_executed": "zol-suite regex ...", + "stdout": "", + "stderr": "Error: Scaffold ID cannot be empty.", + "output_files": [], + "error": True, + "message": "Scaffold ID cannot be empty.", + } + if not (0 <= start_coordinate <= end_coordinate): + return { + "command_executed": "zol-suite regex ...", + "stdout": "", + "stderr": "Error: Invalid coordinates. Start must be <= End and both non-negative.", + "output_files": [], + "error": True, + "message": "Invalid coordinates. Start must be <= End and both non-negative.", + } + + args = [ + "-g", str(input_genome), + "-s", scaffold_id, + "-t", f"{start_coordinate}-{end_coordinate}", # Inferred format for coordinates + "-o", str(output_directory / f"{scaffold_id}_{start_coordinate}-{end_coordinate}.gbk"), # Inferred output file + ] + if cli_args: + args.extend(cli_args) + + return _run_zol_suite_command("regex", args, output_directory, [input_genome]) + + +@mcp.tool() +def zol_scape( + bigscape_results_directory: Path, + output_directory: Path, + cli_args: Optional[List[str]] = None, +) -> Dict[str, Any]: + """ + Run zol analysis on BiG-SCAPE results. + + This tool is a simple wrapper to run zol for all Gene Cluster Families (GCFs) + determined by BiG-SCAPE, complementing CORASON visual results. + + Note: Detailed command-line parameters for 'zol-scape' are not available in the provided + documentation. The 'cli_args' parameter allows passing additional, undocumented + arguments directly to the 'zol-scape' subcommand. + """ + # Input validation + if not bigscape_results_directory.is_dir(): + return { + "command_executed": "zol-suite zol-scape ...", + "stdout": "", + "stderr": f"Error: BiG-SCAPE results directory not found: {bigscape_results_directory}", + "output_files": [], + "error": True, + "message": f"BiG-SCAPE results directory not found: {bigscape_results_directory}", + } + + args = [ + "-i", str(bigscape_results_directory), # Inferred flag for input directory + "-o", str(output_directory / "zol_scape_results"), # Inferred output prefix/directory + ] + if cli_args: + args.extend(cli_args) + + # No specific input files to validate, as it's a directory. + return _run_zol_suite_command("zol-scape", args, output_directory) + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_zol/app/zol_shim_server.py b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_zol/app/zol_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f4833fe930446561e6c21c68dff756073ed135b8 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_zol/app/zol_shim_server.py @@ -0,0 +1,55 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_zol/app/zol_server.py') +LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name) +SERVER_NAME = 'biosci_zol' + + +class _ShimMCP: + @staticmethod + def tool(*args, **kwargs): + if args and callable(args[0]) and len(args) == 1 and not kwargs: + return args[0] + def _decorator(fn): + return fn + return _decorator + + +def _resolve_source_server(): + if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name: + return LOCAL_SERVER + return SOURCE_SERVER + + +def _load_functions(): + source_server = _resolve_source_server() + code = source_server.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(source_server)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(source_server), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_zol/docker-compose.yml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_zol/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..01651afaf40422b6dd079ac2442f64712c117050 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_zol/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-zol: + build: . + image: mcp-zol:latest + container_name: mcp-zol + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=zol + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_zol/environment.yaml b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_zol/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6608f192d97acabe5d2cf7b27a6c291b8762c816 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_zol/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - zol + - python=3.10 + \ No newline at end of file diff --git a/Biomanus/biomni_web/backend/data/mcp_generated/mcp_zol/requirements.txt b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_zol/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/Biomanus/biomni_web/backend/data/mcp_generated/mcp_zol/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp