diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bbmap/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bbmap/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..8bb1d6c1e02e727e07ab7705f2f875415e352426 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bbmap/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bbmap: + build: . + image: mcp-bbmap:latest + container_name: mcp-bbmap + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bbmap + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bbmap/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bbmap/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4dd8a76883b5fb6460bb4414d93156ecc7e3149a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bbmap/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bbmap + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bbmap/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bbmap/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bbmap/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bcftools/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bcftools/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..075aef4a34315764c86518d4f68189f8f3484117 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bcftools/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bcftools via conda (e.g., from bioconda) +RUN conda install -c bioconda bcftools -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY bcftools_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bcftools_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bcftools_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bcftools/app/bcftools_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bcftools/app/bcftools_server.py new file mode 100644 index 0000000000000000000000000000000000000000..90645ca623fb8d0cdb8515b71a7da4233efc7da7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bcftools/app/bcftools_server.py @@ -0,0 +1,858 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# Note: The @mcp.tool decorator is not defined here. +# It is assumed to be provided by the Model Context Protocol (MCP) framework. +# This code is designed to be used within that framework. + +# Helper function to handle subprocess execution and error reporting +def _run_bcftools_command(cmd: List[str], output_file: Optional[Path] = None): + """ + A helper function to execute a bcftools command, handle errors, + and return a structured dictionary. + """ + command_str = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + output_files = [str(output_file)] if output_file and output_file.exists() else [] + + # For commands that create index files automatically + if output_file and str(output_file).endswith((".bcf", ".vcf.gz")): + index_extensions = [".csi", ".tbi"] + for ext in index_extensions: + index_file = Path(str(output_file) + ext) + if index_file.exists(): + output_files.append(str(index_file)) + + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + "return_code": 0, + } + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: 'bcftools' command not found. Please ensure it is in your PATH.", + "output_files": [], + "return_code": 1, + "error": "FileNotFoundError" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "return_code": e.returncode, + "error": "CalledProcessError" + } + +@mcp.tool() +def bcftools_annotate( + input_file: Path, + annotations: Optional[Path] = None, + columns: Optional[str] = None, + header_lines: Optional[Path] = None, + output: Optional[Path] = None, + output_type: str = "v", + remove: Optional[str] = None, + set_id: Optional[str] = None, + regions: Optional[str] = None, + regions_file: Optional[Path] = None, + targets: Optional[str] = None, + targets_file: Optional[Path] = None, + include: Optional[str] = None, + exclude: Optional[str] = None, + samples: Optional[str] = None, + samples_file: Optional[Path] = None, + threads: int = 1, + rename_chrs: Optional[Path] = None, + no_version: bool = False, + single_overlaps: bool = False, + mark_sites: Optional[str] = None, +): + """ + Annotate VCF/BCF files with information from other files. + """ + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if annotations and not annotations.exists(): + raise FileNotFoundError(f"Annotations file not found: {annotations}") + if header_lines and not header_lines.exists(): + raise FileNotFoundError(f"Header lines file not found: {header_lines}") + if output_type not in ["b", "u", "z", "v"]: + raise ValueError("output_type must be one of 'b', 'u', 'z', 'v'.") + + cmd = ["bcftools", "annotate", str(input_file)] + + if annotations: + cmd.extend(["-a", str(annotations)]) + if columns: + cmd.extend(["-c", columns]) + if header_lines: + cmd.extend(["-h", str(header_lines)]) + if output: + cmd.extend(["-o", str(output)]) + if output_type: + cmd.extend(["-O", output_type]) + if remove: + cmd.extend(["-x", remove]) + if set_id: + cmd.extend(["--set-id", set_id]) + if regions: + cmd.extend(["-r", regions]) + if regions_file: + cmd.extend(["-R", str(regions_file)]) + if targets: + cmd.extend(["-t", targets]) + if targets_file: + cmd.extend(["-T", str(targets_file)]) + if include: + cmd.extend(["-i", include]) + if exclude: + cmd.extend(["-e", exclude]) + if samples: + cmd.extend(["-s", samples]) + if samples_file: + cmd.extend(["-S", str(samples_file)]) + if threads > 1: + cmd.extend(["--threads", str(threads)]) + if rename_chrs: + cmd.extend(["--rename-chrs", str(rename_chrs)]) + if no_version: + cmd.append("--no-version") + if single_overlaps: + cmd.append("--single-overlaps") + if mark_sites: + cmd.extend(["--mark-sites", mark_sites]) + + return _run_bcftools_command(cmd, output) + +@mcp.tool() +def bcftools_call( + input_file: Path, + output: Optional[Path] = None, + output_type: str = "v", + ploidy: Optional[str] = None, + ploidy_file: Optional[Path] = None, + call_method: str = "multiallelic", + constrain_alleles: bool = False, + group_samples: Optional[str] = None, + samples: Optional[str] = None, + samples_file: Optional[Path] = None, + format_fields: Optional[str] = None, + keep_alts: bool = False, + keep_masked_ref: bool = False, + skip_variants: bool = False, + threads: int = 1, +): + """ + Call genotypes from likelihoods. + """ + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if output_type not in ["b", "u", "z", "v"]: + raise ValueError("output_type must be one of 'b', 'u', 'z', 'v'.") + if call_method not in ["consensus", "multiallelic"]: + raise ValueError("call_method must be 'consensus' or 'multiallelic'.") + + cmd = ["bcftools", "call", str(input_file)] + + if output: + cmd.extend(["-o", str(output)]) + if output_type: + cmd.extend(["-O", output_type]) + if ploidy: + cmd.extend(["-p", ploidy]) + if ploidy_file: + cmd.extend(["-P", str(ploidy_file)]) + if call_method == "consensus": + cmd.append("-c") + else: # multiallelic is default, but -m is explicit + cmd.append("-m") + if constrain_alleles: + cmd.append("-C alleles") + if group_samples: + cmd.extend(["-G", group_samples]) + if samples: + cmd.extend(["-s", samples]) + if samples_file: + cmd.extend(["-S", str(samples_file)]) + if format_fields: + cmd.extend(["-f", format_fields]) + if keep_alts: + cmd.append("-A") + if keep_masked_ref: + cmd.append("-M") + if skip_variants: + cmd.append("-V") + if threads > 1: + cmd.extend(["--threads", str(threads)]) + + return _run_bcftools_command(cmd, output) + +@mcp.tool() +def bcftools_concat( + input_files: List[Path], + output: Optional[Path] = None, + output_type: str = "v", + allow_overlaps: bool = False, + remove_duplicates: bool = False, + naive: bool = False, + threads: int = 1, +): + """ + Concatenate VCF/BCF files from non-overlapping regions. + """ + 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 output_type not in ["b", "u", "z", "v"]: + raise ValueError("output_type must be one of 'b', 'u', 'z', 'v'.") + + cmd = ["bcftools", "concat"] + + if allow_overlaps: + cmd.append("-a") + if remove_duplicates: + cmd.append("-d") + if naive: + cmd.append("-n") + if output: + cmd.extend(["-o", str(output)]) + if output_type: + cmd.extend(["-O", output_type]) + if threads > 1: + cmd.extend(["--threads", str(threads)]) + + cmd.extend([str(f) for f in input_files]) + + return _run_bcftools_command(cmd, output) + +@mcp.tool() +def bcftools_consensus( + input_file: Path, + fasta_ref: Path, + output: Optional[Path] = None, + chain: Optional[Path] = None, + haplotype: Optional[str] = None, + iupac_codes: bool = False, + mark_del: Optional[str] = None, + mark_ins: Optional[str] = None, + mark_snv: Optional[str] = None, + missing: Optional[str] = None, + sample: Optional[str] = None, + include: Optional[str] = None, + exclude: Optional[str] = None, +): + """ + Create a consensus sequence by applying VCF variants to a reference FASTA file. + """ + if not input_file.exists(): + raise FileNotFoundError(f"Input VCF/BCF file not found: {input_file}") + if not fasta_ref.exists(): + raise FileNotFoundError(f"Reference FASTA file not found: {fasta_ref}") + if haplotype and haplotype not in ["1", "2", "R", "A", "IUPAC", "all"]: + raise ValueError("haplotype must be one of '1', '2', 'R', 'A', 'IUPAC', 'all'.") + + cmd = ["bcftools", "consensus", str(input_file)] + cmd.extend(["-f", str(fasta_ref)]) + + if output: + cmd.extend(["-o", str(output)]) + if chain: + cmd.extend(["-c", str(chain)]) + if haplotype: + cmd.extend(["-H", haplotype]) + if iupac_codes: + cmd.append("-i") + if mark_del: + cmd.extend(["--mark-del", mark_del]) + if mark_ins: + cmd.extend(["--mark-ins", mark_ins]) + if mark_snv: + cmd.extend(["--mark-snv", mark_snv]) + if missing: + cmd.extend(["-m", missing]) + if sample: + cmd.extend(["-s", sample]) + if include: + cmd.extend(["--include", include]) + if exclude: + cmd.extend(["--exclude", exclude]) + + return _run_bcftools_command(cmd, output) + +@mcp.tool() +def bcftools_filter( + input_file: Path, + output: Optional[Path] = None, + output_type: str = "v", + include: Optional[str] = None, + exclude: Optional[str] = None, + soft_filter: Optional[str] = None, + set_gt: Optional[str] = None, + mode: str = "+", + threads: int = 1, +): + """ + Apply filters to VCF/BCF files. + """ + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if output_type not in ["b", "u", "z", "v"]: + raise ValueError("output_type must be one of 'b', 'u', 'z', 'v'.") + if mode not in ["+", "x", "X"]: + raise ValueError("mode must be one of '+', 'x', 'X'.") + + cmd = ["bcftools", "filter", str(input_file)] + + if output: + cmd.extend(["-o", str(output)]) + if output_type: + cmd.extend(["-O", output_type]) + if include: + cmd.extend(["-i", include]) + if exclude: + cmd.extend(["-e", exclude]) + if soft_filter: + cmd.extend(["-s", soft_filter]) + if set_gt: + cmd.extend(["-S", set_gt]) + if mode != "+": + cmd.extend(["-m", mode]) + if threads > 1: + cmd.extend(["--threads", str(threads)]) + + return _run_bcftools_command(cmd, output) + +@mcp.tool() +def bcftools_index( + input_file: Path, + force: bool = False, + stats: bool = False, + threads: int = 1, + csi: bool = False, + tbi: bool = False, + min_csi_shift: int = 14, +): + """ + Index VCF/BCF files for fast random access. + """ + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if csi and tbi: + raise ValueError("Cannot specify both --csi (-c) and --tbi (-t).") + + cmd = ["bcftools", "index"] + + if force: + cmd.append("-f") + if stats: + cmd.append("-n") + if threads > 1: + cmd.extend(["--threads", str(threads)]) + if csi: + cmd.append("-c") + if tbi: + cmd.append("-t") + if csi and min_csi_shift != 14: + cmd.extend(["-m", str(min_csi_shift)]) + + cmd.append(str(input_file)) + + # The output file is the index file itself + output_idx_file = None + if csi: + output_idx_file = Path(str(input_file) + ".csi") + else: # default is tbi for vcf.gz, csi for bcf + if str(input_file).endswith(".bcf"): + output_idx_file = Path(str(input_file) + ".csi") + else: + output_idx_file = Path(str(input_file) + ".tbi") + + return _run_bcftools_command(cmd, output_idx_file) + +@mcp.tool() +def bcftools_isec( + input_files: List[Path], + output_dir: Path, + output_type: str = "v", + complement: bool = False, + collapse: Optional[str] = None, + exclude: Optional[str] = None, + include: Optional[str] = None, + n_sites: Optional[str] = None, + regions: Optional[str] = None, + regions_file: Optional[Path] = None, + targets: Optional[str] = None, + targets_file: Optional[Path] = None, + threads: int = 1, +): + """ + Create intersections, unions, and complements of VCF/BCF files. + """ + if len(input_files) < 2: + raise ValueError("At least two input files must be provided for isec.") + for f in input_files: + if not f.exists(): + raise FileNotFoundError(f"Input file not found: {f}") + if output_type not in ["b", "u", "z", "v"]: + raise ValueError("output_type must be one of 'b', 'u', 'z', 'v'.") + if collapse and collapse not in ["none", "all", "snps", "indels", "both", "any"]: + raise ValueError("Invalid value for collapse.") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = ["bcftools", "isec"] + cmd.extend(["-p", str(output_dir)]) + cmd.extend(["-O", output_type]) + + if complement: + cmd.append("-c") + if collapse: + cmd.extend(["--collapse", collapse]) + if exclude: + cmd.extend(["-e", exclude]) + if include: + cmd.extend(["-i", include]) + if n_sites: + cmd.extend(["-n", n_sites]) + if regions: + cmd.extend(["-r", regions]) + if regions_file: + cmd.extend(["-R", str(regions_file)]) + if targets: + cmd.extend(["-t", targets]) + if targets_file: + cmd.extend(["-T", str(targets_file)]) + if threads > 1: + cmd.extend(["--threads", str(threads)]) + + cmd.extend([str(f) for f in input_files]) + + # isec doesn't have a single output file, it creates a directory + # We will return the directory path in a structured way if needed, + # but for now, we'll rely on the user knowing the output is a directory. + # The _run_bcftools_command helper won't find a single output file. + result = _run_bcftools_command(cmd) + + # Manually list created files + if result["return_code"] == 0: + created_files = [str(p) for p in output_dir.glob('*')] + result["output_files"] = created_files + + return result + +@mcp.tool() +def bcftools_merge( + input_files: List[Path], + output: Optional[Path] = None, + output_type: str = "v", + info_rules: Optional[str] = None, + merge_logic: Optional[str] = None, + threads: int = 1, +): + """ + Merge multiple VCF/BCF files from different samples into a single file. + """ + 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 output_type not in ["b", "u", "z", "v"]: + raise ValueError("output_type must be one of 'b', 'u', 'z', 'v'.") + + cmd = ["bcftools", "merge"] + + if output: + cmd.extend(["-o", str(output)]) + if output_type: + cmd.extend(["-O", output_type]) + if info_rules: + cmd.extend(["--info-rules", info_rules]) + if merge_logic: + cmd.extend(["-m", merge_logic]) + if threads > 1: + cmd.extend(["--threads", str(threads)]) + + cmd.extend([str(f) for f in input_files]) + + return _run_bcftools_command(cmd, output) + +@mcp.tool() +def bcftools_mpileup( + input_bams: List[Path], + fasta_ref: Path, + output: Optional[Path] = None, + output_type: str = "v", + regions: Optional[str] = None, + regions_file: Optional[Path] = None, + annotate: Optional[str] = None, + max_depth: int = 250, + min_base_quality: int = 13, + min_mapping_quality: int = 0, + adjust_mq: int = 50, + no_baq: bool = False, + threads: int = 1, +): + """ + Generate VCF/BCF from alignment files (BAM/CRAM). + """ + if not input_bams: + raise ValueError("At least one input BAM/CRAM file must be provided.") + for f in input_bams: + if not f.exists(): + raise FileNotFoundError(f"Input alignment file not found: {f}") + if not fasta_ref.exists(): + raise FileNotFoundError(f"Reference FASTA file not found: {fasta_ref}") + if output_type not in ["b", "u", "z", "v"]: + raise ValueError("output_type must be one of 'b', 'u', 'z', 'v'.") + + cmd = ["bcftools", "mpileup"] + cmd.extend(["-f", str(fasta_ref)]) + + if output: + cmd.extend(["-o", str(output)]) + if output_type: + cmd.extend(["-O", output_type]) + if regions: + cmd.extend(["-r", regions]) + if regions_file: + cmd.extend(["-R", str(regions_file)]) + if annotate: + cmd.extend(["-a", annotate]) + if max_depth != 250: + cmd.extend(["-d", str(max_depth)]) + if min_base_quality != 13: + cmd.extend(["-q", str(min_base_quality)]) + if min_mapping_quality != 0: + cmd.extend(["-Q", str(min_mapping_quality)]) + if adjust_mq != 50: + cmd.extend(["-C", str(adjust_mq)]) + if no_baq: + cmd.append("-B") + if threads > 1: + cmd.extend(["--threads", str(threads)]) + + cmd.extend([str(f) for f in input_bams]) + + return _run_bcftools_command(cmd, output) + +@mcp.tool() +def bcftools_norm( + input_file: Path, + fasta_ref: Path, + output: Optional[Path] = None, + output_type: str = "v", + check_ref: str = "w", + multiallelics: Optional[str] = None, + atomize: bool = False, + rm_dup: Optional[str] = None, + threads: int = 1, +): + """ + Left-align and normalize indels, check REF, split multiallelic sites. + """ + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if not fasta_ref.exists(): + raise FileNotFoundError(f"Reference FASTA file not found: {fasta_ref}") + if output_type not in ["b", "u", "z", "v"]: + raise ValueError("output_type must be one of 'b', 'u', 'z', 'v'.") + if check_ref not in ["w", "e", "x", "s"]: + raise ValueError("check_ref must be one of 'w', 'e', 'x', 's'.") + + cmd = ["bcftools", "norm", str(input_file)] + cmd.extend(["-f", str(fasta_ref)]) + + if output: + cmd.extend(["-o", str(output)]) + if output_type: + cmd.extend(["-O", output_type]) + if check_ref != "w": + cmd.extend(["-c", check_ref]) + if multiallelics: + cmd.extend(["-m", multiallelics]) + if atomize: + cmd.append("-a") + if rm_dup: + cmd.extend(["-d", rm_dup]) + if threads > 1: + cmd.extend(["--threads", str(threads)]) + + return _run_bcftools_command(cmd, output) + +@mcp.tool() +def bcftools_query( + input_file: Path, + format_string: str, + output: Optional[Path] = None, + include: Optional[str] = None, + exclude: Optional[str] = None, + regions: Optional[str] = None, + regions_file: Optional[Path] = None, + samples: Optional[str] = None, + samples_file: Optional[Path] = None, + list_samples: bool = False, +): + """ + Extracts fields from VCF/BCF files and prints them in a user-defined format. + """ + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + cmd = ["bcftools", "query", str(input_file)] + + if list_samples: + cmd.append("-l") + else: + cmd.extend(["-f", format_string]) + + if output: + cmd.extend(["-o", str(output)]) + if include: + cmd.extend(["-i", include]) + if exclude: + cmd.extend(["-e", exclude]) + if regions: + cmd.extend(["-r", regions]) + if regions_file: + cmd.extend(["-R", str(regions_file)]) + if samples: + cmd.extend(["-s", samples]) + if samples_file: + cmd.extend(["-S", str(samples_file)]) + + return _run_bcftools_command(cmd, output) + +@mcp.tool() +def bcftools_reheader( + input_file: Path, + header: Optional[Path] = None, + samples: Optional[Path] = None, + output: Optional[Path] = None, + output_type: str = "v", +): + """ + Modify VCF/BCF header, e.g., rename samples. + """ + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if header and not header.exists(): + raise FileNotFoundError(f"Header file not found: {header}") + if samples and not samples.exists(): + raise FileNotFoundError(f"Samples file not found: {samples}") + if not header and not samples: + raise ValueError("Either 'header' or 'samples' file must be provided.") + if output_type not in ["b", "u", "z", "v"]: + raise ValueError("output_type must be one of 'b', 'u', 'z', 'v'.") + + cmd = ["bcftools", "reheader"] + + if header: + cmd.extend(["-h", str(header)]) + if samples: + cmd.extend(["-s", str(samples)]) + if output: + cmd.extend(["-o", str(output)]) + + cmd.append(str(input_file)) + + # Reheader does not support -O, output type is inferred from extension + return _run_bcftools_command(cmd, output) + +@mcp.tool() +def bcftools_sort( + input_file: Path, + output: Optional[Path] = None, + output_type: str = "v", + max_mem: str = "768M", + temp_dir: Optional[Path] = None, +): + """ + Sort VCF/BCF file by chromosome and position. + """ + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if output_type not in ["b", "u", "z", "v"]: + raise ValueError("output_type must be one of 'b', 'u', 'z', 'v'.") + + cmd = ["bcftools", "sort", str(input_file)] + + if output: + cmd.extend(["-o", str(output)]) + if output_type: + cmd.extend(["-O", output_type]) + if max_mem: + cmd.extend(["-m", max_mem]) + if temp_dir: + temp_dir.mkdir(exist_ok=True, parents=True) + cmd.extend(["-T", str(temp_dir)]) + + return _run_bcftools_command(cmd, output) + +@mcp.tool() +def bcftools_stats( + input_files: List[Path], + fasta_ref: Optional[Path] = None, + output_dir: Optional[Path] = None, + regions: Optional[str] = None, + regions_file: Optional[Path] = None, + samples: Optional[str] = None, + samples_file: Optional[Path] = None, + threads: int = 1, +): + """ + Produce VCF/BCF stats, create plots with plot-vcfstats. + """ + 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 fasta_ref and not fasta_ref.exists(): + raise FileNotFoundError(f"Reference FASTA file not found: {fasta_ref}") + + cmd = ["bcftools", "stats"] + + if fasta_ref: + cmd.extend(["-f", str(fasta_ref)]) + if regions: + cmd.extend(["-r", regions]) + if regions_file: + cmd.extend(["-R", str(regions_file)]) + if samples: + cmd.extend(["-s", samples]) + if samples_file: + cmd.extend(["-S", str(samples_file)]) + if threads > 1: + cmd.extend(["--threads", str(threads)]) + + cmd.extend([str(f) for f in input_files]) + + # stats command outputs to stdout by default. + # If output_dir is provided, we redirect stdout to a file. + output_file = None + if output_dir: + output_dir.mkdir(exist_ok=True, parents=True) + output_file = output_dir / "stats.txt" + with open(output_file, "w") as f_out: + command_str = " ".join(cmd) + try: + result = subprocess.run( + cmd, + stdout=f_out, + stderr=subprocess.PIPE, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": f"Stats written to {output_file}", + "stderr": result.stderr, + "output_files": [str(output_file)], + "return_code": 0, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout or "", + "stderr": e.stderr, + "output_files": [], + "return_code": e.returncode, + "error": "CalledProcessError" + } + else: + # No output file, capture stdout directly + return _run_bcftools_command(cmd) + +@mcp.tool() +def bcftools_view( + input_file: Path, + output: Optional[Path] = None, + output_type: str = "v", + header_only: bool = False, + no_header: bool = False, + drop_genotypes: bool = False, + trim_alt_alleles: bool = False, + min_alleles: Optional[int] = None, + max_alleles: Optional[int] = None, + min_ac: Optional[int] = None, + max_ac: Optional[int] = None, + min_af: Optional[float] = None, + max_af: Optional[float] = None, + types: Optional[str] = None, + include: Optional[str] = None, + exclude: Optional[str] = None, + regions: Optional[str] = None, + regions_file: Optional[Path] = None, + samples: Optional[str] = None, + samples_file: Optional[Path] = None, + threads: int = 1, +): + """ + Subset, filter, and convert VCF and BCF files. + """ + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if output_type not in ["b", "u", "z", "v"]: + raise ValueError("output_type must be one of 'b', 'u', 'z', 'v'.") + + cmd = ["bcftools", "view", str(input_file)] + + if output: + cmd.extend(["-o", str(output)]) + if output_type: + cmd.extend(["-O", output_type]) + if header_only: + cmd.append("-h") + if no_header: + cmd.append("-H") + if drop_genotypes: + cmd.append("-G") + if trim_alt_alleles: + cmd.append("-a") + if min_alleles is not None: + cmd.extend(["-m", str(min_alleles)]) + if max_alleles is not None: + cmd.extend(["-M", str(max_alleles)]) + if min_ac is not None: + cmd.extend(["-c", str(min_ac)]) + if max_ac is not None: + cmd.extend(["-C", str(max_ac)]) + if min_af is not None: + cmd.extend(["-q", str(min_af)]) + if max_af is not None: + cmd.extend(["-Q", str(max_af)]) + if types: + cmd.extend(["-v", types]) + if include: + cmd.extend(["-i", include]) + if exclude: + cmd.extend(["-e", exclude]) + if regions: + cmd.extend(["-r", regions]) + if regions_file: + cmd.extend(["-R", str(regions_file)]) + if samples: + cmd.extend(["-s", samples]) + if samples_file: + cmd.extend(["-S", str(samples_file)]) + if threads > 1: + cmd.extend(["--threads", str(threads)]) + + return _run_bcftools_command(cmd, output) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bcftools/app/bcftools_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bcftools/app/bcftools_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..524cd0a2aaba344aa7af43bbf7efda3c34265972 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bcftools/app/bcftools_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bcftools/app/bcftools_server.py') +SERVER_NAME = 'biosci_bcftools' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bcftools/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bcftools/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b6d4e0018c2bd5952a61daa862c93500125d3415 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bcftools/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bcftools: + build: . + image: mcp-bcftools:latest + container_name: mcp-bcftools + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bcftools + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bcftools/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bcftools/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..047c9fb057f47426cf0d379551d816ade5cd1fcd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bcftools/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bcftools + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bcftools/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bcftools/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bcftools/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..565ae50155b78f1d8b26241027d43a56a2b50f5a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bedops via conda (e.g., from bioconda) +RUN conda install -c bioconda bedops -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bedops_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bedops_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bedops_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/app/bedops_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/app/bedops_server.py new file mode 100644 index 0000000000000000000000000000000000000000..83f7d8dfa5ad2bb88469adccd27792cee19213de --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/app/bedops_server.py @@ -0,0 +1,819 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# MCP decorator is commented out as per instructions +# import mcp + +@mcp.tool() +def bedops_complement( + files: List[Path], + chop_to_limits: bool = False, + chrom: Optional[str] = None, + ec: bool = False, + header: bool = False, + range_str: Optional[str] = None, + output_file: Optional[Path] = None, +) -> dict: + """ + Computes the complement of one or more BED files. + + This corresponds to the `bedops -c` or `bedops --complement` operation. + It finds the regions within chromosome boundaries that are not covered by + any intervals in the input file(s). + + Args: + files: A list of one or more input BED/Starch files. Must be sorted. + chop_to_limits: If True, chop complementary regions to chromosome limits + defined by the first input file (-L flag). + chrom: Process data for the given chromosome only. + ec: Error check input files (slower). + header: Accept headers (VCF, GFF, SAM, BED, WIG) in any input file. + range_str: Pad coordinates. Use 'L:R' format (e.g., '-10:20') or a + single value 'S' for symmetric padding (e.g., '100'). + output_file: Optional path to save the output. If not provided, + output is returned as a string in the result dictionary. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a + list of output files generated. + """ + if not files: + raise ValueError("At least one input file must be provided for the complement operation.") + for file_path in files: + if not file_path.exists(): + raise FileNotFoundError(f"Input file not found: {file_path}") + + cmd = ["bedops"] + + if chrom: + cmd.extend(["--chrom", chrom]) + if ec: + cmd.append("--ec") + if header: + cmd.append("--header") + if range_str: + cmd.extend(["--range", range_str]) + + cmd.append("--complement") + if chop_to_limits: + cmd.append("-L") + + cmd.extend([str(p) for p in files]) + + try: + if output_file: + with open(output_file, "w") as f: + result = subprocess.run( + cmd, check=True, text=True, stdout=f, stderr=subprocess.PIPE + ) + stdout_capture = "" + output_files_list = [str(output_file)] + else: + result = subprocess.run( + cmd, check=True, text=True, capture_output=True + ) + stdout_capture = result.stdout + output_files_list = [] + + return { + "command_executed": " ".join(cmd), + "stdout": stdout_capture, + "stderr": result.stderr, + "output_files": output_files_list, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"bedops complement failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}\n" + f"Command: {' '.join(cmd)}" + ) from e + +@mcp.tool() +def bedops_difference( + files: List[Path], + chrom: Optional[str] = None, + ec: bool = False, + header: bool = False, + range_str: Optional[str] = None, + output_file: Optional[Path] = None, +) -> dict: + """ + Computes the difference between a reference BED file and one or more other BED files. + + This corresponds to the `bedops -d` or `bedops --difference` operation. + It returns regions from the first (reference) file that do not overlap + with any regions in the subsequent files. + + Args: + files: A list of two or more input BED/Starch files. The first file is + the reference. All files must be sorted. + chrom: Process data for the given chromosome only. + ec: Error check input files (slower). + header: Accept headers (VCF, GFF, SAM, BED, WIG) in any input file. + range_str: Pad coordinates. Use 'L:R' format (e.g., '-10:20') or a + single value 'S' for symmetric padding (e.g., '100'). + output_file: Optional path to save the output. If not provided, + output is returned as a string in the result dictionary. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a + list of output files generated. + """ + if len(files) < 2: + raise ValueError("At least two input files (a reference and one other) must be provided for the difference operation.") + for file_path in files: + if not file_path.exists(): + raise FileNotFoundError(f"Input file not found: {file_path}") + + cmd = ["bedops"] + + if chrom: + cmd.extend(["--chrom", chrom]) + if ec: + cmd.append("--ec") + if header: + cmd.append("--header") + if range_str: + cmd.extend(["--range", range_str]) + + cmd.append("--difference") + cmd.extend([str(p) for p in files]) + + try: + if output_file: + with open(output_file, "w") as f: + result = subprocess.run( + cmd, check=True, text=True, stdout=f, stderr=subprocess.PIPE + ) + stdout_capture = "" + output_files_list = [str(output_file)] + else: + result = subprocess.run( + cmd, check=True, text=True, capture_output=True + ) + stdout_capture = result.stdout + output_files_list = [] + + return { + "command_executed": " ".join(cmd), + "stdout": stdout_capture, + "stderr": result.stderr, + "output_files": output_files_list, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"bedops difference failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}\n" + f"Command: {' '.join(cmd)}" + ) from e + +@mcp.tool() +def bedops_element_of( + files: List[Path], + overlap_criterion: str = "100%", + chrom: Optional[str] = None, + ec: bool = False, + header: bool = False, + range_str: Optional[str] = None, + output_file: Optional[Path] = None, +) -> dict: + """ + Finds elements in the reference file that overlap other files by a specified amount. + + This corresponds to the `bedops -e` or `bedops --element-of` operation. + It returns elements from the first (reference) file that overlap elements + in any of the other files by at least the specified amount. + + Args: + files: A list of two or more input BED/Starch files. The first file is + the reference. All files must be sorted. + overlap_criterion: The required overlap, as base pairs (e.g., '1') or + percentage (e.g., '50%'). Defaults to '100%'. + chrom: Process data for the given chromosome only. + ec: Error check input files (slower). + header: Accept headers (VCF, GFF, SAM, BED, WIG) in any input file. + range_str: Pad coordinates. Use 'L:R' or 'S' format. The first (reference) + file is NOT padded with this operation. + output_file: Optional path to save the output. If not provided, + output is returned as a string in the result dictionary. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a + list of output files generated. + """ + if len(files) < 2: + raise ValueError("At least two input files (a reference and one other) must be provided for the element-of operation.") + for file_path in files: + if not file_path.exists(): + raise FileNotFoundError(f"Input file not found: {file_path}") + + cmd = ["bedops"] + + if chrom: + cmd.extend(["--chrom", chrom]) + if ec: + cmd.append("--ec") + if header: + cmd.append("--header") + if range_str: + cmd.extend(["--range", range_str]) + + cmd.extend(["--element-of", overlap_criterion]) + cmd.extend([str(p) for p in files]) + + try: + if output_file: + with open(output_file, "w") as f: + result = subprocess.run( + cmd, check=True, text=True, stdout=f, stderr=subprocess.PIPE + ) + stdout_capture = "" + output_files_list = [str(output_file)] + else: + result = subprocess.run( + cmd, check=True, text=True, capture_output=True + ) + stdout_capture = result.stdout + output_files_list = [] + + return { + "command_executed": " ".join(cmd), + "stdout": stdout_capture, + "stderr": result.stderr, + "output_files": output_files_list, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"bedops element-of failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}\n" + f"Command: {' '.join(cmd)}" + ) from e + +@mcp.tool() +def bedops_intersect( + files: List[Path], + chrom: Optional[str] = None, + ec: bool = False, + header: bool = False, + range_str: Optional[str] = None, + output_file: Optional[Path] = None, +) -> dict: + """ + Computes the intersection of two or more BED files. + + This corresponds to the `bedops -i` or `bedops --intersect` operation. + It returns regions that are common to all input files. + + Args: + files: A list of two or more input BED/Starch files. All files must be sorted. + chrom: Process data for the given chromosome only. + ec: Error check input files (slower). + header: Accept headers (VCF, GFF, SAM, BED, WIG) in any input file. + range_str: Pad coordinates. Use 'L:R' format (e.g., '-10:20') or a + single value 'S' for symmetric padding (e.g., '100'). + output_file: Optional path to save the output. If not provided, + output is returned as a string in the result dictionary. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a + list of output files generated. + """ + if len(files) < 2: + raise ValueError("At least two input files must be provided for the intersect operation.") + for file_path in files: + if not file_path.exists(): + raise FileNotFoundError(f"Input file not found: {file_path}") + + cmd = ["bedops"] + + if chrom: + cmd.extend(["--chrom", chrom]) + if ec: + cmd.append("--ec") + if header: + cmd.append("--header") + if range_str: + cmd.extend(["--range", range_str]) + + cmd.append("--intersect") + cmd.extend([str(p) for p in files]) + + try: + if output_file: + with open(output_file, "w") as f: + result = subprocess.run( + cmd, check=True, text=True, stdout=f, stderr=subprocess.PIPE + ) + stdout_capture = "" + output_files_list = [str(output_file)] + else: + result = subprocess.run( + cmd, check=True, text=True, capture_output=True + ) + stdout_capture = result.stdout + output_files_list = [] + + return { + "command_executed": " ".join(cmd), + "stdout": stdout_capture, + "stderr": result.stderr, + "output_files": output_files_list, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"bedops intersect failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}\n" + f"Command: {' '.join(cmd)}" + ) from e + +@mcp.tool() +def bedops_merge( + files: List[Path], + chrom: Optional[str] = None, + ec: bool = False, + header: bool = False, + range_str: Optional[str] = None, + output_file: Optional[Path] = None, +) -> dict: + """ + Merges overlapping regions from one or more BED files. + + This corresponds to the `bedops -m` or `bedops --merge` operation. + It combines overlapping or adjacent intervals into a single, larger interval. + + Args: + files: A list of one or more input BED/Starch files. Must be sorted. + chrom: Process data for the given chromosome only. + ec: Error check input files (slower). + header: Accept headers (VCF, GFF, SAM, BED, WIG) in any input file. + range_str: Pad coordinates. Use 'L:R' format (e.g., '-10:20') or a + single value 'S' for symmetric padding (e.g., '100'). + output_file: Optional path to save the output. If not provided, + output is returned as a string in the result dictionary. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a + list of output files generated. + """ + if not files: + raise ValueError("At least one input file must be provided for the merge operation.") + for file_path in files: + if not file_path.exists(): + raise FileNotFoundError(f"Input file not found: {file_path}") + + cmd = ["bedops"] + + if chrom: + cmd.extend(["--chrom", chrom]) + if ec: + cmd.append("--ec") + if header: + cmd.append("--header") + if range_str: + cmd.extend(["--range", range_str]) + + cmd.append("--merge") + cmd.extend([str(p) for p in files]) + + try: + if output_file: + with open(output_file, "w") as f: + result = subprocess.run( + cmd, check=True, text=True, stdout=f, stderr=subprocess.PIPE + ) + stdout_capture = "" + output_files_list = [str(output_file)] + else: + result = subprocess.run( + cmd, check=True, text=True, capture_output=True + ) + stdout_capture = result.stdout + output_files_list = [] + + return { + "command_executed": " ".join(cmd), + "stdout": stdout_capture, + "stderr": result.stderr, + "output_files": output_files_list, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"bedops merge failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}\n" + f"Command: {' '.join(cmd)}" + ) from e + +@mcp.tool() +def bedops_not_element_of( + files: List[Path], + overlap_criterion: str = "100%", + chrom: Optional[str] = None, + ec: bool = False, + header: bool = False, + range_str: Optional[str] = None, + output_file: Optional[Path] = None, +) -> dict: + """ + Finds elements in the reference file that DO NOT overlap other files by a specified amount. + + This corresponds to the `bedops -n` or `bedops --not-element-of` operation. + It is the inverse of the `element-of` operation. + + Args: + files: A list of two or more input BED/Starch files. The first file is + the reference. All files must be sorted. + overlap_criterion: The required overlap, as base pairs (e.g., '1') or + percentage (e.g., '50%'). Defaults to '100%'. + chrom: Process data for the given chromosome only. + ec: Error check input files (slower). + header: Accept headers (VCF, GFF, SAM, BED, WIG) in any input file. + range_str: Pad coordinates. Use 'L:R' or 'S' format. The first (reference) + file is NOT padded with this operation. + output_file: Optional path to save the output. If not provided, + output is returned as a string in the result dictionary. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a + list of output files generated. + """ + if len(files) < 2: + raise ValueError("At least two input files (a reference and one other) must be provided for the not-element-of operation.") + for file_path in files: + if not file_path.exists(): + raise FileNotFoundError(f"Input file not found: {file_path}") + + cmd = ["bedops"] + + if chrom: + cmd.extend(["--chrom", chrom]) + if ec: + cmd.append("--ec") + if header: + cmd.append("--header") + if range_str: + cmd.extend(["--range", range_str]) + + cmd.extend(["--not-element-of", overlap_criterion]) + cmd.extend([str(p) for p in files]) + + try: + if output_file: + with open(output_file, "w") as f: + result = subprocess.run( + cmd, check=True, text=True, stdout=f, stderr=subprocess.PIPE + ) + stdout_capture = "" + output_files_list = [str(output_file)] + else: + result = subprocess.run( + cmd, check=True, text=True, capture_output=True + ) + stdout_capture = result.stdout + output_files_list = [] + + return { + "command_executed": " ".join(cmd), + "stdout": stdout_capture, + "stderr": result.stderr, + "output_files": output_files_list, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"bedops not-element-of failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}\n" + f"Command: {' '.join(cmd)}" + ) from e + +@mcp.tool() +def bedops_partition( + files: List[Path], + chrom: Optional[str] = None, + ec: bool = False, + header: bool = False, + range_str: Optional[str] = None, + output_file: Optional[Path] = None, +) -> dict: + """ + Partitions the input BED file(s) into disjoint segments. + + This corresponds to the `bedops -p` or `bedops --partition` operation. + It breaks the input regions into non-overlapping segments, reporting each + new segment and which input files it came from. + + Args: + files: A list of one or more input BED/Starch files. Must be sorted. + chrom: Process data for the given chromosome only. + ec: Error check input files (slower). + header: Accept headers (VCF, GFF, SAM, BED, WIG) in any input file. + range_str: Pad coordinates. Use 'L:R' format (e.g., '-10:20') or a + single value 'S' for symmetric padding (e.g., '100'). + output_file: Optional path to save the output. If not provided, + output is returned as a string in the result dictionary. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a + list of output files generated. + """ + if not files: + raise ValueError("At least one input file must be provided for the partition operation.") + for file_path in files: + if not file_path.exists(): + raise FileNotFoundError(f"Input file not found: {file_path}") + + cmd = ["bedops"] + + if chrom: + cmd.extend(["--chrom", chrom]) + if ec: + cmd.append("--ec") + if header: + cmd.append("--header") + if range_str: + cmd.extend(["--range", range_str]) + + cmd.append("--partition") + cmd.extend([str(p) for p in files]) + + try: + if output_file: + with open(output_file, "w") as f: + result = subprocess.run( + cmd, check=True, text=True, stdout=f, stderr=subprocess.PIPE + ) + stdout_capture = "" + output_files_list = [str(output_file)] + else: + result = subprocess.run( + cmd, check=True, text=True, capture_output=True + ) + stdout_capture = result.stdout + output_files_list = [] + + return { + "command_executed": " ".join(cmd), + "stdout": stdout_capture, + "stderr": result.stderr, + "output_files": output_files_list, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"bedops partition failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}\n" + f"Command: {' '.join(cmd)}" + ) from e + +@mcp.tool() +def bedops_symmdiff( + files: List[Path], + chrom: Optional[str] = None, + ec: bool = False, + header: bool = False, + range_str: Optional[str] = None, + output_file: Optional[Path] = None, +) -> dict: + """ + Computes the symmetric difference of two or more BED files. + + This corresponds to the `bedops -s` or `bedops --symmdiff` operation. + It returns regions that are unique to any of the input files (i.e., not + present in their intersection). + + Args: + files: A list of two or more input BED/Starch files. All files must be sorted. + chrom: Process data for the given chromosome only. + ec: Error check input files (slower). + header: Accept headers (VCF, GFF, SAM, BED, WIG) in any input file. + range_str: Pad coordinates. Use 'L:R' format (e.g., '-10:20') or a + single value 'S' for symmetric padding (e.g., '100'). + output_file: Optional path to save the output. If not provided, + output is returned as a string in the result dictionary. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a + list of output files generated. + """ + if len(files) < 2: + raise ValueError("At least two input files must be provided for the symmetric difference operation.") + for file_path in files: + if not file_path.exists(): + raise FileNotFoundError(f"Input file not found: {file_path}") + + cmd = ["bedops"] + + if chrom: + cmd.extend(["--chrom", chrom]) + if ec: + cmd.append("--ec") + if header: + cmd.append("--header") + if range_str: + cmd.extend(["--range", range_str]) + + cmd.append("--symmdiff") + cmd.extend([str(p) for p in files]) + + try: + if output_file: + with open(output_file, "w") as f: + result = subprocess.run( + cmd, check=True, text=True, stdout=f, stderr=subprocess.PIPE + ) + stdout_capture = "" + output_files_list = [str(output_file)] + else: + result = subprocess.run( + cmd, check=True, text=True, capture_output=True + ) + stdout_capture = result.stdout + output_files_list = [] + + return { + "command_executed": " ".join(cmd), + "stdout": stdout_capture, + "stderr": result.stderr, + "output_files": output_files_list, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"bedops symmdiff failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}\n" + f"Command: {' '.join(cmd)}" + ) from e + +@mcp.tool() +def bedops_everything( + files: List[Path], + chrom: Optional[str] = None, + ec: bool = False, + header: bool = False, + range_str: Optional[str] = None, + output_file: Optional[Path] = None, +) -> dict: + """ + Returns the union of all elements from input files without merging. + + This corresponds to the `bedops -u` or `bedops --everything` operation. + It effectively concatenates the input files while maintaining sort order + and preserving all original columns. + + Args: + files: A list of one or more input BED/Starch files. Must be sorted. + chrom: Process data for the given chromosome only. + ec: Error check input files (slower). + header: Accept headers (VCF, GFF, SAM, BED, WIG) in any input file. + range_str: Pad coordinates. Use 'L:R' format (e.g., '-10:20') or a + single value 'S' for symmetric padding (e.g., '100'). + output_file: Optional path to save the output. If not provided, + output is returned as a string in the result dictionary. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a + list of output files generated. + """ + if not files: + raise ValueError("At least one input file must be provided for the everything operation.") + for file_path in files: + if not file_path.exists(): + raise FileNotFoundError(f"Input file not found: {file_path}") + + cmd = ["bedops"] + + if chrom: + cmd.extend(["--chrom", chrom]) + if ec: + cmd.append("--ec") + if header: + cmd.append("--header") + if range_str: + cmd.extend(["--range", range_str]) + + cmd.append("--everything") + cmd.extend([str(p) for p in files]) + + try: + if output_file: + with open(output_file, "w") as f: + result = subprocess.run( + cmd, check=True, text=True, stdout=f, stderr=subprocess.PIPE + ) + stdout_capture = "" + output_files_list = [str(output_file)] + else: + result = subprocess.run( + cmd, check=True, text=True, capture_output=True + ) + stdout_capture = result.stdout + output_files_list = [] + + return { + "command_executed": " ".join(cmd), + "stdout": stdout_capture, + "stderr": result.stderr, + "output_files": output_files_list, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"bedops everything failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}\n" + f"Command: {' '.join(cmd)}" + ) from e + +@mcp.tool() +def bedops_chop( + files: List[Path], + bp: int = 1, + stagger: Optional[int] = None, + exclusive_chop: bool = False, + chrom: Optional[str] = None, + ec: bool = False, + header: bool = False, + range_str: Optional[str] = None, + output_file: Optional[Path] = None, +) -> dict: + """ + Chops elements into fixed-size, potentially staggered sub-elements. + + This corresponds to the `bedops -w` or `bedops --chop` operation. + + Args: + files: A list of one or more input BED/Starch files. Must be sorted. + bp: The size in base pairs of each chopped element. Defaults to 1. + stagger: The stagger distance in nucleotides. If not set, no staggering is done. + exclusive_chop: If True, removes single-base elements that can result + from chopping (-x flag). + chrom: Process data for the given chromosome only. + ec: Error check input files (slower). + header: Accept headers (VCF, GFF, SAM, BED, WIG) in any input file. + range_str: Pad coordinates. Use 'L:R' format (e.g., '-10:20') or a + single value 'S' for symmetric padding (e.g., '100'). + output_file: Optional path to save the output. If not provided, + output is returned as a string in the result dictionary. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a + list of output files generated. + """ + if not files: + raise ValueError("At least one input file must be provided for the chop operation.") + for file_path in files: + if not file_path.exists(): + raise FileNotFoundError(f"Input file not found: {file_path}") + + cmd = ["bedops"] + + if chrom: + cmd.extend(["--chrom", chrom]) + if ec: + cmd.append("--ec") + if header: + cmd.append("--header") + if range_str: + cmd.extend(["--range", range_str]) + + cmd.extend(["--chop", str(bp)]) + if stagger is not None: + cmd.extend(["--stagger", str(stagger)]) + if exclusive_chop: + cmd.append("-x") + + cmd.extend([str(p) for p in files]) + + try: + if output_file: + with open(output_file, "w") as f: + result = subprocess.run( + cmd, check=True, text=True, stdout=f, stderr=subprocess.PIPE + ) + stdout_capture = "" + output_files_list = [str(output_file)] + else: + result = subprocess.run( + cmd, check=True, text=True, capture_output=True + ) + stdout_capture = result.stdout + output_files_list = [] + + return { + "command_executed": " ".join(cmd), + "stdout": stdout_capture, + "stderr": result.stderr, + "output_files": output_files_list, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"bedops chop failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}\n" + f"Command: {' '.join(cmd)}" + ) from e \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/app/bedops_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/app/bedops_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4be003035fc3d2877db85a69e3f99d712e5e6a44 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/app/bedops_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/app/bedops_server.py') +SERVER_NAME = 'biosci_bedops' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..91a34e4d62a9ab6c006b5be2741a5942d0c66a8b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bedops: + build: . + image: mcp-bedops:latest + container_name: mcp-bedops + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bedops + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..11a313e56d9e8c3b984f027df03882228599fd59 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bedops + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedtools/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedtools/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..750b05a3e532bd44ab55b4f54058d163a7584b4e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedtools/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bedtools via conda (e.g., from bioconda) +RUN conda install -c bioconda bedtools -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY bedtools_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bedtools_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bedtools_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedtools/app/bedtools_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedtools/app/bedtools_server.py new file mode 100644 index 0000000000000000000000000000000000000000..60cc7a703bb0375092a1a0785ee1924167c42abb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedtools/app/bedtools_server.py @@ -0,0 +1,700 @@ +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): + """A dummy decorator to stand in for @mcp.tool().""" + return func + +mcp = type("mcp", (), {"tool": tool}) + + +@mcp.tool() +def intersect( + a: Path, + b: List[Path], + output: Optional[Path] = None, + wa: bool = False, + wb: bool = False, + loj: bool = False, + wo: bool = False, + wao: bool = False, + u: bool = False, + c: bool = False, + v: bool = False, + ubam: bool = False, + s: bool = False, + S: bool = False, + f: float = 1e-9, + F: float = 1e-9, + r: bool = False, + e: bool = False, + split: bool = False, + g: Optional[Path] = None, + header: bool = False, + bed: bool = False, + sorted: bool = False, + names: Optional[str] = None, + filenames: bool = False, + nonamecheck: bool = False, +): + """ + Find overlapping intervals in two or more BED/GFF/VCF/BAM files. + + This tool allows one to screen for overlaps between two sets of genomic features. + """ + # Input validation + if not a.exists(): + raise FileNotFoundError(f"Input file -a does not exist: {a}") + for b_file in b: + if not b_file.exists(): + raise FileNotFoundError(f"Input file in -b list does not exist: {b_file}") + if g and not g.exists(): + raise FileNotFoundError(f"Genome file -g does not exist: {g}") + + exclusive_flags = [u, c, v, wo, wao] + if sum(exclusive_flags) > 1: + raise ValueError("Options -u, -c, -v, -wo, -wao are mutually exclusive.") + if s and S: + raise ValueError("Options -s and -S are mutually exclusive.") + if f < 0.0 or f > 1.0: + raise ValueError("-f (fraction) must be between 0.0 and 1.0.") + if F < 0.0 or F > 1.0: + raise ValueError("-F (fraction) must be between 0.0 and 1.0.") + if sorted and not g: + raise ValueError("The -sorted option requires a genome file (-g).") + + # Command construction + cmd = ["bedtools", "intersect", "-a", str(a), "-b"] + cmd.extend([str(p) for p in b]) + + if wa: cmd.append("-wa") + if wb: cmd.append("-wb") + if loj: cmd.append("-loj") + if wo: cmd.append("-wo") + if wao: cmd.append("-wao") + if u: cmd.append("-u") + if c: cmd.append("-c") + if v: cmd.append("-v") + if ubam: cmd.append("-ubam") + if s: cmd.append("-s") + if S: cmd.append("-S") + if f != 1e-9: cmd.extend(["-f", str(f)]) + if F != 1e-9: cmd.extend(["-F", str(F)]) + if r: cmd.append("-r") + if e: cmd.append("-e") + if split: cmd.append("-split") + if g: cmd.extend(["-g", str(g)]) + if header: cmd.append("-header") + if bed: cmd.append("-bed") + if sorted: cmd.append("-sorted") + if names: cmd.extend(["-names", names]) + if filenames: cmd.append("-filenames") + if nonamecheck: cmd.append("-nonamecheck") + + # Subprocess execution + command_executed = " ".join(cmd) + output_files = [] + stdout_capture, stderr_capture = "", "" + + try: + if output: + output_files.append(str(output)) + with open(output, "w") as f_out: + result = subprocess.run( + cmd, check=True, text=True, stdout=f_out, stderr=subprocess.PIPE + ) + stderr_capture = result.stderr + else: + result = subprocess.run( + cmd, check=True, text=True, capture_output=True + ) + stdout_capture = result.stdout + stderr_capture = result.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout or "", + "stderr": e.stderr or "CalledProcessError with no stderr.", + "output_files": [], + "return_code": e.returncode, + } + + return { + "command_executed": command_executed, + "stdout": stdout_capture, + "stderr": stderr_capture, + "output_files": output_files, + } + + +@mcp.tool() +def merge( + i: Path, + output: Optional[Path] = None, + s: bool = False, + S: Optional[str] = None, + d: int = 0, + c: Optional[str] = None, + o: Optional[str] = None, + header: bool = False, + delim: str = ";", + n: bool = False, + nms: bool = False, + scores: Optional[str] = None, + bed: bool = False, + prec: int = 5, +): + """ + Merge overlapping features in a BED/GFF/VCF file. + + This tool combines overlapping or "book-ended" features into a single feature. + """ + # Input validation + if not i.exists(): + raise FileNotFoundError(f"Input file -i does not exist: {i}") + if S and S not in ["+", "-"]: + raise ValueError("Option -S must be either '+' or '-'.") + if s and S: + raise ValueError("Options -s and -S are mutually exclusive.") + if d < 0: + raise ValueError("Option -d (distance) must be a non-negative integer.") + if (c and not o) or (o and not c): + raise ValueError("Options -c and -o must be used together.") + if c and o: + if len(c.split(',')) != len(o.split(',')): + raise ValueError("The number of columns in -c must match the number of operations in -o.") + + # Command construction + cmd = ["bedtools", "merge", "-i", str(i)] + + if s: cmd.append("-s") + if S: cmd.extend(["-S", S]) + if d > 0: cmd.extend(["-d", str(d)]) + if c: cmd.extend(["-c", c]) + if o: cmd.extend(["-o", o]) + if header: cmd.append("-header") + if delim != ";": cmd.extend(["-delim", delim]) + if n: cmd.append("-n") + if nms: cmd.append("-nms") + if scores: cmd.extend(["-scores", scores]) + if bed: cmd.append("-bed") + if prec != 5: cmd.extend(["-prec", str(prec)]) + + # Subprocess execution + command_executed = " ".join(cmd) + output_files = [] + stdout_capture, stderr_capture = "", "" + + try: + if output: + output_files.append(str(output)) + with open(output, "w") as f_out: + result = subprocess.run( + cmd, check=True, text=True, stdout=f_out, stderr=subprocess.PIPE + ) + stderr_capture = result.stderr + else: + result = subprocess.run( + cmd, check=True, text=True, capture_output=True + ) + stdout_capture = result.stdout + stderr_capture = result.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout or "", + "stderr": e.stderr or "CalledProcessError with no stderr.", + "output_files": [], + "return_code": e.returncode, + } + + return { + "command_executed": command_executed, + "stdout": stdout_capture, + "stderr": stderr_capture, + "output_files": output_files, + } + + +@mcp.tool() +def subtract( + a: Path, + b: List[Path], + output: Optional[Path] = None, + f: float = 1e-9, + F: float = 1e-9, + r: bool = False, + e: bool = False, + s: bool = False, + S: bool = False, + A: bool = False, + B: bool = False, + N: bool = False, + header: bool = False, + g: Optional[Path] = None, +): + """ + Remove overlapping intervals from a BED/GFF/VCF file. + + This tool removes portions of features in file A that are overlapped by features in file(s) B. + """ + # Input validation + if not a.exists(): + raise FileNotFoundError(f"Input file -a does not exist: {a}") + for b_file in b: + if not b_file.exists(): + raise FileNotFoundError(f"Input file in -b list does not exist: {b_file}") + if g and not g.exists(): + raise FileNotFoundError(f"Genome file -g does not exist: {g}") + if A and B: + raise ValueError("Options -A and -B are mutually exclusive.") + if s and S: + raise ValueError("Options -s and -S are mutually exclusive.") + + # Command construction + cmd = ["bedtools", "subtract", "-a", str(a), "-b"] + cmd.extend([str(p) for p in b]) + + if f != 1e-9: cmd.extend(["-f", str(f)]) + if F != 1e-9: cmd.extend(["-F", str(F)]) + if r: cmd.append("-r") + if e: cmd.append("-e") + if s: cmd.append("-s") + if S: cmd.append("-S") + if A: cmd.append("-A") + if B: cmd.append("-B") + if N: cmd.append("-N") + if header: cmd.append("-header") + if g: cmd.extend(["-g", str(g)]) + + # Subprocess execution + command_executed = " ".join(cmd) + output_files = [] + stdout_capture, stderr_capture = "", "" + + try: + if output: + output_files.append(str(output)) + with open(output, "w") as f_out: + result = subprocess.run( + cmd, check=True, text=True, stdout=f_out, stderr=subprocess.PIPE + ) + stderr_capture = result.stderr + else: + result = subprocess.run( + cmd, check=True, text=True, capture_output=True + ) + stdout_capture = result.stdout + stderr_capture = result.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout or "", + "stderr": e.stderr or "CalledProcessError with no stderr.", + "output_files": [], + "return_code": e.returncode, + } + + return { + "command_executed": command_executed, + "stdout": stdout_capture, + "stderr": stderr_capture, + "output_files": output_files, + } + + +@mcp.tool() +def slop( + i: Path, + g: Path, + output: Optional[Path] = None, + b: int = 0, + l: int = 0, + r: int = 0, + s: bool = False, + pct: bool = False, + header: bool = False, +): + """ + Increase the size of features in a BED/GFF/VCF file. + + This tool will increase the size of each feature in a feature file by a user-defined number of bases. + """ + # Input validation + if not i.exists(): + raise FileNotFoundError(f"Input file -i does not exist: {i}") + if not g.exists(): + raise FileNotFoundError(f"Genome file -g does not exist: {g}") + if b != 0 and (l != 0 or r != 0): + raise ValueError("Option -b cannot be used with -l or -r.") + + # Command construction + cmd = ["bedtools", "slop", "-i", str(i), "-g", str(g)] + + if b != 0: cmd.extend(["-b", str(b)]) + if l != 0: cmd.extend(["-l", str(l)]) + if r != 0: cmd.extend(["-r", str(r)]) + if s: cmd.append("-s") + if pct: cmd.append("-pct") + if header: cmd.append("-header") + + # Subprocess execution + command_executed = " ".join(cmd) + output_files = [] + stdout_capture, stderr_capture = "", "" + + try: + if output: + output_files.append(str(output)) + with open(output, "w") as f_out: + result = subprocess.run( + cmd, check=True, text=True, stdout=f_out, stderr=subprocess.PIPE + ) + stderr_capture = result.stderr + else: + result = subprocess.run( + cmd, check=True, text=True, capture_output=True + ) + stdout_capture = result.stdout + stderr_capture = result.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout or "", + "stderr": e.stderr or "CalledProcessError with no stderr.", + "output_files": [], + "return_code": e.returncode, + } + + return { + "command_executed": command_executed, + "stdout": stdout_capture, + "stderr": stderr_capture, + "output_files": output_files, + } + + +@mcp.tool() +def getfasta( + fi: Path, + bed: Path, + fo: Optional[Path] = None, + s: bool = False, + split: bool = False, + name: bool = False, + name_plus: bool = False, + tab: bool = False, + full_header: bool = False, +): + """ + Extract DNA sequences from a FASTA file based on BED/GFF/VCF coordinates. + """ + # Input validation + if not fi.exists(): + raise FileNotFoundError(f"FASTA input file -fi does not exist: {fi}") + if not bed.exists(): + raise FileNotFoundError(f"BED/GFF/VCF file -bed does not exist: {bed}") + if name and name_plus: + raise ValueError("Options -name and -name+ are mutually exclusive.") + + # Command construction + cmd = ["bedtools", "getfasta", "-fi", str(fi), "-bed", str(bed)] + + if s: cmd.append("-s") + if split: cmd.append("-split") + if name: cmd.append("-name") + if name_plus: cmd.append("-name+") + if tab: cmd.append("-tab") + if full_header: cmd.append("-fullHeader") + if fo: cmd.extend(["-fo", str(fo)]) + + # Subprocess execution + command_executed = " ".join(cmd) + output_files = [] + stdout_capture, stderr_capture = "", "" + + try: + # getfasta is unique in that it has a dedicated -fo parameter + # and doesn't typically write to stdout if -fo is used. + result = subprocess.run( + cmd, check=True, text=True, capture_output=True + ) + stdout_capture = result.stdout + stderr_capture = result.stderr + if fo: + output_files.append(str(fo)) + + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout or "", + "stderr": e.stderr or "CalledProcessError with no stderr.", + "output_files": [], + "return_code": e.returncode, + } + + return { + "command_executed": command_executed, + "stdout": stdout_capture, + "stderr": stderr_capture, + "output_files": output_files, + } + + +@mcp.tool() +def sort( + i: Path, + output: Optional[Path] = None, + header: bool = False, + g: Optional[Path] = None, + faidx: Optional[Path] = None, + sizeA: bool = False, + sizeD: bool = False, + chrThenSizeA: bool = False, + chrThenSizeD: bool = False, + chrThenScoreA: bool = False, + chrThenScoreD: bool = False, +): + """ + Sort a BED/GFF/VCF file by chromosome and then by start position. + """ + # Input validation + if not i.exists(): + raise FileNotFoundError(f"Input file -i does not exist: {i}") + if g and not g.exists(): + raise FileNotFoundError(f"Genome file -g does not exist: {g}") + if faidx and not faidx.exists(): + raise FileNotFoundError(f"FASTA index file -faidx does not exist: {faidx}") + + sort_flags = [sizeA, sizeD, chrThenSizeA, chrThenSizeD, chrThenScoreA, chrThenScoreD] + if sum(sort_flags) > 1: + raise ValueError("Multiple sorting order flags were provided, but only one is allowed.") + + # Command construction + cmd = ["bedtools", "sort", "-i", str(i)] + + if header: cmd.append("-header") + if g: cmd.extend(["-g", str(g)]) + if faidx: cmd.extend(["-faidx", str(faidx)]) + if sizeA: cmd.append("-sizeA") + if sizeD: cmd.append("-sizeD") + if chrThenSizeA: cmd.append("-chrThenSizeA") + if chrThenSizeD: cmd.append("-chrThenSizeD") + if chrThenScoreA: cmd.append("-chrThenScoreA") + if chrThenScoreD: cmd.append("-chrThenScoreD") + + # Subprocess execution + command_executed = " ".join(cmd) + output_files = [] + stdout_capture, stderr_capture = "", "" + + try: + if output: + output_files.append(str(output)) + with open(output, "w") as f_out: + result = subprocess.run( + cmd, check=True, text=True, stdout=f_out, stderr=subprocess.PIPE + ) + stderr_capture = result.stderr + else: + result = subprocess.run( + cmd, check=True, text=True, capture_output=True + ) + stdout_capture = result.stdout + stderr_capture = result.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout or "", + "stderr": e.stderr or "CalledProcessError with no stderr.", + "output_files": [], + "return_code": e.returncode, + } + + return { + "command_executed": command_executed, + "stdout": stdout_capture, + "stderr": stderr_capture, + "output_files": output_files, + } + + +@mcp.tool() +def coverage( + a: Path, + b: List[Path], + output: Optional[Path] = None, + s: bool = False, + S: bool = False, + f: float = 1e-9, + F: float = 1e-9, + r: bool = False, + e: bool = False, + split: bool = False, + d: bool = False, + counts: bool = False, + hist: bool = False, + mean: bool = False, + g: Optional[Path] = None, + header: bool = False, + sorted: bool = False, +): + """ + Compute the coverage of features in file A on features in file(s) B. + """ + # Input validation + if not a.exists(): + raise FileNotFoundError(f"Input file -a does not exist: {a}") + for b_file in b: + if not b_file.exists(): + raise FileNotFoundError(f"Input file in -b list does not exist: {b_file}") + if g and not g.exists(): + raise FileNotFoundError(f"Genome file -g does not exist: {g}") + if s and S: + raise ValueError("Options -s and -S are mutually exclusive.") + if sorted and not g: + raise ValueError("The -sorted option requires a genome file (-g).") + + # Command construction + cmd = ["bedtools", "coverage", "-a", str(a), "-b"] + cmd.extend([str(p) for p in b]) + + if s: cmd.append("-s") + if S: cmd.append("-S") + if f != 1e-9: cmd.extend(["-f", str(f)]) + if F != 1e-9: cmd.extend(["-F", str(F)]) + if r: cmd.append("-r") + if e: cmd.append("-e") + if split: cmd.append("-split") + if d: cmd.append("-d") + if counts: cmd.append("-counts") + if hist: cmd.append("-hist") + if mean: cmd.append("-mean") + if g: cmd.extend(["-g", str(g)]) + if header: cmd.append("-header") + if sorted: cmd.append("-sorted") + + # Subprocess execution + command_executed = " ".join(cmd) + output_files = [] + stdout_capture, stderr_capture = "", "" + + try: + if output: + output_files.append(str(output)) + with open(output, "w") as f_out: + result = subprocess.run( + cmd, check=True, text=True, stdout=f_out, stderr=subprocess.PIPE + ) + stderr_capture = result.stderr + else: + result = subprocess.run( + cmd, check=True, text=True, capture_output=True + ) + stdout_capture = result.stdout + stderr_capture = result.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout or "", + "stderr": e.stderr or "CalledProcessError with no stderr.", + "output_files": [], + "return_code": e.returncode, + } + + return { + "command_executed": command_executed, + "stdout": stdout_capture, + "stderr": stderr_capture, + "output_files": output_files, + } + + +@mcp.tool() +def genomecov( + i: Path, + g: Path, + output: Optional[Path] = None, + d: bool = False, + dz: bool = False, + bga: bool = False, + bg: bool = False, + scale: float = 1.0, + pc: bool = False, + fs: bool = False, + split: bool = False, + strand: Optional[str] = None, + max: int = 0, + trackline: bool = False, + trackopts: Optional[str] = None, +): + """ + Compute genome-wide coverage of a feature file. + """ + # Input validation + if not i.exists(): + raise FileNotFoundError(f"Input file -i does not exist: {i}") + if not g.exists(): + raise FileNotFoundError(f"Genome file -g does not exist: {g}") + if strand and strand not in ["+", "-"]: + raise ValueError("Option -strand must be either '+' or '-'.") + if max < 0: + raise ValueError("Option -max must be a non-negative integer.") + output_modes = [d, dz, bga, bg] + if sum(output_modes) > 1: + raise ValueError("Output format flags (-d, -dz, -bga, -bg) are mutually exclusive.") + + # Command construction + cmd = ["bedtools", "genomecov", "-i", str(i), "-g", str(g)] + + if d: cmd.append("-d") + if dz: cmd.append("-dz") + if bga: cmd.append("-bga") + if bg: cmd.append("-bg") + if scale != 1.0: cmd.extend(["-scale", str(scale)]) + if pc: cmd.append("-pc") + if fs: cmd.append("-fs") + if split: cmd.append("-split") + if strand: cmd.extend(["-strand", strand]) + if max > 0: cmd.extend(["-max", str(max)]) + if trackline: cmd.append("-trackline") + if trackopts: cmd.extend(["-trackopts", trackopts]) + + # Subprocess execution + command_executed = " ".join(cmd) + output_files = [] + stdout_capture, stderr_capture = "", "" + + try: + if output: + output_files.append(str(output)) + with open(output, "w") as f_out: + result = subprocess.run( + cmd, check=True, text=True, stdout=f_out, stderr=subprocess.PIPE + ) + stderr_capture = result.stderr + else: + result = subprocess.run( + cmd, check=True, text=True, capture_output=True + ) + stdout_capture = result.stdout + stderr_capture = result.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout or "", + "stderr": e.stderr or "CalledProcessError with no stderr.", + "output_files": [], + "return_code": e.returncode, + } + + return { + "command_executed": command_executed, + "stdout": stdout_capture, + "stderr": stderr_capture, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedtools/app/bedtools_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedtools/app/bedtools_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5dd958ed4f9a8879b58491e726965d448f84f4ed --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedtools/app/bedtools_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedtools/app/bedtools_server.py') +SERVER_NAME = 'biosci_bedtools' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedtools/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedtools/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..10a63b0a472bab5986e0819cee19136b24f3225d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedtools/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bedtools: + build: . + image: mcp-bedtools:latest + container_name: mcp-bedtools + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bedtools + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedtools/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedtools/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eb86132c46b74418d77a62f07a7d2128519e3f20 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedtools/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bedtools + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedtools/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedtools/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedtools/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..26acb9706d6e3e8a943d4d9676b9eb014a983372 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioawk via conda (e.g., from bioconda) +RUN conda install -c bioconda bioawk -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioawk_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioawk_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioawk_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/app/bioawk_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/app/bioawk_server.py new file mode 100644 index 0000000000000000000000000000000000000000..045640223e6d54a4636d76ad5fad59535ca67373 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/app/bioawk_server.py @@ -0,0 +1,132 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict, Any + +# Assume 'mcp' is a globally available module in the execution environment. +# from some_mcp_library import mcp + +@mcp.tool +def bioawk( + program: Optional[str] = None, + program_file: Optional[Path] = None, + input_files: Optional[List[Path]] = None, + output_file: Optional[Path] = None, + format: Optional[str] = None, + tab_separator: bool = False, + include_header: bool = False, + variables: Optional[List[str]] = None, + field_separator: Optional[str] = None, +) -> Dict[str, Any]: + """ + Executes the bioawk command, a powerful stream editor for biological data formats. + + bioawk is an extension of awk that understands common biological data formats + like FASTA, FASTQ, SAM, VCF, BED, and GFF. At least one of 'program' or + 'program_file' must be provided. + + Args: + program: The AWK program string to execute. Mutually exclusive with 'program_file'. + program_file: Path to a file containing the AWK program. Mutually exclusive with 'program'. + input_files: A list of input files to process. If not provided, bioawk reads from standard input. + output_file: Path to a file where the output (stdout) will be saved. If not provided, stdout is captured and returned. + format: Input format (-c). Supported formats include 'fasta', 'fastq', 'sam', 'vcf', 'bed', 'gff'. + tab_separator: Use tab as the input and output field separator (-t flag). + include_header: Include header in the output for formats like VCF/SAM (-H flag). + variables: A list of 'var=value' strings to define AWK variables (-v flag). + field_separator: The input field separator string (-F flag). + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not program and not program_file: + raise ValueError("Either 'program' or 'program_file' must be provided.") + if program and program_file: + raise ValueError("'program' and 'program_file' are mutually exclusive and cannot be used together.") + + if program_file: + if not program_file.is_file(): + raise FileNotFoundError(f"Program file not found: {program_file}") + + if input_files: + for file_path in input_files: + if not file_path.is_file(): + raise FileNotFoundError(f"Input file not found: {file_path}") + + VALID_FORMATS = {"fasta", "fastq", "sam", "vcf", "bed", "gff"} + if format and format.lower() not in VALID_FORMATS: + raise ValueError(f"Invalid format '{format}'. Must be one of {VALID_FORMATS}.") + + if variables: + for var in variables: + if "=" not in var: + raise ValueError(f"Invalid variable assignment '{var}'. Must be in 'var=value' format.") + + # --- Command Construction --- + cmd = ["bioawk"] + + if format: + cmd.extend(["-c", format.lower()]) + if tab_separator: + cmd.append("-t") + if include_header: + cmd.append("-H") + if field_separator: + cmd.extend(["-F", field_separator]) + if variables: + for var in variables: + cmd.extend(["-v", var]) + + # The program or program_file argument must come after options but before input files. + if program_file: + cmd.extend(["-f", str(program_file)]) + elif program: + cmd.append(program) + + if input_files: + cmd.extend([str(p) for p in input_files]) + + command_executed = " ".join(cmd) + + # --- Subprocess Execution --- + try: + if output_file: + # Create parent directories if they don't exist + output_file.parent.mkdir(parents=True, exist_ok=True) + with open(output_file, "w") as f_out: + result = subprocess.run( + cmd, + check=True, + stdout=f_out, + stderr=subprocess.PIPE, + text=True, + ) + stdout_content = f"Output successfully written to {output_file}" + output_files_list = [str(output_file)] + else: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + stdout_content = result.stdout + output_files_list = [] + + return { + "command_executed": command_executed, + "stdout": stdout_content, + "stderr": result.stderr, + "output_files": output_files_list, + } + except FileNotFoundError: + raise RuntimeError("bioawk command not found. Please ensure it is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + # Return a structured error response if the command fails + return { + "command_executed": command_executed, + "stdout": e.stdout or "", + "stderr": e.stderr or f"bioawk exited with error code {e.returncode}", + "output_files": [], + "error": f"Command failed with exit code {e.returncode}" + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/app/bioawk_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/app/bioawk_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6b2bf10ed77446b94cc76a336eba7370590a14db --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/app/bioawk_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/app/bioawk_server.py') +SERVER_NAME = 'biosci_bioawk' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7225a96d51707881729bddfe8df7a8a8ad5a61bd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioawk: + build: . + image: mcp-bioawk:latest + container_name: mcp-bioawk + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioawk + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d850d38d19bdb05c11c590472bc88660b4d32fef --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioawk + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6f2d33b2efd16bce295e2841bac519b1b3633d42 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.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-affyio via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-affyio -y && conda clean -a + +# 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-affyio_server.py /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-affyio_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --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-affyio_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/app/bioconductor-affyio_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/app/bioconductor-affyio_server.py new file mode 100644 index 0000000000000000000000000000000000000000..59885936782f559ab659966f24a285ba65cff383 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/app/bioconductor-affyio_server.py @@ -0,0 +1,208 @@ +import subprocess +import json +import os +from pathlib import Path +from typing import Optional, List, Dict, Any + +@mcp.tool() +def affyio_read_celfile_header( + filename: str, + info: str = "full" +) -> Dict[str, Any]: + """ + Read the header information from an Affymetrix CEL file. + + Args: + filename: Path to the CEL file. + info: Level of information to extract ('full' or 'minimal'). + """ + file_path = Path(filename) + if not file_path.exists(): + return {"error": f"File not found: {filename}"} + + if info not in ["full", "minimal"]: + info = "full" + + # R script to extract header and convert to JSON + r_command = f""" + library(affyio) + library(jsonlite) + header <- read.celfile.header("{str(file_path)}", info="{info}") + cat(toJSON(header, auto_unbox = TRUE)) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_command], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"read.celfile.header('{filename}')", + "header_data": json.loads(result.stdout), + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "command_executed": e.cmd + } + except json.JSONDecodeError: + return {"error": "Failed to parse R output", "raw_stdout": result.stdout} + +@mcp.tool() +def affyio_read_celfile( + filename: str, + output_csv: str, + intensity_only: bool = True +) -> Dict[str, Any]: + """ + Read an Affymetrix CEL file and export the intensity data to a CSV file. + + Args: + filename: Path to the CEL file. + output_csv: Path where the intensity data should be saved. + intensity_only: If True, only the intensity values are extracted. + """ + input_path = Path(filename) + output_path = Path(output_csv) + + if not input_path.exists(): + return {"error": f"Input file not found: {filename}"} + + intensity_val = "TRUE" if intensity_only else "FALSE" + + r_command = f""" + library(affyio) + data <- read.celfile("{str(input_path)}", intensity.only={intensity_val}) + # If intensity.only is TRUE, it returns a list with INTENSITY + # If FALSE, it returns a list with INTENSITY, MASKS, OUTLIERS + write.csv(data$INTENSITY, "{str(output_path)}") + """ + + try: + subprocess.run( + ["Rscript", "-e", r_command], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"read.celfile('{filename}')", + "status": "Success", + "output_file": str(output_path) + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stderr": e.stderr, + "stdout": e.stdout + } + +@mcp.tool() +def affyio_check_cdf_type( + filename: str +) -> Dict[str, Any]: + """ + Identify the type of an Affymetrix CDF file (e.g., text, binary, gzipped). + + Args: + filename: Path to the CDF file. + """ + file_path = Path(filename) + if not file_path.exists(): + return {"error": f"File not found: {filename}"} + + r_command = f""" + library(affyio) + type <- check.cdf.type("{str(file_path)}") + cat(type) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_command], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"check.cdf.type('{filename}')", + "cdf_type": result.stdout.strip(), + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} + +@mcp.tool() +def affyio_read_cdffile_summary( + filename: str +) -> Dict[str, Any]: + """ + Read an Affymetrix CDF file and return a summary of its contents. + Note: Full CDF lists are extremely large; this tool returns structural metadata. + + Args: + filename: Path to the CDF file. + """ + file_path = Path(filename) + if not file_path.exists(): + return {"error": f"File not found: {filename}"} + + r_command = f""" + library(affyio) + library(jsonlite) + cdf_data <- read.cdffile.list("{str(file_path)}") + summary_info <- list( + filename = "{filename}", + num_probesets = length(cdf_data), + probeset_names = head(names(cdf_data), 10) + ) + cat(toJSON(summary_info, auto_unbox = TRUE)) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_command], + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": f"read.cdffile.list('{filename}')", + "summary": json.loads(result.stdout), + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} + +@mcp.tool() +def affyio_get_package_version() -> Dict[str, Any]: + """ + Check the installed version of the affyio package and its dependencies. + """ + r_command = """ + library(affyio) + v <- as.character(packageVersion("affyio")) + cat(v) + """ + try: + result = subprocess.run( + ["Rscript", "-e", r_command], + capture_output=True, + text=True, + check=True + ) + return { + "package": "affyio", + "version": result.stdout.strip(), + "r_version": subprocess.run(["Rscript", "--version"], capture_output=True, text=True).stderr.strip() + } + except subprocess.CalledProcessError as e: + return { + "error": "Could not determine package version. Ensure bioconductor-affyio is installed.", + "stderr": e.stderr + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/app/bioconductor-affyio_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/app/bioconductor-affyio_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e5070944db2376613a715d207ee0461b226c7a22 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/app/bioconductor-affyio_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/app/bioconductor-affyio_server.py') +SERVER_NAME = 'biosci_bioconductor_affyio' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..ac239ca3a52d2c9c05317d88ee726fcd08573a94 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-affyio: + build: . + image: mcp-bioconductor-affyio:latest + container_name: mcp-bioconductor-affyio + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-affyio + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..486380658759a501811fc16c5f5101304cb08b26 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-affyio + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotate/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotate/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8df3183e644dd3c5947b4c5585e2c942f6d7c80c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotate/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.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-annotate via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-annotate -y && conda clean -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-annotate_server.py /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-annotate_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --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-annotate_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotate/app/bioconductor-annotate_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotate/app/bioconductor-annotate_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e8aa22c0b818479e01d8ba4f0ce30f4cb61ba843 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotate/app/bioconductor-annotate_server.py @@ -0,0 +1,141 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, List, Dict, Any + +# The mcp.tool decorator is supplied by the MCP framework. +# It is aliased here for clarity and to allow for standalone code analysis. +class mcp: + """A dummy class to represent the MCP decorator for static analysis.""" + @staticmethod + def tool(func): + """A dummy decorator that returns the function unchanged.""" + return func + +@mcp.tool +def rscript( + script_file: Optional[Path] = None, + expressions: Optional[List[str]] = None, + script_args: Optional[List[str]] = None, + verbose: bool = False, + default_packages: Optional[str] = None, + vanilla: bool = False, + save: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: bool = False, + restore: bool = False, +) -> Dict[str, Any]: + """ + Executes an R script or R expressions using the Rscript command-line tool. + + This tool serves as a wrapper for the Rscript interpreter, which is commonly + used to run bioinformatics scripts that rely on R packages from repositories + like CRAN or Bioconductor (e.g., for using bioconductor-annotate). + You must provide either a path to an R script file or a list of R expressions + to execute. + + Args: + script_file: Path to the R script file to be executed. + expressions: A list of R expressions to execute directly. Use this instead of script_file. + script_args: A list of arguments to be passed to the R script itself. + verbose: If True, enables verbose output, printing information on progress. + default_packages: A comma-separated string of package names to be loaded by default. + vanilla: If True, combines --no-save, --no-restore, --no-site-file, + --no-init-file, and --no-environ. This provides a clean session. + If True, the individual flags (save, restore, etc.) are ignored. + save: If True, the workspace will be saved at the end of the session. Ignored if vanilla is True. + no_environ: If True, site and user environment files will not be read. Ignored if vanilla is True. + no_site_file: If True, the site-wide Rprofile will not be read. Ignored if vanilla is True. + no_init_file: If True, the user's R profile will not be read. Ignored if vanilla is True. + restore: If True, previously saved objects will be restored at startup. Ignored if vanilla is True. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # 1. Input Validation + if not script_file and not expressions: + raise ValueError("Either 'script_file' or 'expressions' must be provided.") + if script_file and expressions: + raise ValueError("Cannot provide both 'script_file' and 'expressions' simultaneously.") + + if script_file: + if not script_file.is_file(): + raise FileNotFoundError(f"The specified script file does not exist: {script_file}") + + # 2. Command Construction + cmd = ["Rscript"] + + if verbose: + cmd.append("--verbose") + + if default_packages: + cmd.append(f"--default-packages={default_packages}") + + if vanilla: + cmd.append("--vanilla") + else: + # These options are processed only if --vanilla is not used + if save: + cmd.append("--save") + if no_environ: + cmd.append("--no-environ") + if no_site_file: + cmd.append("--no-site-file") + if no_init_file: + cmd.append("--no-init-file") + if restore: + cmd.append("--restore") + + # Add script file or expressions to execute + if script_file: + cmd.append(str(script_file)) + elif expressions: + for expr in expressions: + cmd.extend(["-e", expr]) + + # Add trailing arguments for the R script + if script_args: + cmd.extend(script_args) + + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + # 3. Subprocess Execution and Error Handling + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except FileNotFoundError: + # This error occurs if 'Rscript' is not in the system's PATH + logging.error("Rscript executable not found.") + return { + "error": "Rscript not found. Please ensure R is installed and in your PATH.", + "command_executed": command_executed, + "stdout": "", + "stderr": "Rscript executable not found.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + # This error occurs if the R script exits with a non-zero status code + logging.error(f"Rscript execution failed with exit code {e.returncode}") + return { + "error": f"Rscript execution failed with exit code {e.returncode}.", + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + # 4. Structured Result Return + # This wrapper cannot reliably determine output files generated by the user's script. + # The user is responsible for knowing and handling the script's output. + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotate/app/bioconductor-annotate_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotate/app/bioconductor-annotate_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9e75ef215bafcb160485aeb4bb69c2b3257d2406 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotate/app/bioconductor-annotate_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotate/app/bioconductor-annotate_server.py') +SERVER_NAME = 'biosci_bioconductor_annotate' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotate/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotate/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..5020838deb35bbae2bcb064ef99231a9f153e504 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotate/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-annotate: + build: . + image: mcp-bioconductor-annotate:latest + container_name: mcp-bioconductor-annotate + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-annotate + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotate/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotate/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ca6f7fedcb6d13738028109983815bb7e6c4b8fd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotate/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-annotate + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotate/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotate/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotate/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotationdbi/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotationdbi/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..31bb65012357ab749e55a3d2e0a30bbf3fc1c6e2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotationdbi/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.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-annotationdbi via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-annotationdbi -y && conda clean -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-annotationdbi_server.py /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-annotationdbi_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --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-annotationdbi_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotationdbi/app/bioconductor-annotationdbi_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotationdbi/app/bioconductor-annotationdbi_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6ae86efcdbf2219ae36a88dbaccb8032654aa3f2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotationdbi/app/bioconductor-annotationdbi_server.py @@ -0,0 +1,456 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# MCP decorator is assumed to be defined in the execution environment. +# No import is needed as per the instructions. + +@mcp.tool() +def annotationdbi_columns(db_package: str) -> dict: + """ + Lists all available columns for a given Bioconductor annotation package. + + This tool requires R, Rscript, and the Bioconductor packages 'AnnotationDbi' + and the specified 'db_package' to be installed in the R environment. + + Args: + db_package: The name of the Bioconductor annotation package (e.g., "org.Hs.eg.db"). + + Returns: + A dictionary containing the command executed and the standard output with the column names. + """ + if not db_package: + raise ValueError("db_package must be a non-empty string.") + + r_script_content = f""" + suppressPackageStartupMessages(library(AnnotationDbi)) + + db_package_name <- "{db_package}" + + if (!requireNamespace(db_package_name, quietly = TRUE)) {{ + stop(paste("Annotation package '", db_package_name, "' is not installed. Please install it from Bioconductor."), call. = FALSE) + }} + db <- get(db_package_name) + + tryCatch({{ + result_data <- AnnotationDbi::columns(db) + cat(result_data, sep = "\\n") + }}, error = function(e) {{ + stop(paste("AnnotationDbi::columns failed:", e$message), call. = FALSE) + }}) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, encoding='utf-8') as tmp_script: + tmp_script.write(r_script_content) + script_path = tmp_script.name + + cmd = ["Rscript", script_path] + command_executed = f"Rscript {script_path}" + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed with exit code {e.returncode}" + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'Rscript' command not found. Please ensure R is installed and 'Rscript' is in your system's PATH.", + "error": "Dependency not found" + } + finally: + Path(script_path).unlink() + +@mcp.tool() +def annotationdbi_keytypes(db_package: str) -> dict: + """ + Lists all available keytypes for a given Bioconductor annotation package. + + This tool requires R, Rscript, and the Bioconductor packages 'AnnotationDbi' + and the specified 'db_package' to be installed in the R environment. + + Args: + db_package: The name of the Bioconductor annotation package (e.g., "org.Hs.eg.db"). + + Returns: + A dictionary containing the command executed and the standard output with the keytype names. + """ + if not db_package: + raise ValueError("db_package must be a non-empty string.") + + r_script_content = f""" + suppressPackageStartupMessages(library(AnnotationDbi)) + + db_package_name <- "{db_package}" + + if (!requireNamespace(db_package_name, quietly = TRUE)) {{ + stop(paste("Annotation package '", db_package_name, "' is not installed. Please install it from Bioconductor."), call. = FALSE) + }} + db <- get(db_package_name) + + tryCatch({{ + result_data <- AnnotationDbi::keytypes(db) + cat(result_data, sep = "\\n") + }}, error = function(e) {{ + stop(paste("AnnotationDbi::keytypes failed:", e$message), call. = FALSE) + }}) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, encoding='utf-8') as tmp_script: + tmp_script.write(r_script_content) + script_path = tmp_script.name + + cmd = ["Rscript", script_path] + command_executed = f"Rscript {script_path}" + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed with exit code {e.returncode}" + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'Rscript' command not found. Please ensure R is installed and 'Rscript' is in your system's PATH.", + "error": "Dependency not found" + } + finally: + Path(script_path).unlink() + +@mcp.tool() +def annotationdbi_keys(db_package: str, keytype: str) -> dict: + """ + Lists all available keys for a given keytype in a Bioconductor annotation package. + + This tool requires R, Rscript, and the Bioconductor packages 'AnnotationDbi' + and the specified 'db_package' to be installed in the R environment. + + Args: + db_package: The name of the Bioconductor annotation package (e.g., "org.Hs.eg.db"). + keytype: The keytype for which to retrieve all available keys (e.g., "ENTREZID"). + + Returns: + A dictionary containing the command executed and the standard output with the keys. + """ + if not db_package: + raise ValueError("db_package must be a non-empty string.") + if not keytype: + raise ValueError("keytype must be a non-empty string.") + + r_script_content = f""" + suppressPackageStartupMessages(library(AnnotationDbi)) + + db_package_name <- "{db_package}" + keytype_str <- "{keytype}" + + if (!requireNamespace(db_package_name, quietly = TRUE)) {{ + stop(paste("Annotation package '", db_package_name, "' is not installed. Please install it from Bioconductor."), call. = FALSE) + }} + db <- get(db_package_name) + + tryCatch({{ + result_data <- AnnotationDbi::keys(db, keytype = keytype_str) + cat(result_data, sep = "\\n") + }}, error = function(e) {{ + stop(paste("AnnotationDbi::keys failed:", e$message), call. = FALSE) + }}) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, encoding='utf-8') as tmp_script: + tmp_script.write(r_script_content) + script_path = tmp_script.name + + cmd = ["Rscript", script_path] + command_executed = f"Rscript {script_path}" + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed with exit code {e.returncode}" + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'Rscript' command not found. Please ensure R is installed and 'Rscript' is in your system's PATH.", + "error": "Dependency not found" + } + finally: + Path(script_path).unlink() + +@mcp.tool() +def annotationdbi_select( + db_package: str, + keys: str, + columns: str, + keytype: str, + output_file: Path, +) -> dict: + """ + Retrieves data from a Bioconductor annotation package using AnnotationDbi::select. + + This tool requires R, Rscript, and the Bioconductor packages 'AnnotationDbi' + and the specified 'db_package' to be installed in the R environment. + + Args: + db_package: The name of the Bioconductor annotation package (e.g., "org.Hs.eg.db"). + keys: A comma-separated string of keys to query (e.g., "BRCA1,TP53"). + columns: A comma-separated string of columns to retrieve (e.g., "SYMBOL,GENENAME,ENTREZID"). + keytype: The type of the provided keys (e.g., "SYMBOL"). + output_file: The path to save the results as a TSV file. + + Returns: + A dictionary containing the command executed, logs, and the path to the output file. + """ + if not db_package: + raise ValueError("db_package must be a non-empty string.") + if not keys: + raise ValueError("keys must be a non-empty, comma-separated string.") + if not columns: + raise ValueError("columns must be a non-empty, comma-separated string.") + if not keytype: + raise ValueError("keytype must be a non-empty string.") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + r_script_content = f""" + suppressPackageStartupMessages(library(AnnotationDbi)) + + db_package_name <- "{db_package}" + keys_vec <- unlist(strsplit("{keys}", ",")) + columns_vec <- unlist(strsplit("{columns}", ",")) + keytype_str <- "{keytype}" + output_file_path <- "{output_file.resolve()}" + + if (!requireNamespace(db_package_name, quietly = TRUE)) {{ + stop(paste("Annotation package '", db_package_name, "' is not installed. Please install it from Bioconductor."), call. = FALSE) + }} + db <- get(db_package_name) + + tryCatch({{ + results <- AnnotationDbi::select(db, + keys = keys_vec, + columns = columns_vec, + keytype = keytype_str) + + write.table(results, + file = output_file_path, + sep = "\\t", + row.names = FALSE, + col.names = TRUE, + quote = FALSE) + + cat(paste("Successfully wrote", nrow(results), "rows to", basename(output_file_path), "\\n")) + + }}, error = function(e) {{ + stop(paste("AnnotationDbi::select failed:", e$message), call. = FALSE) + }}) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, encoding='utf-8') as tmp_script: + tmp_script.write(r_script_content) + script_path = tmp_script.name + + cmd = ["Rscript", script_path] + command_executed = f"Rscript {script_path}" + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file.resolve())] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed with exit code {e.returncode}", + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'Rscript' command not found. Please ensure R is installed and 'Rscript' is in your system's PATH.", + "error": "Dependency not found", + "output_files": [] + } + finally: + Path(script_path).unlink() + +@mcp.tool() +def annotationdbi_mapids( + db_package: str, + keys: str, + column: str, + keytype: str, + output_file: Path, + multi_vals: str = "first", +) -> dict: + """ + Maps identifiers from one type to another using AnnotationDbi::mapIds. + + This tool requires R, Rscript, and the Bioconductor packages 'AnnotationDbi' + and the specified 'db_package' to be installed in the R environment. + + Args: + db_package: The name of the Bioconductor annotation package (e.g., "org.Hs.eg.db"). + keys: A comma-separated string of keys to query (e.g., "BRCA1,TP53"). + column: The single column (identifier type) to map to (e.g., "ENTREZID"). + keytype: The type of the provided keys (e.g., "SYMBOL"). + output_file: The path to save the mapping results as a TSV file. + multi_vals: How to handle multiple matches. One of "first", "list", "filter", "asNA". + + Returns: + A dictionary containing the command executed, logs, and the path to the output file. + """ + if not db_package: + raise ValueError("db_package must be a non-empty string.") + if not keys: + raise ValueError("keys must be a non-empty, comma-separated string.") + if not column: + raise ValueError("column must be a non-empty string.") + if not keytype: + raise ValueError("keytype must be a non-empty string.") + + valid_multi_vals = ["first", "list", "filter", "asNA", "character"] + if multi_vals not in valid_multi_vals: + raise ValueError(f"multi_vals must be one of {valid_multi_vals}") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + r_script_content = f""" + suppressPackageStartupMessages(library(AnnotationDbi)) + + db_package_name <- "{db_package}" + keys_vec <- unlist(strsplit("{keys}", ",")) + column_str <- "{column}" + keytype_str <- "{keytype}" + multi_vals_str <- "{multi_vals}" + output_file_path <- "{output_file.resolve()}" + + if (!requireNamespace(db_package_name, quietly = TRUE)) {{ + stop(paste("Annotation package '", db_package_name, "' is not installed. Please install it from Bioconductor."), call. = FALSE) + }} + db <- get(db_package_name) + + tryCatch({{ + results_vec <- AnnotationDbi::mapIds(db, + keys = keys_vec, + column = column_str, + keytype = keytype_str, + multiVals = multi_vals_str) + + # Convert named vector to a data frame for saving + results_df <- data.frame(FROM = names(results_vec), TO = I(results_vec), stringsAsFactors = FALSE) + + write.table(results_df, + file = output_file_path, + sep = "\\t", + row.names = FALSE, + col.names = TRUE, + quote = FALSE) + + cat(paste("Successfully wrote", nrow(results_df), "rows to", basename(output_file_path), "\\n")) + + }}, error = function(e) {{ + stop(paste("AnnotationDbi::mapIds failed:", e$message), call. = FALSE) + }}) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, encoding='utf-8') as tmp_script: + tmp_script.write(r_script_content) + script_path = tmp_script.name + + cmd = ["Rscript", script_path] + command_executed = f"Rscript {script_path}" + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file.resolve())] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"R script execution failed with exit code {e.returncode}", + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'Rscript' command not found. Please ensure R is installed and 'Rscript' is in your system's PATH.", + "error": "Dependency not found", + "output_files": [] + } + finally: + Path(script_path).unlink() \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotationdbi/app/bioconductor-annotationdbi_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotationdbi/app/bioconductor-annotationdbi_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ee8169da2029a5a5a0d643141e5f82570ef9c861 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotationdbi/app/bioconductor-annotationdbi_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotationdbi/app/bioconductor-annotationdbi_server.py') +SERVER_NAME = 'biosci_bioconductor_annotationdbi' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotationdbi/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotationdbi/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..5ffb2fbebfe206e4992e7f807130e3578bf3ea00 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotationdbi/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-annotationdbi: + build: . + image: mcp-bioconductor-annotationdbi:latest + container_name: mcp-bioconductor-annotationdbi + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-annotationdbi + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotationdbi/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotationdbi/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..219d52fcbc8c34ff46e974f7676c137182099e8a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotationdbi/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-annotationdbi + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotationdbi/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotationdbi/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotationdbi/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-apeglm/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-apeglm/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..57cd40f2416b347da5e546796f7f35bde99211bf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-apeglm/app/bioconductor-apeglm_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-apeglm/app/bioconductor-apeglm_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7031698a08086ed2e134d32b9a96ea026f4bf1a2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-apeglm/app/bioconductor-apeglm_server.py @@ -0,0 +1,125 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict, Any + +@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, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-apeglm/app/bioconductor-apeglm_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-apeglm/app/bioconductor-apeglm_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..98ef211f740bb65a8e6b686fef12adc84bf3d12b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-apeglm/app/bioconductor-apeglm_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-apeglm/app/bioconductor-apeglm_server.py') +SERVER_NAME = 'biosci_bioconductor_apeglm' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-apeglm/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-apeglm/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e15e303cb39aa7756cd707cc87115c9bf685830c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-apeglm/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-apeglm/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ebc2281a594f219239a61a4c8336c9dea78166b1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-apeglm/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-apeglm/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-apeglm/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-beachmat/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-beachmat/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e2d1ddf443e6b5ba969dbb4c0bd4f54e64efe2ee --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-beachmat/app/bioconductor-beachmat_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-beachmat/app/bioconductor-beachmat_server.py new file mode 100644 index 0000000000000000000000000000000000000000..74f22a203cf099726fe98e373d5958dac216e077 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-beachmat/app/bioconductor-beachmat_server.py @@ -0,0 +1,218 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict, Any + +@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" + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-beachmat/app/bioconductor-beachmat_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-beachmat/app/bioconductor-beachmat_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d30f6211ba29a34d1630ce4d54cf6d37c78f4f79 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-beachmat/app/bioconductor-beachmat_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-beachmat/app/bioconductor-beachmat_server.py') +SERVER_NAME = 'biosci_bioconductor_beachmat' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-beachmat/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-beachmat/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..1a3717e241b2cd27a16a8f9aa28e280a06f484e4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-beachmat/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-beachmat/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..02751f5276ca8f7f7c000952c3eb4b28cd1a78a6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-beachmat/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-beachmat/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-beachmat/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biobase/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biobase/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..036e2d732972382824401066de86773db43de86c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biobase/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.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-biobase via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-biobase -y && conda clean -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-biobase_server.py /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-biobase_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --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-biobase_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biobase/app/bioconductor-biobase_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biobase/app/bioconductor-biobase_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0760642f437e0b62049e09c1e0be4cd3c4628e7c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biobase/app/bioconductor-biobase_server.py @@ -0,0 +1,159 @@ +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 decorator is assumed to be available in the execution environment. +# No need to define or import it. + +@mcp.tool +def rscript_run( + 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: + """ + Executes an R script or R expressions using the Rscript command-line tool. + + This tool is a wrapper for Rscript, allowing the execution of R code from a + file or directly as string expressions. It is commonly used for running + bioinformatics scripts that rely on R and Bioconductor packages. + + Args: + script_file: Path to the R script file to be executed. + expressions: A list of R expressions to execute. Use this or script_file, not both. + script_args: A list of arguments to be passed to the R script itself. + verbose: If True, enables verbose output, printing progress information. + default_packages: A comma-separated string of package names to be loaded by default. + save: If True, the R workspace is saved at the end of the session (--save). + no_environ: If True, site and user environment files are not read (--no-environ). + no_site_file: If True, the site-wide Rprofile is not read (--no-site-file). + no_init_file: If True, the user's R profile is not read (--no-init-file). + restore: If True, previously saved objects are restored at startup (--restore). + vanilla: If True, combines --no-save, --no-restore, --no-site-file, + --no-init-file, and --no-environ. Overrides the individual flags. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # 1. Input Validation + if (script_file is None and not expressions) or (script_file is not None and expressions): + raise ValueError("You must provide either 'script_file' or 'expressions', but not both.") + + if script_file and not script_file.is_file(): + raise FileNotFoundError(f"The specified script file does not exist: {script_file}") + + # 2. Command Construction + cmd = ["Rscript"] + + if vanilla: + cmd.append("--vanilla") + else: + if save: + cmd.append("--save") + if no_environ: + cmd.append("--no-environ") + if no_site_file: + cmd.append("--no-site-file") + if no_init_file: + cmd.append("--no-init-file") + if restore: + cmd.append("--restore") + + if verbose: + cmd.append("--verbose") + + if default_packages: + cmd.append(f"--default-packages={default_packages}") + + if expressions: + for expr in expressions: + cmd.extend(["-e", expr]) + + if script_file: + cmd.append(str(script_file)) + + if script_args: + cmd.extend(script_args) + + command_executed = " ".join(cmd) + logger.info(f"Executing command: {command_executed}") + + # 3. 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": [] + } + except FileNotFoundError: + logger.error("Rscript not found. Please ensure R is installed and in your PATH.") + raise + except subprocess.CalledProcessError as e: + logger.error(f"Rscript execution failed with return code {e.returncode}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Rscript execution failed.", + "return_code": e.returncode, + "output_files": [] + } + +@mcp.tool +def rscript_version() -> dict: + """ + Retrieves the version of the Rscript interpreter. + + Returns: + A dictionary containing the executed command and the version information. + """ + cmd = ["Rscript", "--version"] + command_executed = " ".join(cmd) + logger.info(f"Executing command: {command_executed}") + + try: + # Rscript --version prints to stderr and exits with code 0. + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + } + except FileNotFoundError: + logger.error("Rscript not found. Please ensure R is installed and in your PATH.") + raise + except subprocess.CalledProcessError as e: + # This case is unlikely for Rscript --version but is good practice. + logger.error(f"Failed to get Rscript version. Return code: {e.returncode}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to retrieve Rscript version.", + "return_code": e.returncode, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biobase/app/bioconductor-biobase_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biobase/app/bioconductor-biobase_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c6ffc00939e6fa53c1e1a7b2b769be2d73cb5247 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biobase/app/bioconductor-biobase_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biobase/app/bioconductor-biobase_server.py') +SERVER_NAME = 'biosci_bioconductor_biobase' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biobase/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biobase/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7ab99455c1d5cc2a66cd0672bb717e7e20964491 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biobase/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-biobase: + build: . + image: mcp-bioconductor-biobase:latest + container_name: mcp-bioconductor-biobase + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-biobase + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biobase/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biobase/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..46fbc1523a52b2bd27837fce805cdd46303e15f1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biobase/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-biobase + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biobase/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biobase/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biobase/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocgenerics/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocgenerics/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7a2b64e38b21f9a17c0eed662d17a9ffec398d69 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocgenerics/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.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-biocgenerics via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-biocgenerics -y && conda clean -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-biocgenerics_server.py /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-biocgenerics_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --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-biocgenerics_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocgenerics/app/bioconductor-biocgenerics_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocgenerics/app/bioconductor-biocgenerics_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1e11d8460d5c1480e98207fcc450ce32e781875f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocgenerics/app/bioconductor-biocgenerics_server.py @@ -0,0 +1,148 @@ +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 from the MCP library. +def tool(func): + """A dummy decorator to mimic @mcp.tool() for standalone execution.""" + return func + +@tool +def rscript( + file: Optional[Path] = None, + expressions: Optional[List[str]] = None, + script_args: Optional[List[str]] = None, + version: bool = False, + verbose: bool = False, + default_packages: Optional[str] = None, + save: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: bool = False, + restore: bool = False, + vanilla: bool = False, +) -> Dict[str, Any]: + """ + Executes an R script or R expressions using the Rscript command-line tool. + + Rscript is the standard command-line interface for R, a core dependency for + Bioconductor packages. This tool allows for running R scripts or evaluating + R code directly. + + Args: + file: Path to an R script file to be executed. + expressions: A list of R expressions to evaluate. Use this instead of 'file'. + script_args: A list of arguments to be passed to the R script itself. + version: If True, print the R version and exit, ignoring other options. + verbose: If True, print information on progress. + default_packages: A comma-separated list of package names to be loaded by default. + save: If True, save the workspace at the end of the session. + no_environ: If True, do not read the site and user environment files. + no_site_file: If True, do not read the site-wide Rprofile. + no_init_file: If True, do not read the user R profile. + restore: If True, restore previously saved objects at startup. + vanilla: If True, combines --no-save, --no-restore, --no-site-file, + --no-init-file, and --no-environ. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # --- Command Construction --- + cmd = ["Rscript"] + + # If --version is requested, it's a special case. + # We run it and return immediately, ignoring all other parameters. + if version: + cmd.append("--version") + 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 FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Rscript failed with exit code {e.returncode}", + "output_files": [] + } + + # --- Input Validation for standard execution --- + # Either 'file' or 'expressions' must be provided, but not both. + file_provided = file is not None + expressions_provided = expressions is not None and len(expressions) > 0 + + if not (file_provided ^ expressions_provided): + raise ValueError("You must provide either the 'file' parameter or the 'expressions' parameter, but not both.") + + if file_provided: + if not file.is_file(): + raise FileNotFoundError(f"The specified R script file does not exist: {file}") + + # --- Build the full command --- + if verbose: + cmd.append("--verbose") + if default_packages: + cmd.append(f"--default-packages={default_packages}") + if save: + cmd.append("--save") + if no_environ: + cmd.append("--no-environ") + if no_site_file: + cmd.append("--no-site-file") + if no_init_file: + cmd.append("--no-init-file") + if restore: + cmd.append("--restore") + if vanilla: + cmd.append("--vanilla") + + if expressions_provided: + for expr in expressions: + cmd.extend(["-e", expr]) + + if file_provided: + cmd.append(str(file)) + + if script_args: + cmd.extend(script_args) + + # --- Subprocess Execution --- + command_str = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] # Rscript itself doesn't define output files; the script might. + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + # Return a structured error message for failed executions + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Rscript execution failed with exit code {e.returncode}", + "output_files": [] + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocgenerics/app/bioconductor-biocgenerics_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocgenerics/app/bioconductor-biocgenerics_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1ea07e3d419d1bb73c0603fc755f466386899009 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocgenerics/app/bioconductor-biocgenerics_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocgenerics/app/bioconductor-biocgenerics_server.py') +SERVER_NAME = 'biosci_bioconductor_biocgenerics' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocgenerics/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocgenerics/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..70411f1e7d442cee4491e9153313717c04073c2a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocgenerics/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-biocgenerics: + build: . + image: mcp-bioconductor-biocgenerics:latest + container_name: mcp-bioconductor-biocgenerics + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-biocgenerics + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocgenerics/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocgenerics/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..787c5a33b775733411e744e8efa96b3656b0a63c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocgenerics/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-biocgenerics + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocgenerics/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocgenerics/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocgenerics/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocneighbors/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocneighbors/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4cdc8c7e26e0a235c8ccaaa029b1ea7b48426fe9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocneighbors/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.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-biocneighbors via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-biocneighbors -y && conda clean -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-biocneighbors_server.py /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-biocneighbors_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --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-biocneighbors_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocneighbors/app/bioconductor-biocneighbors_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocneighbors/app/bioconductor-biocneighbors_server.py new file mode 100644 index 0000000000000000000000000000000000000000..887469d262cf6d0f608fa3ffa80c1d1d16565296 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocneighbors/app/bioconductor-biocneighbors_server.py @@ -0,0 +1,155 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union + +@mcp.tool() +def run_rscript( + r_script_file: Optional[Path] = None, + r_expressions: Optional[List[str]] = None, + additional_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, + print_help: bool = False, + print_version: bool = False, +) -> dict: + """ + Executes an R script file or R expressions using the Rscript command-line utility. + + This tool provides a comprehensive interface to the Rscript utility, enabling users + to run R code directly from the command line. It supports two primary modes of + operation: executing a specified R script file or running one or more R expressions + passed as strings. Additionally, it allows for the configuration of various R session + options, such as default package loading, workspace saving/restoring behavior, + and environment file handling. + + Args: + r_script_file: Path to an R script file (.R file) to be executed. This parameter + is mutually exclusive with `r_expressions`. If provided, the file + must exist. + r_expressions: A list of R code strings, where each string represents an + expression to be executed. Each expression will be passed to + Rscript using a separate '-e' flag. This parameter is mutually + exclusive with `r_script_file`. + additional_args: A list of strings representing extra arguments to be passed + to the R script or expressions being executed. These arguments + are typically accessible within the R script via `commandArgs()`. + verbose: If True, Rscript will print information on its progress during execution. + default_packages: A comma-separated string of R package names (e.g., "stats,utils") + that R should load by default. Alternatively, "NULL" can be + specified to prevent any default packages from loading. + save_workspace: If True, the R workspace will be saved at the end of the session. + no_environ: If True, R will not read the site-wide and user-specific environment + files (.Renviron). + no_site_file: If True, R will not read the site-wide R profile file (Rprofile.site). + no_init_file: If True, R will not read the user's R profile file (.Rprofile). + restore_workspace: If True, R will attempt to restore previously saved objects + from a workspace file (.RData) at startup. + vanilla: If True, Rscript will combine the effects of --no-save, --no-restore, + --no-site-file, --no-init-file, and --no-environ, providing a clean + R session. + print_help: If True, Rscript will print its usage information and exit. When this + is True, other execution options are typically ignored by Rscript. + print_version: If True, Rscript will print its version information and exit. When + this is True, other execution options are typically ignored by Rscript. + + Returns: + A dictionary containing the command executed, standard output, standard error, + and a list of any output files generated (typically empty for Rscript itself, + as output files are usually created by the R script being run). + Returns structured error information if the Rscript command fails or encounters + an execution error. + """ + command: List[str] = ["Rscript"] + output_files: List[Path] = [] + + # Handle --help and --version flags first, as they typically cause Rscript to exit immediately. + if print_help: + command.append("--help") + elif print_version: + command.append("--version") + else: + # Validate mutually exclusive input modes: r_script_file vs. r_expressions + if r_script_file and r_expressions: + raise ValueError("Cannot specify both 'r_script_file' and 'r_expressions'. Please choose one mode of execution.") + if not r_script_file and not r_expressions: + raise ValueError("Either 'r_script_file' or 'r_expressions' must be provided to execute R code.") + + # Add the R script file or expressions to the command + if r_script_file: + if not r_script_file.is_file(): + raise FileNotFoundError(f"R script file not found at the specified path: {r_script_file}") + command.append(str(r_script_file)) + elif r_expressions: + for expr in r_expressions: + command.extend(["-e", expr]) + + # Add general Rscript options + if verbose: + command.append("--verbose") + if default_packages is not None: + command.append(f"--default-packages={default_packages}") + + # Add R session options + if save_workspace: + command.append("--save") + if no_environ: + command.append("--no-environ") + if no_site_file: + command.append("--no-site-file") + if no_init_file: + command.append("--no-init-file") + if restore_workspace: + command.append("--restore") + if vanilla: + command.append("--vanilla") + + # Add any additional arguments to be passed to the R script + if additional_args: + command.extend(additional_args) + + try: + # Execute the Rscript command + process = subprocess.run( + command, + check=True, # Raise CalledProcessError for non-zero exit codes + capture_output=True, # Capture stdout and stderr + text=True, # Decode stdout and stderr as text + encoding='utf-8' # Specify encoding for consistent text handling + ) + + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files, + } + except FileNotFoundError: + # Handle case where 'Rscript' command itself is not found in PATH + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: 'Rscript' command not found. Please ensure R is installed and accessible in your system's PATH.", + "output_files": [], + } + except subprocess.CalledProcessError as e: + # Handle errors reported by Rscript (non-zero exit code) + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + except Exception as e: + # Catch any other unexpected errors during execution + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": f"An unexpected error occurred during Rscript execution: {str(e)}", + "output_files": [], + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocneighbors/app/bioconductor-biocneighbors_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocneighbors/app/bioconductor-biocneighbors_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9d5352a5c422b42808c38fcc1f414dacc6784f3a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocneighbors/app/bioconductor-biocneighbors_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocneighbors/app/bioconductor-biocneighbors_server.py') +SERVER_NAME = 'biosci_bioconductor_biocneighbors' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocneighbors/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocneighbors/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..2a76ad0e73e8868ef81968583d407d15c3dcf99c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocneighbors/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-biocneighbors: + build: . + image: mcp-bioconductor-biocneighbors:latest + container_name: mcp-bioconductor-biocneighbors + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-biocneighbors + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocneighbors/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocneighbors/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ca4a426d4d1955490a5931118107ef1e6defbf17 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocneighbors/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-biocneighbors + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocneighbors/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocneighbors/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocneighbors/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocparallel/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocparallel/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3889c91481bf1407e096bbf1fe1a4c95a424ee92 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocparallel/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.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-biocparallel via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-biocparallel -y && conda clean -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-biocparallel_server.py /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-biocparallel_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --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-biocparallel_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocparallel/app/bioconductor-biocparallel_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocparallel/app/bioconductor-biocparallel_server.py new file mode 100644 index 0000000000000000000000000000000000000000..cf8902bf007e8eb9d0e9f394c52e4f4df8a3abdb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocparallel/app/bioconductor-biocparallel_server.py @@ -0,0 +1,265 @@ +import subprocess +import tempfile +import os +from pathlib import Path +from typing import Optional, List, Literal, Union + +@mcp.tool() +def bplapply( + x_expr: str, + fun_expr: str, + workers: int = 2, + backend_type: Literal["MulticoreParam", "SnowParam", "SerialParam"] = "MulticoreParam", + tasks: int = 0, + stop_on_error: bool = True, + input_rds: Optional[str] = None, + output_rds: Optional[str] = None, +): + """ + Parallel version of lapply using BiocParallel. + + Args: + x_expr: R expression representing the list or vector to iterate over (e.g., '1:100'). + fun_expr: R expression for the function to apply (e.g., 'function(i) { Sys.sleep(0.1); i^2 }'). + workers: Number of parallel workers. + backend_type: The BiocParallel backend to use. + tasks: Number of tasks (0 for default). + stop_on_error: Whether to stop execution if an error occurs in a worker. + input_rds: Optional path to an RDS file containing the input data. If provided, x_expr is ignored. + output_rds: Optional path to save the result as an RDS file. + """ + if workers < 1: + workers = 1 + + # Construct R script + r_script = [ + "library(BiocParallel)", + f"param <- {backend_type}(workers = {workers}, tasks = {tasks}, stop.on.error = {str(stop_on_error).upper()})" + ] + + if input_rds: + input_path = Path(input_rds) + if not input_path.exists(): + return {"error": f"Input RDS file not found: {input_rds}"} + r_script.append(f"X <- readRDS('{input_path.absolute()}')") + else: + r_script.append(f"X <- {x_expr}") + + r_script.append(f"FUN <- {fun_expr}") + r_script.append("res <- bplapply(X, FUN, BPPARAM = param)") + + if output_rds: + output_path = Path(output_rds) + r_script.append(f"saveRDS(res, '{output_path.absolute()}')") + else: + r_script.append("print(res)") + + return _run_r_command("\n".join(r_script)) + +@mcp.tool() +def bpmapply( + fun_expr: str, + dots_expr: str, + workers: int = 2, + backend_type: Literal["MulticoreParam", "SnowParam", "SerialParam"] = "MulticoreParam", + more_args_expr: str = "list()", + input_rds: Optional[str] = None, +): + """ + Parallel version of mapply (multivariate apply) using BiocParallel. + + Args: + fun_expr: R expression for the function to apply. + dots_expr: R expression for the arguments to pass to FUN (e.g., 'list(1:3, 4:6)'). + workers: Number of parallel workers. + backend_type: The BiocParallel backend to use. + more_args_expr: R expression for additional arguments to FUN. + input_rds: Optional path to an RDS file containing a list of arguments. + """ + r_script = [ + "library(BiocParallel)", + f"param <- {backend_type}(workers = {workers})" + ] + + if input_rds: + input_path = Path(input_rds) + if not input_path.exists(): + return {"error": f"Input RDS file not found: {input_rds}"} + r_script.append(f"args_list <- readRDS('{input_path.absolute()}')") + r_script.append(f"res <- do.call(bpmapply, c(list(FUN = {fun_expr}, MoreArgs = {more_args_expr}, BPPARAM = param), args_list))") + else: + r_script.append(f"res <- bpmapply({fun_expr}, {dots_expr}, MoreArgs = {more_args_expr}, BPPARAM = param)") + + r_script.append("print(res)") + return _run_r_command("\n".join(r_script)) + +@mcp.tool() +def bpvec( + x_expr: str, + fun_expr: str, + workers: int = 2, + backend_type: Literal["MulticoreParam", "SnowParam", "SerialParam"] = "MulticoreParam", + input_rds: Optional[str] = None, +): + """ + Parallel version of vec (vectorized apply) using BiocParallel. + Useful when the function can handle chunks of the vector at once. + """ + r_script = [ + "library(BiocParallel)", + f"param <- {backend_type}(workers = {workers})" + ] + + if input_rds: + input_path = Path(input_rds) + if not input_path.exists(): + return {"error": f"Input RDS file not found: {input_rds}"} + r_script.append(f"X <- readRDS('{input_path.absolute()}')") + else: + r_script.append(f"X <- {x_expr}") + + r_script.append(f"res <- bpvec(X, {fun_expr}, BPPARAM = param)") + r_script.append("print(res)") + return _run_r_command("\n".join(r_script)) + +@mcp.tool() +def bpaggregate( + x_expr: str, + by_expr: str, + fun_expr: str, + workers: int = 2, + backend_type: Literal["MulticoreParam", "SnowParam", "SerialParam"] = "MulticoreParam", +): + """ + Parallel version of aggregate using BiocParallel. + + Args: + x_expr: R expression for the data object. + by_expr: R expression for the grouping elements. + fun_expr: R expression for the function to apply. + workers: Number of workers. + backend_type: Parallel backend. + """ + r_script = [ + "library(BiocParallel)", + f"param <- {backend_type}(workers = {workers})", + f"res <- bpaggregate({x_expr}, {by_expr}, {fun_expr}, BPPARAM = param)", + "print(res)" + ] + return _run_r_command("\n".join(r_script)) + +@mcp.tool() +def bpiterate( + iter_expr: str, + fun_expr: str, + workers: int = 2, + backend_type: Literal["SnowParam", "MulticoreParam"] = "SnowParam", + reduce_expr: Optional[str] = None, + init_expr: Optional[str] = None, +): + """ + Parallel iteration over an indeterminate number of elements using an iterator. + + Args: + iter_expr: R expression for the iterator function (should return NULL when finished). + fun_expr: R expression for the function to apply to each element. + workers: Number of workers. + backend_type: Parallel backend. + reduce_expr: Optional R expression for a reduction function. + init_expr: Optional R expression for the initial value for reduction. + """ + r_script = [ + "library(BiocParallel)", + f"param <- {backend_type}(workers = {workers})", + f"ITER <- {iter_expr}", + f"FUN <- {fun_expr}" + ] + + cmd = "res <- bpiterate(ITER, FUN" + if reduce_expr: + cmd += f", REDUCE = {reduce_expr}" + if init_expr: + cmd += f", init = {init_expr}" + cmd += ", BPPARAM = param)" + + r_script.append(cmd) + r_script.append("print(res)") + + return _run_r_command("\n".join(r_script)) + +@mcp.tool() +def bpworkers( + backend_type: Literal["MulticoreParam", "SnowParam", "SerialParam"] = "MulticoreParam" +): + """ + Query the number of available workers for a specific BiocParallel backend. + """ + r_script = [ + "library(BiocParallel)", + f"param <- {backend_type}()", + "cat(bpworkers(param))" + ] + return _run_r_command("\n".join(r_script)) + +@mcp.tool() +def bpvalidate( + code_snippet: str +): + """ + Validates if a specific R code snippet can be parallelized without errors. + Checks for global variable availability and serialization issues. + """ + r_script = [ + "library(BiocParallel)", + "tryCatch({", + f" expr <- quote({{ {code_snippet} }})", + " bpvalidate(expr)", + " cat('Validation successful')", + "}, error = function(e) {", + " cat('Validation failed:', e$message)", + "})" + ] + return _run_r_command("\n".join(r_script)) + +def _run_r_command(r_code: str): + """ + Helper function to execute R code via Rscript. + """ + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(r_code) + tmp_path = tmp.name + + try: + # Check if Rscript is available + subprocess.run(["Rscript", "--version"], capture_output=True, check=True) + + # Execute the script + result = subprocess.run( + ["Rscript", tmp_path], + capture_output=True, + text=True, + check=True + ) + + return { + "command_executed": f"Rscript {tmp_path}", + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript {tmp_path}", + "stdout": e.stdout, + "stderr": e.stderr, + "status": "error", + "error_message": str(e) + } + except FileNotFoundError: + return { + "status": "error", + "error_message": "Rscript not found. Please ensure R is installed and in your PATH." + } + finally: + if os.path.exists(tmp_path): + os.remove(tmp_path) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocparallel/app/bioconductor-biocparallel_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocparallel/app/bioconductor-biocparallel_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..365e908a59eb579dfe504c2b741d3d5e38379d61 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocparallel/app/bioconductor-biocparallel_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocparallel/app/bioconductor-biocparallel_server.py') +SERVER_NAME = 'biosci_bioconductor_biocparallel' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocparallel/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocparallel/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c703a49304f38194f6f715e8d6331b09c68f0efe --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocparallel/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-biocparallel: + build: . + image: mcp-bioconductor-biocparallel:latest + container_name: mcp-bioconductor-biocparallel + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-biocparallel + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocparallel/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocparallel/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9eff9f9d36cb8cda31d024a072cd5d4682ce6c01 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocparallel/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-biocparallel + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocparallel/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocparallel/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocparallel/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocsingular/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocsingular/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..dc043c8fcb94e3e8d18677417f0b4e0922ffc3f6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocsingular/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.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-biocsingular via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-biocsingular -y && conda clean -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-biocsingular_server.py /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-biocsingular_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --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-biocsingular_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocsingular/app/bioconductor-biocsingular_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocsingular/app/bioconductor-biocsingular_server.py new file mode 100644 index 0000000000000000000000000000000000000000..90c67d690984693cf5c0042bff7c64d944b44ab3 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocsingular/app/bioconductor-biocsingular_server.py @@ -0,0 +1,216 @@ +import subprocess +import os +from pathlib import Path +from typing import Optional, List, Dict, Any + +@mcp.tool() +def biocsingular_run_svd( + input_path: str, + output_prefix: str, + k: int = 5, + nu: int = 5, + nv: int = 5, + algorithm: str = "Irlba", + center: bool = True, + scale: bool = False, + deferred: bool = False, +) -> Dict[str, Any]: + """ + Perform Singular Value Decomposition (SVD) on a matrix using BiocSingular. + Supports various algorithms including Exact, Irlba, and Random SVD. + + Args: + input_path: Path to the input matrix file (CSV, TSV, or RDS format). + output_prefix: Prefix for the output files (will create .rds and .csv files). + k: Number of singular values to compute. + nu: Number of left singular vectors to compute. + nv: Number of right singular vectors to compute. + algorithm: SVD algorithm to use ('Exact', 'Irlba', 'Random', 'FastDot'). + center: Whether to center the columns of the matrix. + scale: Whether to scale the columns of the matrix. + deferred: Whether to use deferred centering and scaling (memory efficient). + """ + input_file = Path(input_path) + if not input_file.exists(): + return {"error": f"Input file not found: {input_path}"} + + # Validate algorithm + valid_algos = ["Exact", "Irlba", "Random", "FastDot"] + if algorithm not in valid_algos: + return {"error": f"Invalid algorithm. Must be one of: {', '.join(valid_algos)}"} + + # Construct R script + r_script = f""" + library(BiocSingular) + + # Load data + ext <- tolower(tools::file_ext("{input_path}")) + if (ext == "rds") {{ + mat <- readRDS("{input_path}") + }} else if (ext == "csv") {{ + mat <- as.matrix(read.csv("{input_path}", row.names=1)) + }} else {{ + mat <- as.matrix(read.table("{input_path}", sep="\\t", header=TRUE, row.names=1)) + }} + + # Set parameter object + param <- {algorithm}Param(deferred = {"TRUE" if deferred else "FALSE"}) + + # Run SVD + res <- runSVD( + mat, + k = {k}, + nu = {nu}, + nv = {nv}, + BSPARAM = param, + center = {"TRUE" if center else "FALSE"}, + scale = {"TRUE" if scale else "FALSE"} + ) + + # Save results + saveRDS(res, "{output_prefix}_svd.rds") + write.csv(res$u, "{output_prefix}_u.csv") + write.csv(res$v, "{output_prefix}_v.csv") + write.csv(data.frame(d=res$d), "{output_prefix}_d.csv") + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + + output_files = [ + f"{output_prefix}_svd.rds", + f"{output_prefix}_u.csv", + f"{output_prefix}_v.csv", + f"{output_prefix}_d.csv" + ] + + return { + "command_executed": f"BiocSingular::runSVD via Rscript", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(Path(f).absolute()) for f in output_files if Path(f).exists()] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def biocsingular_run_pca( + input_path: str, + output_prefix: str, + rank: int = 5, + algorithm: str = "Irlba", + center: bool = True, + scale: bool = False, + deferred: bool = False, +) -> Dict[str, Any]: + """ + Perform Principal Component Analysis (PCA) on a matrix using BiocSingular. + Optimized for large-scale genomic data. + + Args: + input_path: Path to the input matrix file (CSV, TSV, or RDS format). + output_prefix: Prefix for the output files. + rank: Number of principal components to compute. + algorithm: PCA algorithm to use ('Exact', 'Irlba', 'Random', 'FastDot'). + center: Whether to center the columns. + scale: Whether to scale the columns. + deferred: Whether to use deferred centering and scaling. + """ + input_file = Path(input_path) + if not input_file.exists(): + return {"error": f"Input file not found: {input_path}"} + + valid_algos = ["Exact", "Irlba", "Random", "FastDot"] + if algorithm not in valid_algos: + return {"error": f"Invalid algorithm. Must be one of: {', '.join(valid_algos)}"} + + r_script = f""" + library(BiocSingular) + + # Load data + ext <- tolower(tools::file_ext("{input_path}")) + if (ext == "rds") {{ + mat <- readRDS("{input_path}") + }} else if (ext == "csv") {{ + mat <- as.matrix(read.csv("{input_path}", row.names=1)) + }} else {{ + mat <- as.matrix(read.table("{input_path}", sep="\\t", header=TRUE, row.names=1)) + }} + + # Set parameter object + param <- {algorithm}Param(deferred = {"TRUE" if deferred else "FALSE"}) + + # Run PCA + res <- runPCA( + mat, + rank = {rank}, + BSPARAM = param, + center = {"TRUE" if center else "FALSE"}, + scale = {"TRUE" if scale else "FALSE"} + ) + + # Save results + saveRDS(res, "{output_prefix}_pca.rds") + write.csv(res$x, "{output_prefix}_pcs.csv") + write.csv(res$rotation, "{output_prefix}_loadings.csv") + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + + output_files = [ + f"{output_prefix}_pca.rds", + f"{output_prefix}_pcs.csv", + f"{output_prefix}_loadings.csv" + ] + + return { + "command_executed": f"BiocSingular::runPCA via Rscript", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(Path(f).absolute()) for f in output_files if Path(f).exists()] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def biocsingular_get_info() -> Dict[str, Any]: + """ + Check if BiocSingular is installed and return version information. + """ + r_script = "library(BiocSingular); cat(as.character(packageVersion('BiocSingular')))" + + try: + result = subprocess.run( + ["Rscript", "-e", r_script], + capture_output=True, + text=True, + check=True + ) + return { + "biocsingular_version": result.stdout.strip(), + "status": "installed" + } + except subprocess.CalledProcessError: + return { + "status": "not_found", + "error": "BiocSingular is not installed in the R environment." + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocsingular/app/bioconductor-biocsingular_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocsingular/app/bioconductor-biocsingular_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..afb1aaaaf718c06e2b84de3a05ff539382b51c2d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocsingular/app/bioconductor-biocsingular_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocsingular/app/bioconductor-biocsingular_server.py') +SERVER_NAME = 'biosci_bioconductor_biocsingular' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocsingular/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocsingular/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..291654c99584d5dc3b38c51c7ad55775aac18c3a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocsingular/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-biocsingular: + build: . + image: mcp-bioconductor-biocsingular:latest + container_name: mcp-bioconductor-biocsingular + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-biocsingular + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocsingular/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocsingular/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0df4768f7fb4bd8ff66c5c7dee9e78602b0872f0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocsingular/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-biocsingular + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocsingular/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocsingular/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biocsingular/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomart/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomart/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..79ad411e2a2130f33623e2ac97b8853e27d93630 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomart/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.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-biomart via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-biomart -y && conda clean -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-biomart_server.py /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-biomart_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --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-biomart_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomart/app/bioconductor-biomart_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomart/app/bioconductor-biomart_server.py new file mode 100644 index 0000000000000000000000000000000000000000..13e6cf0b7efef98523034671591ed36d34927ee3 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomart/app/bioconductor-biomart_server.py @@ -0,0 +1,157 @@ +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_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, + vanilla: bool = False, + save: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: bool = False, + restore: bool = False, +) -> dict: + """ + Executes an R script or R expressions using Rscript. + + This tool serves as a wrapper around the Rscript command-line utility, + allowing for the execution of R code from a file or directly as expressions. + It provides control over the R session's environment and startup behavior. + + Args: + script_file: Path to the R script file to be executed. + expressions: A list of R expressions to execute. Use this or 'script_file', but not both. + script_args: A list of arguments to be passed to the R script itself. + verbose: If True, prints more information on progress. + default_packages: A comma-separated list of package names to be loaded by default. + vanilla: If True, combines --no-save, --no-restore, --no-site-file, --no-init-file, and --no-environ. + If set to True, the individual flags (save, no_environ, etc.) are ignored. + save: If True, saves the workspace at the end of the session. Ignored if 'vanilla' is True. + no_environ: If True, does not read site and user environment files. Ignored if 'vanilla' is True. + no_site_file: If True, does not read the site-wide Rprofile. Ignored if 'vanilla' is True. + no_init_file: If True, does not read the user R profile. Ignored if 'vanilla' is True. + restore: If True, restores previously saved objects at startup. Ignored if 'vanilla' is True. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # 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("Provide either 'script_file' or 'expressions', but not both.") + if script_file and not script_file.exists(): + raise FileNotFoundError(f"The specified script file does not exist: {script_file}") + + command = ["Rscript"] + + # Add Rscript-specific options + if verbose: + command.append("--verbose") + if default_packages: + command.extend(["--default-packages", default_packages]) + + # Add R session options + if vanilla: + command.append("--vanilla") + else: + if save: + command.append("--save") + if no_environ: + command.append("--no-environ") + if no_site_file: + command.append("--no-site-file") + if no_init_file: + command.append("--no-init-file") + if restore: + command.append("--restore") + + # Add expressions or script file + if expressions: + for expr in expressions: + command.extend(["-e", expr]) + elif script_file: + command.append(str(script_file)) + + # Add arguments for the script itself + if script_args: + command.extend(script_args) + + command_str = " ".join(command) + + try: + result = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], # Rscript itself doesn't define output files; the script might. + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Rscript execution failed with return code {e.returncode}", + "output_files": [], + } + + +@mcp.tool() +def get_rscript_version() -> dict: + """ + Retrieves the version of the Rscript interpreter. + + This function executes 'Rscript --version' to get version information + about the R installation. + + Returns: + A dictionary containing the executed command, stdout, and stderr. + """ + command = ["Rscript", "--version"] + command_str = " ".join(command) + + try: + result = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Rscript version check failed with return code {e.returncode}", + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomart/app/bioconductor-biomart_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomart/app/bioconductor-biomart_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d8e489ca604400496c118eb94d28857f97922e6d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomart/app/bioconductor-biomart_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomart/app/bioconductor-biomart_server.py') +SERVER_NAME = 'biosci_bioconductor_biomart' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomart/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomart/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..28b0d67e45352a76a21edffbb689ba52089af958 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomart/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-biomart: + build: . + image: mcp-bioconductor-biomart:latest + container_name: mcp-bioconductor-biomart + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-biomart + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomart/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomart/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..91792aaa37ed9b8c73981f4630c068f11ca0c2c2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomart/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-biomart + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomart/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomart/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomart/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomformat/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomformat/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9421f7ac6a878b4b1b6b7db6f6b3aee6be5ab144 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomformat/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-biomformat via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-biomformat -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-biomformat_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-biomformat_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-biomformat_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomformat/app/bioconductor-biomformat_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomformat/app/bioconductor-biomformat_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f0c6ea0723d83a9011e2784d36a93eccd30fcfae --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomformat/app/bioconductor-biomformat_server.py @@ -0,0 +1,181 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, Dict, Any, List + +# --- Internal R Script Definitions --- +# These R scripts act as command-line wrappers for the biomformat R package functions. +# In a real-world scenario, these might be pre-existing R scripts or part of a larger R package. + +_READ_BIOM_R_SCRIPT = """ +# R script to read a BIOM file and save the R object as an RDS file. +suppressPackageStartupMessages(library(biomformat)) + +args <- commandArgs(trailingOnly = TRUE) + +if (length(args) < 2) { + stop("Usage: read_biom_wrapper.R ") +} + +input_file <- args[1] +output_rds_file <- args[2] + +tryCatch({ + biom_obj <- read_biom(input_file) + saveRDS(biom_obj, file = output_rds_file) + cat(paste("Successfully read BIOM file '", input_file, "' and saved R object to '", output_rds_file, "'\\n", sep="")) +}, error = function(e) { + stop(paste("Error reading BIOM file '", input_file, "': ", e$message, sep="")) +}) +""" + +_WRITE_BIOM_R_SCRIPT = """ +# R script to read an R object from an RDS file and write it to a BIOM file. +suppressPackageStartupMessages(library(biomformat)) + +args <- commandArgs(trailingOnly = TRUE) + +if (length(args) < 2) { + stop("Usage: write_biom_wrapper.R ") +} + +input_rds_file <- args[1] +output_biom_file <- args[2] + +tryCatch({ + biom_obj <- readRDS(input_rds_file) + write_biom(biom_obj, output_biom_file) + cat(paste("Successfully wrote R object from '", input_rds_file, "' to BIOM file '", output_biom_file, "'\\n", sep="")) +}, error = function(e) { + stop(paste("Error writing BIOM file '", output_biom_file, "': ", e$message, sep="")) +}) +""" + +# --- Helper Function for R Script Execution --- + +def _execute_r_script(script_content: str, args: List[str]) -> Dict[str, Any]: + """ + Helper function to execute an R script with given arguments. + Writes the R script content to a temporary file and executes it using Rscript. + """ + temp_r_script_path: Optional[Path] = None + try: + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R") as temp_r_script: + temp_r_script.write(script_content) + temp_r_script_path = Path(temp_r_script.name) + + command = ["Rscript", str(temp_r_script_path)] + args + + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [] # This will be populated by the calling MCP tool function + } + 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) if 'command' in locals() else "Rscript not found", + "stdout": "", + "stderr": "Error: Rscript command not found. Please ensure R is installed and Rscript is in your PATH.", + "error": "Rscript not found", + "output_files": [] + } + finally: + # Clean up the temporary R script file + if temp_r_script_path and temp_r_script_path.exists(): + temp_r_script_path.unlink() + + +# --- MCP Tool Definitions --- + +# @mcp.tool() +def read_biom_file( + input_biom_path: Path, + output_rds_path: Path, +) -> Dict[str, Any]: + """ + Reads a BIOM format file and converts it into an R object saved as an RDS file. + + This tool wraps the `read_biom` function from the `biomformat` R package. + NOTE: This implementation is based on a hypothetical R wrapper script + due to the lack of direct command-line documentation for the R package. + + Args: + input_biom_path: Path to the input BIOM format file. + output_rds_path: Path where the R object (RDS format) will be saved. + + Returns: + A dictionary containing execution details, stdout, stderr, and output files. + """ + # Input validation + if not input_biom_path.is_file(): + raise FileNotFoundError(f"Input BIOM file not found: {input_biom_path}") + + # Ensure parent directory for output exists + output_rds_path.parent.mkdir(parents=True, exist_ok=True) + + # Prepare arguments for the R script + r_args = [str(input_biom_path), str(output_rds_path)] + + # Execute the R script + result = _execute_r_script(_READ_BIOM_R_SCRIPT, r_args) + + # Add output file to the result if successful and no error occurred + if "error" not in result and output_rds_path.is_file(): + result["output_files"].append(str(output_rds_path)) + + return result + + +# @mcp.tool() +def write_biom_file( + input_rds_path: Path, + output_biom_path: Path, +) -> Dict[str, Any]: + """ + Writes an R object (from an RDS file) into a BIOM format file. + + This tool wraps the `write_biom` function from the `biomformat` R package. + NOTE: This implementation is based on a hypothetical R wrapper script + due to the lack of direct command-line documentation for the R package. + + Args: + input_rds_path: Path to the input R object (RDS format) file. + output_biom_path: Path where the BIOM format file will be saved. + + Returns: + A dictionary containing execution details, stdout, stderr, and output files. + """ + # Input validation + if not input_rds_path.is_file(): + raise FileNotFoundError(f"Input RDS file not found: {input_rds_path}") + + # Ensure parent directory for output exists + output_biom_path.parent.mkdir(parents=True, exist_ok=True) + + # Prepare arguments for the R script + r_args = [str(input_rds_path), str(output_biom_path)] + + # Execute the R script + result = _execute_r_script(_WRITE_BIOM_R_SCRIPT, r_args) + + # Add output file to the result if successful and no error occurred + if "error" not in result and output_biom_path.is_file(): + result["output_files"].append(str(output_biom_path)) + + return result \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomformat/app/bioconductor-biomformat_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomformat/app/bioconductor-biomformat_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ebc7ccd75139e806a75b42bd10758cc0eea7028f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomformat/app/bioconductor-biomformat_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomformat/app/bioconductor-biomformat_server.py') +SERVER_NAME = 'biosci_bioconductor_biomformat' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomformat/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomformat/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomformat/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomformat/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomformat/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..86cabcccd9eb81b29a1a10145f27a8e36bbd6602 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomformat/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-biomformat: + build: . + image: mcp-bioconductor-biomformat:latest + container_name: mcp-bioconductor-biomformat + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-biomformat + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomformat/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomformat/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4ec0abb2d3fc1c760f68917798e92c1f2f3e5bd7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomformat/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-biomformat + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomformat/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomformat/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biomformat/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biostrings/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biostrings/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..04502dc2af170c29e07379c364d485a2b0cea7b8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biostrings/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.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-biostrings via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-biostrings -y && conda clean -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-biostrings_server.py /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-biostrings_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --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-biostrings_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biostrings/app/bioconductor-biostrings_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biostrings/app/bioconductor-biostrings_server.py new file mode 100644 index 0000000000000000000000000000000000000000..244c611111dc935cf10e298964e791a667a42b30 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biostrings/app/bioconductor-biostrings_server.py @@ -0,0 +1,136 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, List, Dict, Any + +# Mock the decorator for standalone execution +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +@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, + vanilla: bool = False, + save: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: bool = False, + restore: bool = False, +) -> Dict[str, Any]: + """ + Executes an R script or R expressions using the Rscript command-line tool. + + This tool serves as a wrapper for Rscript, allowing for the execution of R code + from a file or directly from string expressions. It mirrors the functionality + provided by `Rscript --help`. + + Args: + script_file: Path to the R script file to be executed. Mutually exclusive with 'expressions'. + expressions: A list of R expressions to be executed. Mutually exclusive with 'script_file'. + script_args: A list of arguments to be passed to the R script itself. + verbose: If True, enables verbose output, printing information on progress. + default_packages: A comma-separated string of package names to be loaded by default. + vanilla: If True, combines --no-save, --no-restore, --no-site-file, --no-init-file, and --no-environ. + If set, it overrides the individual flags (save, restore, etc.). + save: If True, the workspace is saved at the end of the session. Ignored if 'vanilla' is True. + no_environ: If True, site and user environment files are not read. Ignored if 'vanilla' is True. + no_site_file: If True, the site-wide Rprofile is not read. Ignored if 'vanilla' is True. + no_init_file: If True, the user's R profile is not read. Ignored if 'vanilla' is True. + restore: If True, previously saved objects are restored at startup. Ignored if 'vanilla' is True. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files (always empty). + """ + # 1. Input Validation + if not script_file and not expressions: + raise ValueError("Either 'script_file' or 'expressions' must be provided.") + if script_file and expressions: + raise ValueError("'script_file' and 'expressions' are mutually exclusive and cannot be used together.") + if script_file and not script_file.is_file(): + raise FileNotFoundError(f"The specified script file does not exist: {script_file}") + if expressions and not expressions: + raise ValueError("'expressions' list cannot be empty if provided.") + + # 2. Command Construction + cmd = ["Rscript"] + + if verbose: + cmd.append("--verbose") + + if default_packages: + cmd.extend(["--default-packages", default_packages]) + + if vanilla: + cmd.append("--vanilla") + else: + # These options are combined and handled by the --vanilla flag in Rscript + if save: + cmd.append("--save") + if no_environ: + cmd.append("--no-environ") + if no_site_file: + cmd.append("--no-site-file") + if no_init_file: + cmd.append("--no-init-file") + if restore: + cmd.append("--restore") + + # Add expressions or script file to the command + if expressions: + for expr in expressions: + cmd.extend(["-e", expr]) + elif script_file: + cmd.append(str(script_file)) + + # Add arguments for the R script itself + if script_args: + cmd.extend(script_args) + + command_str = " ".join(cmd) + logging.info(f"Executing command: {command_str}") + + # 3. Subprocess Execution and Error Handling + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + stdout = result.stdout + stderr = result.stderr + except FileNotFoundError: + # This error occurs if 'Rscript' is not in the system's PATH + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: 'Rscript' command not found. Please ensure R is installed and accessible in your system's PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + # This error occurs if the R script itself fails (non-zero exit code) + logging.error(f"Rscript execution failed with return code {e.returncode}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + # 4. Structured Result Return + # Rscript itself does not have a dedicated output file parameter. Any files + # created are determined by the R code within the script. + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": stderr, + "output_files": [] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biostrings/app/bioconductor-biostrings_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biostrings/app/bioconductor-biostrings_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..71d9091746b506f4a3e3901f281dfce4854f2430 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biostrings/app/bioconductor-biostrings_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biostrings/app/bioconductor-biostrings_server.py') +SERVER_NAME = 'biosci_bioconductor_biostrings' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biostrings/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biostrings/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..04cc0ec4df0b6b32962f9077038c73df1dbbfe47 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biostrings/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-biostrings: + build: . + image: mcp-bioconductor-biostrings:latest + container_name: mcp-bioconductor-biostrings + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-biostrings + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biostrings/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biostrings/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..45c3e252d78ba0fbedb6d8c87e58e82896f73d44 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biostrings/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-biostrings + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biostrings/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biostrings/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-biostrings/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-bsgenome/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-bsgenome/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e92d90bc32975c5c742f867f85094b60f17d393d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-bsgenome/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-bsgenome via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-bsgenome -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-bsgenome_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-bsgenome_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-bsgenome_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-bsgenome/app/bioconductor-bsgenome_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-bsgenome/app/bioconductor-bsgenome_server.py new file mode 100644 index 0000000000000000000000000000000000000000..588b7a281f58ec1138351f0da97d519f7db6badf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-bsgenome/app/bioconductor-bsgenome_server.py @@ -0,0 +1,204 @@ +import subprocess +import tempfile +import shutil +import re +from pathlib import Path +from typing import Optional, List + +# This is a placeholder for the actual decorator. +# In a real MCP environment, you would use `@mcp.tool()`. +def mcp_tool_placeholder(*args, **kwargs): + def decorator(func): + return func + return decorator + +@mcp_tool_placeholder() +def forge_bsgenome_data_pkg( + organism: str, + common_name: str, + organism_abbreviation: str, + provider: str, + provider_version: str, + release_date: str, + package_version: str, + author: str, + maintainer: str, + seqs_srcdir: Path, + output_pkg_path: Path, + circ_seqs: Optional[List[str]] = None, + seqfiles_prefix: Optional[str] = None, + seqfiles_suffix: Optional[str] = None, + license_str: str = "Artistic-2.0", + title: Optional[str] = None, + description: Optional[str] = None, + organism_biocview: Optional[str] = None, +) -> dict: + """ + Creates a Bioconductor BSgenome data package from a set of FASTA files. + + This tool wraps the `forgeBSgenomeDataPkg` function from the R/Bioconductor + BSgenome package. It automates the creation of the necessary seed file and + executes an R script to build the package source directory, which is then + returned as a gzipped tarball. + + Args: + organism: Full organism name (e.g., "Homo sapiens"). + common_name: Common name for the organism (e.g., "Human"). + organism_abbreviation: Abbreviation for the organism, used in package naming (e.g., "Hsapiens"). + provider: Source of the genome data (e.g., "UCSC"). + provider_version: Version or build of the genome from the provider (e.g., "hg38"). + release_date: Release date of the genome build (e.g., "Dec. 2013"). + package_version: Version for the new BSgenome package, in X.Y.Z format (e.g., "1.0.0"). + author: The author of this BSgenome package. + maintainer: The maintainer of the package, including email (e.g., "Your Name "). + seqs_srcdir: Input directory containing the genome sequence files (e.g., FASTA files). + output_pkg_path: Path to save the final gzipped tarball of the package source (e.g., 'MyPackage.tar.gz'). + circ_seqs: Optional list of sequence names that are circular (e.g., ["chrM"]). + seqfiles_prefix: Optional prefix for the sequence files within `seqs_srcdir`. + seqfiles_suffix: Optional suffix for the sequence files (e.g., ".fa", ".fasta"). + license_str: The license for the generated package. + title: Optional title for the package. A default will be generated if not provided. + description: Optional description for the package. A default will be generated if not provided. + organism_biocview: Optional Bioconductor view term for the organism (e.g., "Homo_sapiens"). + + Returns: + A dictionary containing the execution details and path to the output file. + """ + # 1. Input Validation + if not seqs_srcdir.is_dir(): + raise ValueError(f"Input directory '{seqs_srcdir}' does not exist or is not a directory.") + if not re.match(r"^\d+\.\d+\.\d+$", package_version): + raise ValueError(f"Package version '{package_version}' is not in X.Y.Z format.") + for name_part in [organism_abbreviation, provider]: + if not name_part.isalnum(): + raise ValueError(f"Package name component '{name_part}' contains invalid characters. Use only alphanumerics.") + if not output_pkg_path.parent.exists(): + output_pkg_path.parent.mkdir(parents=True, exist_ok=True) + + # 2. Generate derived values + sanitized_provider_version = re.sub(r'[^a-zA-Z0-9.]', '', provider_version) + package_name = f"BSgenome.{organism_abbreviation}.{provider}.{sanitized_provider_version}" + bsgenome_objname = organism_abbreviation + + if title is None: + title = f"Full genome sequences for {organism} ({provider} version {provider_version})" + if description is None: + description = ( + f"Full genome sequences for {organism} ({common_name}) as provided by " + f"{provider} ({provider_version}, {release_date}) and stored in Biostrings objects." + ) + + organism_biocview_val = organism_biocview if organism_biocview else organism.replace(" ", "_") + + # 3. Create seed file content + seed_content = [ + f"Package: {package_name}", + f"Title: {title}", + f"Description: {description}", + f"Version: {package_version}", + f"Author: {author}", + f"Maintainer: {maintainer}", + f"License: {license_str}", + f"organism: {organism}", + f"common_name: {common_name}", + f"provider: {provider}", + f"provider_version: {provider_version}", + f"release_date: {release_date}", + f"BSgenomeObjname: {bsgenome_objname}", + f"organism_biocview: {organism_biocview_val}", + f"seqs_srcdir: {seqs_srcdir.resolve()}", + ] + + if circ_seqs: + r_vector = ', '.join(f'"{seq}"' for seq in circ_seqs) + seed_content.append(f"circ_seqs: c({r_vector})") + if seqfiles_prefix: + seed_content.append(f"seqfiles_prefix: {seqfiles_prefix}") + if seqfiles_suffix: + seed_content.append(f"seqfiles_suffix: {seqfiles_suffix}") + + seed_file_text = "\n".join(seed_content) + + # 4. Create R script + r_script_text = f""" + # Ensure BiocManager and BSgenome are installed + if (!requireNamespace("BiocManager", quietly = TRUE)) {{ + install.packages("BiocManager", repos="http://cran.us.r-project.org") + }} + if (!requireNamespace("BSgenome", quietly = TRUE)) {{ + BiocManager::install("BSgenome", update=FALSE, ask=FALSE) + }} + + library(BSgenome) + + # Forge the package + tryCatch({{ + forgeBSgenomeDataPkg(seed_file="seed.txt", destdir=".") + cat("BSgenome package '{package_name}' successfully forged.\\n") + }}, error = function(e) {{ + cat("Error during package forging:\\n") + cat(conditionMessage(e), "\\n") + quit(status = 1) + }}) + """ + + # 5. Execute in a temporary directory + with tempfile.TemporaryDirectory() as tmpdir: + work_dir = Path(tmpdir) + seed_file_path = work_dir / "seed.txt" + r_script_path = work_dir / "run_forge.R" + + seed_file_path.write_text(seed_file_text) + r_script_path.write_text(r_script_text) + + cmd = ["Rscript", str(r_script_path)] + command_executed = " ".join(cmd) + + try: + process = subprocess.run( + cmd, + cwd=work_dir, + check=True, + capture_output=True, + text=True, + encoding='utf-8', + ) + + # 6. Package the result + created_pkg_dir = work_dir / package_name + if not created_pkg_dir.is_dir(): + raise FileNotFoundError( + f"BSgenome package directory '{package_name}' was not created. " + f"Check R script output for errors.\nStderr: {process.stderr}" + ) + + archive_base_name = str(output_pkg_path.with_suffix('')) + archive_path_str = shutil.make_archive( + base_name=archive_base_name, + format='gztar', + root_dir=work_dir, + base_dir=package_name + ) + + final_archive_path = Path(archive_path_str) + if final_archive_path != output_pkg_path: + final_archive_path.rename(output_pkg_path) + + return { + "command_executed": command_executed, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {"bsgenome_package_archive": str(output_pkg_path)} + } + + except subprocess.CalledProcessError as e: + # Using .decode() in case the output is not valid utf-8 on error + stdout = e.stdout if isinstance(e.stdout, str) else e.stdout.decode('utf-8', errors='replace') + stderr = e.stderr if isinstance(e.stderr, str) else e.stderr.decode('utf-8', errors='replace') + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "error": "R script execution failed.", + "return_code": e.returncode, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-bsgenome/app/bioconductor-bsgenome_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-bsgenome/app/bioconductor-bsgenome_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d121d0271bb0d74837b8f03f16a2f8e47b553b0e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-bsgenome/app/bioconductor-bsgenome_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-bsgenome/app/bioconductor-bsgenome_server.py') +SERVER_NAME = 'biosci_bioconductor_bsgenome' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-bsgenome/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-bsgenome/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-bsgenome/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-bsgenome/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-bsgenome/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..a16172fc9d353b1fa84f3f1c445702f0bc06751b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-bsgenome/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-bsgenome: + build: . + image: mcp-bioconductor-bsgenome:latest + container_name: mcp-bioconductor-bsgenome + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-bsgenome + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-bsgenome/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-bsgenome/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1d3824d6847258fcb5b0a063d4a0c1268b07dfd8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-bsgenome/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-bsgenome + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-bsgenome/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-bsgenome/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-bsgenome/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-clustifyr/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-clustifyr/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..52ec0d803f99f7a08118a664f84fa502c5ecfe8e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-clustifyr/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.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-clustifyr via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-clustifyr -y && conda clean -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-clustifyr_server.py /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-clustifyr_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --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-clustifyr_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-clustifyr/app/bioconductor-clustifyr_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-clustifyr/app/bioconductor-clustifyr_server.py new file mode 100644 index 0000000000000000000000000000000000000000..12e5742f7983ae9ac3937d47c2bea39f9cb938d5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-clustifyr/app/bioconductor-clustifyr_server.py @@ -0,0 +1,119 @@ +import subprocess +import shlex +from pathlib import Path +from typing import Optional, List, Dict, Any + +# @mcp.tool() is a placeholder for the actual decorator in the MCP framework. +# The code is written to be compatible with it. + +@mcp.tool() +def clustifyr_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 using Rscript, for running Bioconductor packages like clustifyr. + + This tool serves as a wrapper around the Rscript command-line interpreter, + allowing the execution of R scripts that utilize the clustifyr library or other + Bioconductor packages. You can either provide an R script file or a list of + R expressions to execute. + + Args: + script_file: Path to the R script file to be executed. Mutually exclusive with 'expressions'. + expressions: A list of R expressions to execute. Mutually exclusive with 'script_file'. + script_args: A list of arguments to be passed to the R script itself. + verbose: If True, print information on progress. + default_packages: A comma-separated list of package names to be loaded by default (e.g., "clustifyr,Seurat"). + save: If True, save the workspace at the end of the session. Ignored if 'vanilla' is True. + no_environ: If True, do not read the site and user environment files. Ignored if 'vanilla' is True. + no_site_file: If True, do not read the site-wide Rprofile. Ignored if 'vanilla' is True. + no_init_file: If True, do not read the user R profile. Ignored if 'vanilla' is True. + restore: If True, restore previously saved objects at startup. Ignored if 'vanilla' is True. + vanilla: If True, combines --no-save, --no-restore, --no-site-file, --no-init-file, and --no-environ. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + Note: Output files are not automatically detected and must be known from the R script's logic. + """ + # 1. Input Validation + if not script_file and not expressions: + raise ValueError("Either 'script_file' or 'expressions' must be provided.") + if script_file and expressions: + raise ValueError("'script_file' and 'expressions' are mutually exclusive 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}") + + # 2. Command Construction + cmd = ["Rscript"] + + # The --vanilla option is a shortcut for several other flags. + if vanilla: + cmd.append("--vanilla") + else: + if save: + cmd.append("--save") + if no_environ: + cmd.append("--no-environ") + if no_site_file: + cmd.append("--no-site-file") + if no_init_file: + cmd.append("--no-init-file") + if restore: + cmd.append("--restore") + + if verbose: + cmd.append("--verbose") + + if default_packages: + cmd.extend(["--default-packages", default_packages]) + + # Add the script file or expressions to execute + if script_file: + cmd.append(str(script_file)) + elif expressions: + for expr in expressions: + cmd.extend(["-e", expr]) + + # Add any additional arguments for the R script itself + if script_args: + cmd.extend(script_args) + + command_executed = shlex.join(cmd) + + # 3. Subprocess Execution + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + # 4. Structured Result Return + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] # Rscript does not have a defined output file parameter. + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your system's PATH.") + except subprocess.CalledProcessError as e: + # Handle cases where the R script fails + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Rscript execution failed with return code {e.returncode}", + "output_files": [] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-clustifyr/app/bioconductor-clustifyr_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-clustifyr/app/bioconductor-clustifyr_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..953fbaa9da32e2960a4d322ec97b117c3b3ac53e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-clustifyr/app/bioconductor-clustifyr_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-clustifyr/app/bioconductor-clustifyr_server.py') +SERVER_NAME = 'biosci_bioconductor_clustifyr' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-clustifyr/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-clustifyr/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..815f8ab58e324137dfb25d93e4ee371b34fc90af --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-clustifyr/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-clustifyr: + build: . + image: mcp-bioconductor-clustifyr:latest + container_name: mcp-bioconductor-clustifyr + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-clustifyr + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-clustifyr/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-clustifyr/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..34e35a6e37b07334f789ad2eaa09c886ac0f1f7e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-clustifyr/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-clustifyr + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-clustifyr/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-clustifyr/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-clustifyr/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-cytomapper/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-cytomapper/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..05ba47cceccdf90f283645882e3e1a77140c29c5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-cytomapper/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.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-cytomapper via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-cytomapper -y && conda clean -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-cytomapper_server.py /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-cytomapper_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --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-cytomapper_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-cytomapper/app/bioconductor-cytomapper_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-cytomapper/app/bioconductor-cytomapper_server.py new file mode 100644 index 0000000000000000000000000000000000000000..281ec9f1dfe3c30bac17b5a62550ce3f1fb5a1a2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-cytomapper/app/bioconductor-cytomapper_server.py @@ -0,0 +1,124 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +# The mcp.tool decorator is a placeholder for the actual implementation in the MCP framework. +# In a real MCP environment, this would be: from mcp import tool +def tool(*args, **kwargs): + def decorator(f): + return f + return decorator + +mcp = type("mcp", (), {"tool": tool}) + + +@mcp.tool() +def cytomapper_rscript( + script_file: Optional[Path] = None, + expressions: Optional[List[str]] = None, + args: Optional[List[str]] = None, + verbose: bool = False, + default_packages: Optional[str] = None, + save: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: bool = False, + restore: bool = False, + vanilla: bool = False, +) -> Dict[str, Any]: + """ + Executes an R script using the Rscript command-line interface. + + This tool is a wrapper for Rscript, designed to run R scripts that utilize + Bioconductor packages like 'cytomapper'. Since 'cytomapper' is an R library + without a direct command-line executable, this tool provides the necessary + interface to run user-provided scripts that implement 'cytomapper' workflows. + + You must provide either a path to an R script file or a list of R expressions to execute. + + Args: + script_file: Path to the R script file to be executed. + expressions: A list of R expressions to execute directly. Use instead of script_file. + args: A list of additional arguments to be passed to the R script. + verbose: If True, print information on progress (--verbose). + default_packages: Comma-separated list of package names to be loaded by default. + save: If True, save the workspace at the end of the session (--save). + no_environ: If True, do not read the site and user environment files (--no-environ). + no_site_file: If True, do not read the site-wide Rprofile (--no-site-file). + no_init_file: If True, do not read the user R profile (--no-init-file). + restore: If True, restore previously saved objects at startup (--restore). + vanilla: If True, combines --no-save, --no-restore, --no-site-file, + --no-init-file, and --no-environ. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + Note: Output files are not automatically detected; the R script is responsible for + managing its own outputs. + """ + # Input validation + if not script_file and not expressions: + raise ValueError("You must provide either 'script_file' or 'expressions'.") + if script_file and expressions: + raise ValueError("You cannot provide both 'script_file' and 'expressions'.") + if script_file and not script_file.is_file(): + raise FileNotFoundError(f"The specified script file does not exist or is not a file: {script_file}") + + command = ["Rscript"] + + # Add Rscript options + if vanilla: + command.append("--vanilla") + else: + if save: + command.append("--save") + if no_environ: + command.append("--no-environ") + if no_site_file: + command.append("--no-site-file") + if no_init_file: + command.append("--no-init-file") + if restore: + command.append("--restore") + + if verbose: + command.append("--verbose") + if default_packages: + command.append(f"--default-packages={default_packages}") + + # Add execution target (script file or expressions) + if expressions: + for expr in expressions: + command.extend(["-e", expr]) + elif script_file: + command.append(str(script_file)) + + # Add arguments for the R script itself + if args: + command.extend(args) + + command_str = " ".join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + raise RuntimeError("The 'Rscript' command was not found. Please ensure R is installed and accessible in the system's PATH.") + except subprocess.CalledProcessError as e: + # Return a structured error response + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Rscript execution failed with return code {e.returncode}", + "output_files": [] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-cytomapper/app/bioconductor-cytomapper_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-cytomapper/app/bioconductor-cytomapper_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6373f1cb23645385599d9be6283d5e38b341dda7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-cytomapper/app/bioconductor-cytomapper_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-cytomapper/app/bioconductor-cytomapper_server.py') +SERVER_NAME = 'biosci_bioconductor_cytomapper' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-cytomapper/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-cytomapper/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..907b3f17199b82cd6261476c9a0b08d00c4e8fd7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-cytomapper/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-cytomapper: + build: . + image: mcp-bioconductor-cytomapper:latest + container_name: mcp-bioconductor-cytomapper + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-cytomapper + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-cytomapper/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-cytomapper/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bd7bd84c1e8982b4e751012c9542ffeeb64c7e31 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-cytomapper/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-cytomapper + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-cytomapper/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-cytomapper/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-cytomapper/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dirichletmultinomial/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dirichletmultinomial/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6b140ffebcc28a004b81e016332d3c19575de84d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dirichletmultinomial/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-dirichletmultinomial via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-dirichletmultinomial -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-dirichletmultinomial_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-dirichletmultinomial_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-dirichletmultinomial_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dirichletmultinomial/app/bioconductor-dirichletmultinomial_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dirichletmultinomial/app/bioconductor-dirichletmultinomial_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f9b283e7113523b7a3a33a4476ec18ef3997cab2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dirichletmultinomial/app/bioconductor-dirichletmultinomial_server.py @@ -0,0 +1,217 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be imported. +def tool(*args, **kwargs): + def decorator(func): + return func + return decorator + +mcp = type("mcp", (), {"tool": tool}) + + +@mcp.tool() +def dirichlet_multinomial_dmn( + count_matrix: Path, + k: int, + output_prefix: str, + b: int = 100, + verbose: bool = False, + seed: Optional[int] = None, +) -> dict: + """ + Fits a Dirichlet-Multinomial Mixture Model to count data. + + This tool serves as a wrapper for the dmn() function from the Bioconductor + R package 'DirichletMultinomial'. It takes a count matrix (samples x features) + and fits a model to identify a specified number of clusters (k). + + Tool Requirements: + - R installed and in the system's PATH. + - Rscript executable. + - The following R packages installed: 'DirichletMultinomial', 'readr', 'dplyr', 'tidyr'. + + Args: + count_matrix: Path to the input count matrix file. The file should be + tab-separated (TSV) with a header. The first column must + contain sample identifiers. + k: The number of mixture components (clusters) to fit. Must be an integer >= 2. + output_prefix: A string prefix for all output files. + b: The number of random starts for initialization. Corresponds to the 'B' + parameter in the dmn() function. Defaults to 100. + verbose: If True, enables verbose output from the R script. Defaults to False. + seed: An optional integer for setting the random seed in R for reproducibility. + Defaults to None. + + Returns: + A dictionary containing the execution command, stdout, stderr, and a list + of paths to the generated output files. + """ + # --- 1. Input and Parameter Validation --- + if not count_matrix.is_file(): + raise FileNotFoundError(f"Input file not found: {count_matrix}") + if k < 2: + raise ValueError("k (number of components) must be an integer of 2 or greater.") + if b <= 0: + raise ValueError("b (number of random starts) must be a positive integer.") + if not output_prefix: + raise ValueError("output_prefix cannot be empty.") + + # --- 2. R Script Generation --- + # Convert Python types to R-compatible string representations + verbose_str = "TRUE" if verbose else "FALSE" + seed_str = str(seed) if seed is not None else "NULL" + + # Using absolute paths is safer for subprocess execution + abs_count_matrix_path = count_matrix.resolve() + abs_output_prefix = Path(output_prefix).resolve() + + r_script_content = f""" + # Load required libraries + # Suppress startup messages for cleaner output + suppressPackageStartupMessages(library(DirichletMultinomial)) + suppressPackageStartupMessages(library(readr)) + suppressPackageStartupMessages(library(dplyr)) + suppressPackageStartupMessages(library(tidyr)) + suppressPackageStartupMessages(library(tibble)) + + # --- Parameters passed from Python --- + count_file <- "{abs_count_matrix_path}" + k_value <- {k} + b_value <- {b} + verbose_value <- {verbose_str} + output_prefix <- "{abs_output_prefix}" + seed_value <- {seed_str} + + # --- Main script --- + tryCatch({{ + # Set seed for reproducibility + if (!is.null(seed_value)) {{ + set.seed(seed_value) + }} + + # Load data + message("Reading count matrix from: ", count_file) + counts_df <- readr::read_tsv(count_file, col_types = cols()) + + # Convert first column to row names and the rest to a matrix + count_matrix <- as.matrix(counts_df[,-1]) + rownames(count_matrix) <- counts_df[[1]] + message("Dimensions of count matrix: ", nrow(count_matrix), " samples, ", ncol(count_matrix), " features.") + + # Validate that data is integer counts + if (!all(count_matrix == floor(count_matrix))) {{ + stop("Count matrix contains non-integer values. Please provide a raw count matrix.") + }} + + # Fit the Dirichlet-Multinomial model + message("Fitting DMN model with k=", k_value, "...") + fit <- dmn(count_matrix, k = k_value, B = b_value, verbose = verbose_value) + message("Model fitting complete.") + + # --- Save outputs --- + # Since we fit for a single k, extract that model directly + best_fit <- fit[[1]] + + # 1. Save the full model object + model_rds_path <- paste0(output_prefix, "_model.rds") + message("Saving model object to: ", model_rds_path) + saveRDS(fit, file = model_rds_path) + + # 2. Save goodness-of-fit statistics + gof_path <- paste0(output_prefix, "_gof.tsv") + message("Saving goodness-of-fit statistics to: ", gof_path) + gof_stats <- data.frame( + k = sapply(fit, n_components), + laplace = sapply(fit, laplace), + aic = sapply(fit, AIC), + bic = sapply(fit, BIC) + ) + readr::write_tsv(gof_stats, gof_path) + + # 3. Save mixture weights (proportions of each component) + mixture_weights_path <- paste0(output_prefix, "_mixture_weights.tsv") + message("Saving mixture weights to: ", mixture_weights_path) + mixture_weights_df <- as.data.frame(mixturewt(best_fit)) + colnames(mixture_weights_df) <- paste0("Component_", 1:ncol(mixture_weights_df)) + readr::write_tsv(mixture_weights_df, mixture_weights_path) + + # 4. Save cluster assignments for each sample + assignments_path <- paste0(output_prefix, "_cluster_assignments.tsv") + message("Saving cluster assignments to: ", assignments_path) + assignments <- data.frame( + sample_id = rownames(count_matrix), + best_component = apply(mixture(best_fit), 1, which.max) + ) + readr::write_tsv(assignments, assignments_path) + + # 5. Save component parameters (theta values for each feature) + theta_path <- paste0(output_prefix, "_component_parameters.tsv") + message("Saving component parameters (theta) to: ", theta_path) + theta_values <- as.data.frame(fitted(best_fit)) + colnames(theta_values) <- paste0("Component_", 1:ncol(theta_values)) + theta_values <- tibble::rownames_to_column(theta_values, var = "feature_id") + readr::write_tsv(theta_values, theta_path) + + message("Script finished successfully.") + }}, error = function(e) {{ + message("An error occurred in the R script: ", e$message) + quit(status = 1, save = "no") + }}) + """ + + # --- 3. Subprocess Execution --- + with tempfile.TemporaryDirectory() as temp_dir: + r_script_path = Path(temp_dir) / "run_dmn.R" + with open(r_script_path, "w") as f: + f.write(r_script_content) + + command = ["Rscript", str(r_script_path)] + command_str = " ".join(command) + + try: + result = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + except FileNotFoundError: + raise RuntimeError( + "Rscript not found. Please ensure R is installed and " + "'Rscript' is in your system's PATH." + ) + except subprocess.CalledProcessError as e: + error_message = ( + f"The R script failed with exit code {e.returncode}.\n" + f"This could be due to missing R packages (DirichletMultinomial, readr, dplyr, tidyr) " + f"or an issue with the input data format.\n" + f"Command: {command_str}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) + raise RuntimeError(error_message) from e + + # --- 4. Collect and Return Structured Output --- + output_files_generated: List[str] = [] + expected_suffixes = [ + "_model.rds", + "_gof.tsv", + "_mixture_weights.tsv", + "_cluster_assignments.tsv", + "_component_parameters.tsv", + ] + for suffix in expected_suffixes: + output_file = Path(f"{abs_output_prefix}{suffix}") + if output_file.exists(): + output_files_generated.append(str(output_file)) + + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files_generated, + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dirichletmultinomial/app/bioconductor-dirichletmultinomial_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dirichletmultinomial/app/bioconductor-dirichletmultinomial_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ad0fc61af8b28ae5a5ad811820955cfe4900a3af --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dirichletmultinomial/app/bioconductor-dirichletmultinomial_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dirichletmultinomial/app/bioconductor-dirichletmultinomial_server.py') +SERVER_NAME = 'biosci_bioconductor_dirichletmultinomial' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dirichletmultinomial/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dirichletmultinomial/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dirichletmultinomial/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dirichletmultinomial/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dirichletmultinomial/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..cb60f4389afe631128c813da64d85d6a4bc4d26e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dirichletmultinomial/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-dirichletmultinomial: + build: . + image: mcp-bioconductor-dirichletmultinomial:latest + container_name: mcp-bioconductor-dirichletmultinomial + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-dirichletmultinomial + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dirichletmultinomial/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dirichletmultinomial/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c361af9475e4996a82d48c65765813a91eb93eb4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dirichletmultinomial/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-dirichletmultinomial + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dirichletmultinomial/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dirichletmultinomial/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dirichletmultinomial/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dnacopy/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dnacopy/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..acfa6545a2f171d74ff198f82cd7aaba66db4989 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dnacopy/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-dnacopy via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-dnacopy -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-dnacopy_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-dnacopy_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-dnacopy_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dnacopy/app/bioconductor-dnacopy_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dnacopy/app/bioconductor-dnacopy_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0689beccafb1bc4991e8ebbb1daff93377fcf2ea --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dnacopy/app/bioconductor-dnacopy_server.py @@ -0,0 +1,208 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Dict, List, Optional, Union + +# 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.""" + return func + +@tool +def dnacopy_segment( + input_file: Path, + output_prefix: str, + sample_id_col: str, + chrom_col: str, + maploc_col: str, + data_col: str, + smooth_cna: bool = True, + make_plot: bool = True, + alpha: float = 0.01, + nperm: int = 10000, + p_method: str = "hybrid", + min_width: int = 2, + undo_splits: str = "sdundo", + undo_sd: float = 3.0, + trim: float = 0.025, + verbose: int = 1, +) -> Dict[str, Union[str, List[str]]]: + """ + Performs Circular Binary Segmentation (CBS) on copy number data using the R package DNAcopy. + + This tool takes a tab-delimited file containing genomic data (chromosome, position, log-ratio) + and segments it to identify regions of equal copy number. + + Args: + input_file: Path to the input tab-delimited data file. + output_prefix: Prefix for the output files (e.g., 'my_sample'). + sample_id_col: Name of the column containing sample identifiers. + chrom_col: Name of the column containing chromosome identifiers. + maploc_col: Name of the column containing genomic map locations (positions). + data_col: Name of the column containing the log2 ratio copy number data. + smooth_cna: If True, apply the `smooth.CNA` function before segmentation. Defaults to True. + make_plot: If True, generate a plot of the segmentation results as a PDF. Defaults to True. + alpha: Significance level to accept a change-point. Defaults to 0.01. + nperm: Number of permutations for `p.method='perm'`. Defaults to 10000. + p_method: Method to compute p-values. Must be 'hybrid' or 'perm'. Defaults to 'hybrid'. + min_width: The minimum number of markers for a segment. Defaults to 2. + undo_splits: Method for undoing splits. Must be 'none', 'prune', or 'sdundo'. Defaults to 'sdundo'. + undo_sd: The number of standard deviations for the undoing rule. Defaults to 3.0. + trim: Proportion of data to be trimmed for variance calculation. Defaults to 0.025. + verbose: Verbosity level (0, 1, or 2). Defaults to 1. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output file paths. + """ + # --- 1. Input Validation --- + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + p_method_choices = ["hybrid", "perm"] + if p_method not in p_method_choices: + raise ValueError(f"p_method must be one of {p_method_choices}, not '{p_method}'") + + undo_splits_choices = ["none", "prune", "sdundo"] + if undo_splits not in undo_splits_choices: + raise ValueError(f"undo_splits must be one of {undo_splits_choices}, not '{undo_splits}'") + + if not (0 < alpha < 1): + raise ValueError("alpha must be between 0 and 1.") + + if not (0 <= trim < 0.5): + raise ValueError("trim must be between 0 and 0.5.") + + if nperm <= 0: + raise ValueError("nperm must be a positive integer.") + + if min_width < 2: + raise ValueError("min_width must be an integer >= 2.") + + if verbose not in [0, 1, 2]: + raise ValueError("verbose must be 0, 1, or 2.") + + # --- 2. Define Output Paths --- + output_seg_file = Path(f"{output_prefix}.seg") + output_plot_file = Path(f"{output_prefix}.pdf") + output_files = [str(output_seg_file)] + if make_plot: + output_files.append(str(output_plot_file)) + + # --- 3. Generate R Script --- + # This script reads the data, creates a CNA object, optionally smooths it, + # runs segmentation, and writes the output. It also handles non-numeric + # chromosome names like 'X' and 'Y'. + r_script = f""" + # Load the library + library(DNAcopy) + + # Read the input data + cat("Reading input file: {input_file}\\n") + raw_data <- read.table("{input_file}", header=TRUE, sep="\\t", stringsAsFactors=FALSE, check.names=FALSE) + + # Ensure required columns exist + required_cols <- c("{sample_id_col}", "{chrom_col}", "{maploc_col}", "{data_col}") + if (!all(required_cols %in% colnames(raw_data))) {{ + stop("One or more required columns not found in the input file.") + }} + + # Pre-process chromosome column to handle non-numeric values (e.g., X, Y) + cat("Processing chromosome identifiers...\\n") + raw_data[["{chrom_col}"]] <- as.character(raw_data[["{chrom_col}"]]) + raw_data[["{chrom_col}"]][toupper(raw_data[["{chrom_col}"]]) == 'X'] <- 23 + raw_data[["{chrom_col}"]][toupper(raw_data[["{chrom_col}"]]) == 'Y'] <- 24 + raw_data[["{chrom_col}"]][toupper(raw_data[["{chrom_col}"]]) == 'MT'] <- 25 + raw_data[["{chrom_col}"]] <- suppressWarnings(as.numeric(raw_data[["{chrom_col}"]])) + + # Filter out rows with NA values in key columns after conversion + raw_data <- raw_data[ + !is.na(raw_data[["{chrom_col}"]]) & + !is.na(raw_data[["{maploc_col}"]]) & + !is.na(raw_data[["{data_col}"]]), + ] + + # Create CNA object + cat("Creating CNA object...\\n") + CNA.object <- CNA( + genomdat = raw_data[["{data_col}"]], + chrom = raw_data[["{chrom_col}"]], + maploc = raw_data[["{maploc_col}"]], + data.type = 'logratio', + sampleid = raw_data[["{sample_id_col}"]] + ) + + # Smooth the data if requested + target_object <- CNA.object + if ({str(smooth_cna).upper()}) {{ + cat("Smoothing CNA object...\\n") + target_object <- smooth.CNA(CNA.object) + }} + + # Perform segmentation + cat("Performing segmentation...\\n") + segmentation <- segment( + target_object, + alpha = {alpha}, + nperm = {nperm}, + p.method = "{p_method}", + min.width = {min_width}, + undo.splits = "{undo_splits}", + undo.SD = {undo_sd}, + trim = {trim}, + verbose = {verbose} + ) + + # Write segmentation output + cat("Writing segmentation output to {output_seg_file}\\n") + write.table(segmentation$output, file="{output_seg_file}", sep="\\t", quote=FALSE, row.names=FALSE) + + # Generate plot if requested + if ({str(make_plot).upper()}) {{ + cat("Generating plot at {output_plot_file}\\n") + pdf("{output_plot_file}") + plot(segmentation, plot.type="w") + dev.off() + }} + + cat("DNAcopy analysis complete.\\n") + """ + + # --- 4. Execute R Script --- + command = [] + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_script: + tmp_script.write(r_script) + script_path = tmp_script.name + + command = ["Rscript", script_path] + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + # Provide a more informative error message + error_message = ( + f"DNAcopy R script failed with exit code {e.returncode}.\n" + f"Command: {' '.join(command)}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) + raise RuntimeError(error_message) from e + finally: + # Clean up the temporary script file + if 'script_path' in locals() and Path(script_path).exists(): + Path(script_path).unlink() + + # --- 5. Return Structured Output --- + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dnacopy/app/bioconductor-dnacopy_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dnacopy/app/bioconductor-dnacopy_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4e35c63c11f28ceaa1593b1d5726dff44d482f70 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dnacopy/app/bioconductor-dnacopy_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dnacopy/app/bioconductor-dnacopy_server.py') +SERVER_NAME = 'biosci_bioconductor_dnacopy' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dnacopy/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dnacopy/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dnacopy/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dnacopy/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dnacopy/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..2a3bc04cf7735b56b19adb7824aab027ad1edc38 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dnacopy/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-dnacopy: + build: . + image: mcp-bioconductor-dnacopy:latest + container_name: mcp-bioconductor-dnacopy + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-dnacopy + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dnacopy/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dnacopy/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a899be3d3c4b68ef4f21429190feaaf5b44d4dbf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dnacopy/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-dnacopy + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dnacopy/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dnacopy/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-dnacopy/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-edger/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-edger/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..afa6508a4a79e041e41e6dba488188175d2bf18b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-edger/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-edger via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-edger -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-edger_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-edger_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-edger_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-edger/app/bioconductor-edger_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-edger/app/bioconductor-edger_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a54a68420dd5092a56d6fb0567bcfad5c714dfad --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-edger/app/bioconductor-edger_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-edger/app/bioconductor-edger_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..cd85b28baa661dd2dcf88ac64f6150102e36e185 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-edger/app/bioconductor-edger_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-edger/app/bioconductor-edger_server.py') +SERVER_NAME = 'biosci_bioconductor_edger' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-edger/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-edger/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-edger/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-edger/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-edger/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..3c2d48e4be4ae96adc8e3d2a236e22da2a3d7e41 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-edger/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-edger: + build: . + image: mcp-bioconductor-edger:latest + container_name: mcp-bioconductor-edger + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-edger + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-edger/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-edger/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6dc7924789c820fb39041415eb915f5b2f3558e6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-edger/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-edger + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-edger/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-edger/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-edger/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genefilter/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genefilter/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..dc85663f20f55f0012a7e7ede03831c347bd098c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genefilter/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-genefilter via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-genefilter -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-genefilter_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-genefilter_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-genefilter_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genefilter/app/bioconductor-genefilter_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genefilter/app/bioconductor-genefilter_server.py new file mode 100644 index 0000000000000000000000000000000000000000..63f36db3be307a8eded744c36c4199d3e8268690 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genefilter/app/bioconductor-genefilter_server.py @@ -0,0 +1,319 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# Mock decorator for standalone execution +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def genefilter_nsfilter( + expression_data: Path, + output_prefix: str, + feature_data: Optional[Path] = None, + require_entrez: bool = False, + require_symbol: bool = False, + remove_dup_entrez: bool = True, + var_func: str = "IQR", + var_filter: bool = True, + var_cutoff: float = 0.5, + var_by_quantile: bool = True, +) -> dict: + """ + Performs non-specific filtering of genes using the nsFilter function. + + This tool wraps the nsFilter function from the R genefilter package. It is designed + to remove genes/probes that are unlikely to be informative, such as those with low + variance across samples or those lacking proper annotation. + + Args: + expression_data: Path to the input expression data file (CSV format). + Rows should be genes and columns should be samples. + The first column should contain gene identifiers. + output_prefix: Prefix for the output files. + feature_data: Optional path to a feature data file (CSV format) with annotations. + The first column must match the gene identifiers in expression_data. + require_entrez: If True, requires features to have an Entrez Gene ID. + require_symbol: If True, requires features to have a gene symbol. + remove_dup_entrez: If True, removes duplicated Entrez IDs. + var_func: The function to calculate variance ('IQR', 'sd', 'mad'). + var_filter: If True, applies the variance filter. + var_cutoff: The quantile cutoff for variance. + var_by_quantile: If True, the var.cutoff is treated as a quantile; otherwise, + it's a fixed threshold. + + Returns: + A dictionary containing the command executed, stdout, stderr, and paths to + the filtered expression data and the filter summary. + """ + # Input validation + if not expression_data.is_file(): + raise FileNotFoundError(f"Input file not found: {expression_data}") + if feature_data and not feature_data.is_file(): + raise FileNotFoundError(f"Feature data file not found: {feature_data}") + if var_func not in ["IQR", "sd", "mad"]: + raise ValueError("var_func must be one of 'IQR', 'sd', or 'mad'.") + + output_filtered_eset = Path(f"{output_prefix}_filtered_expression.csv") + output_filter_stats = Path(f"{output_prefix}_filter_stats.csv") + + r_script_content = f""" + # Load necessary libraries + library(genefilter) + library(Biobase) + + # Read data + exprs_data <- as.matrix(read.csv("{expression_data}", row.names=1, check.names=FALSE)) + + # Create a minimal ExpressionSet object + eset <- ExpressionSet(assayData=exprs_data) + + # Add feature data if provided + if (!is.null("{feature_data}")) {{ + pdata <- read.csv("{feature_data}", row.names=1, check.names=FALSE) + # Ensure order matches + pdata <- pdata[rownames(exprs(eset)), , drop=FALSE] + phenoData(eset) <- new("AnnotatedDataFrame", data=pdata) + }} + + # Perform non-specific filtering + # Note: require.entrez and require.symbol need corresponding columns in featureData + # We will simulate this if not present for the logic to run + if (is.null(fvarLabels(eset))) {{ + fvarLabels(eset) <- "ID" + }} + if ({str(require_entrez).upper()} && !("EntrezId" %in% fvarLabels(eset))) {{ + fData(eset)$EntrezId <- rownames(fData(eset)) + }} + if ({str(require_symbol).upper()} && !("Symbol" %in% fvarLabels(eset))) {{ + fData(eset)$Symbol <- rownames(fData(eset)) + }} + + filter_result <- nsFilter( + eset, + require.entrez = {str(require_entrez).upper()}, + require.symbol = {str(require_symbol).upper()}, + remove.dupEntrez = {str(remove_dup_entrez).upper()}, + var.func = {var_func}, + var.filter = {str(var_filter).upper()}, + var.cutoff = {var_cutoff}, + varByQuantile = {str(var_by_quantile).upper()} + ) + + # Save results + write.csv(exprs(filter_result$eset), file="{output_filtered_eset}") + write.csv(as.data.frame(filter_result$filter.log), file="{output_filter_stats}") + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_script: + tmp_script.write(r_script_content) + script_path = tmp_script.name + + cmd = ["Rscript", script_path] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": { + "filtered_expression": str(output_filtered_eset), + "filter_stats": str(output_filter_stats) + } + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } + finally: + Path(script_path).unlink() + + +@mcp.tool +def genefilter_rowttests( + expression_data: Path, + factor_levels: str, + output_file: Path, + t_statistic_only: bool = False, +) -> dict: + """ + Computes two-sample t-tests for each row of a matrix-like object. + + This tool wraps the rowttests function from the R genefilter package. It is useful + for differential expression analysis between two groups. + + Args: + expression_data: Path to the input expression data file (CSV format). + Rows should be genes, columns should be samples. + The first column should contain gene identifiers. + factor_levels: A comma-separated string defining the two groups for the t-test. + Example: "groupA,groupA,groupB,groupB,groupA". The number of + elements must match the number of columns in expression_data. + output_file: Path to save the t-test results (CSV format). + t_statistic_only: If True, returns only the t-statistic for each row. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to + the output results file. + """ + # Input validation + if not expression_data.is_file(): + raise FileNotFoundError(f"Input file not found: {expression_data}") + + r_script_content = f""" + library(genefilter) + + # Read data + data_matrix <- as.matrix(read.csv("{expression_data}", row.names=1, check.names=FALSE)) + + # Create factor from input string + factor_vector <- c({factor_levels}) + if (length(factor_vector) != ncol(data_matrix)) {{ + stop("The number of factor levels must match the number of columns in the expression data.") + }} + fac <- factor(factor_vector) + if (nlevels(fac) != 2) {{ + stop("The factor must have exactly two levels (groups) for a two-sample t-test.") + }} + + # Perform row-wise t-tests + ttest_results <- rowttests(data_matrix, fac, tstatOnly={str(t_statistic_only).upper()}) + + # Save results + write.csv(ttest_results, file="{output_file}") + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_script: + tmp_script.write(r_script_content) + script_path = tmp_script.name + + cmd = ["Rscript", script_path] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"results": str(output_file)} + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } + finally: + Path(script_path).unlink() + + +@mcp.tool +def genefilter_k_over_a( + expression_data: Path, + k: int, + A: float, + output_prefix: str, +) -> dict: + """ + Filters genes where at least 'k' samples have expression values over 'A'. + + This tool uses the kOverA filter function with the main genefilter engine. + It's a common filtering step to remove genes with consistently low expression. + + Args: + expression_data: Path to the input expression data file (CSV format). + Rows should be genes, columns should be samples. + The first column should contain gene identifiers. + k: The minimum number of samples that must be above the threshold 'A'. + A: The expression level threshold. + output_prefix: Prefix for the output files. + + Returns: + A dictionary containing the command executed, stdout, stderr, and paths to + the filtered data and a list of passing gene IDs. + """ + # Input validation + if not expression_data.is_file(): + raise FileNotFoundError(f"Input file not found: {expression_data}") + if k < 0: + raise ValueError("k must be a non-negative integer.") + + output_filtered_data = Path(f"{output_prefix}_filtered_data.csv") + output_passing_genes = Path(f"{output_prefix}_passing_genes.txt") + + r_script_content = f""" + library(genefilter) + + # Read data + data_matrix <- as.matrix(read.csv("{expression_data}", row.names=1, check.names=FALSE)) + + # Define the kOverA filter function + kOverA_filter <- kOverA(k={k}, A={A}) + + # Apply the filter using genefilter + passing_indices <- genefilter(data_matrix, kOverA_filter) + + # Subset the data to keep only the passing genes + filtered_matrix <- data_matrix[passing_indices, ] + passing_gene_ids <- rownames(filtered_matrix) + + # Save the results + write.csv(filtered_matrix, file="{output_filtered_data}") + write.table(passing_gene_ids, file="{output_passing_genes}", row.names=FALSE, col.names=FALSE, quote=FALSE) + """ + + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_script: + tmp_script.write(r_script_content) + script_path = tmp_script.name + + cmd = ["Rscript", script_path] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": { + "filtered_data": str(output_filtered_data), + "passing_genes": str(output_passing_genes) + } + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed.", + "return_code": e.returncode + } + finally: + Path(script_path).unlink() \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genefilter/app/bioconductor-genefilter_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genefilter/app/bioconductor-genefilter_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..98f504c31aa32368fd4e557f280a8e0199fb5d4d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genefilter/app/bioconductor-genefilter_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genefilter/app/bioconductor-genefilter_server.py') +SERVER_NAME = 'biosci_bioconductor_genefilter' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genefilter/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genefilter/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genefilter/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genefilter/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genefilter/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b8e8117174138cbb23e50012e6aebca949f11ffa --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genefilter/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-genefilter: + build: . + image: mcp-bioconductor-genefilter:latest + container_name: mcp-bioconductor-genefilter + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-genefilter + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genefilter/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genefilter/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..312740a65e928231eccc1ea6ad5aa3f5d906f6ab --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genefilter/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-genefilter + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genefilter/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genefilter/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genefilter/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-geneplotter/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-geneplotter/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9d0c94a2a986994b11bf5544d2ed47deb4078e57 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-geneplotter/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-geneplotter via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-geneplotter -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-geneplotter_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-geneplotter_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-geneplotter_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-geneplotter/app/bioconductor-geneplotter_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-geneplotter/app/bioconductor-geneplotter_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ef6dfcc0ec4c0900ae2ecde3121d5f1e6f66341a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-geneplotter/app/bioconductor-geneplotter_server.py @@ -0,0 +1,442 @@ +import subprocess +import tempfile +import os +from pathlib import Path +from typing import Optional, Dict, Any, List + +# Mock decorator for standalone execution +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def geneplotter_plot_ma( + expression_file: Path, + output_file: Path, + main_title: str = "MA Plot", + xlab: str = "A (Average Log Intensity)", + ylab: str = "M (Log Ratio)", + point_color: str = "blue", + point_size: float = 0.5, + add_abline: bool = True, + file_separator: str = "tab", +) -> Dict[str, Any]: + """ + Generates an M-A plot from a two-column expression file. + + This tool takes a file with two columns of expression data (e.g., two + samples or conditions), calculates M (log-ratio) and A (average log-intensity), + and generates a scatter plot. It is a common visualization for differential + expression analysis. + + Args: + expression_file: Path to the input data file. Must contain at least two + numeric columns representing two conditions. A header is expected. + output_file: Path to save the output PNG image. + main_title: The main title for the plot. + xlab: Label for the x-axis (A-values). + ylab: Label for the y-axis (M-values). + point_color: Color of the points in the plot. + point_size: Size of the points (cex in R). + add_abline: If True, adds a horizontal red line at y=0. + file_separator: The separator used in the input file ('tab' or 'comma'). + + Returns: + A dictionary containing the execution command, stdout, stderr, and a + list with the path to the output plot file. + """ + # --- Input Validation --- + if not expression_file.is_file(): + raise FileNotFoundError(f"Input file not found: {expression_file}") + if output_file.suffix.lower() != ".png": + raise ValueError("output_file must have a .png extension.") + if point_size <= 0: + raise ValueError("point_size must be a positive number.") + if file_separator not in ["tab", "comma"]: + raise ValueError("file_separator must be 'tab' or 'comma'.") + + output_file.parent.mkdir(parents=True, exist_ok=True) + sep_char = "\t" if file_separator == "tab" else "," + + # --- R Script --- + r_script_content = f""" + library(geneplotter) + library(methods) + + args <- commandArgs(trailingOnly = TRUE) + inputFile <- args[1] + outputFile <- args[2] + mainTitle <- args[3] + xLab <- args[4] + yLab <- args[5] + pointColor <- args[6] + pointSize <- as.numeric(args[7]) + addAbline <- as.logical(args[8]) + + data <- read.csv(inputFile, header = TRUE, sep = "{sep_char}") + + if (ncol(data) < 2) {{ + stop("Input file must have at least two numeric columns.") + }} + + offset <- 1e-6 + col1 <- as.numeric(data[,1]) + col2 <- as.numeric(data[,2]) + + M <- log2(col1 + offset) - log2(col2 + offset) + A <- 0.5 * (log2(col1 + offset) + log2(col2 + offset)) + ma_data <- data.frame(A = A, M = M) + + png(outputFile, width = 800, height = 600) + + plot(ma_data, + main = mainTitle, + xlab = xLab, + ylab = yLab, + col = pointColor, + cex = pointSize, + pch = 16) + + if (addAbline) {{ + abline(h = 0, col = "red", lwd = 2) + }} + + dev.off() + """ + + 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 + + # --- Subprocess Execution --- + command: List[str] = [ + "Rscript", + script_path, + str(expression_file), + str(output_file), + main_title, + xlab, + ylab, + point_color, + str(point_size), + str(add_abline).upper(), + ] + + command_str = " ".join(command) + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file)], + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + error_message = ( + f"R script execution failed with return code {e.returncode}.\n" + f"Command: {command_str}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) + raise RuntimeError(error_message) + finally: + os.remove(script_path) + + +@mcp.tool +def geneplotter_plot_densities( + expression_file: Path, + output_file: Path, + main_title: str = "Density of log2(intensities)", + xlab: str = "log2(intensity)", + log_transform: bool = True, + legend_position: str = "topright", + line_width: int = 2, + file_separator: str = "tab", +) -> Dict[str, Any]: + """ + Plots density estimates of expression values for each sample. + + This tool is useful for quality control, allowing visual inspection of the + distribution of expression values across multiple samples to check for + batch effects or normalization issues. + + Args: + expression_file: Path to the input data file. Columns should be samples + and rows should be features (e.g., genes). A header row + with sample names and a first column with feature names + are expected. + output_file: Path to save the output PNG image. + main_title: The main title for the plot. + xlab: Label for the x-axis. + log_transform: If True, log2-transforms the data before plotting. + legend_position: Position of the legend (e.g., "topright", "bottomleft"). + line_width: Width of the density lines. + file_separator: The separator used in the input file ('tab' or 'comma'). + + Returns: + A dictionary containing the execution command, stdout, stderr, and a + list with the path to the output plot file. + """ + # --- Input Validation --- + if not expression_file.is_file(): + raise FileNotFoundError(f"Input file not found: {expression_file}") + if output_file.suffix.lower() != ".png": + raise ValueError("output_file must have a .png extension.") + if line_width <= 0: + raise ValueError("line_width must be a positive integer.") + if file_separator not in ["tab", "comma"]: + raise ValueError("file_separator must be 'tab' or 'comma'.") + + output_file.parent.mkdir(parents=True, exist_ok=True) + sep_char = "\t" if file_separator == "tab" else "," + + # --- R Script --- + r_script_content = f""" + library(geneplotter) + library(methods) + + args <- commandArgs(trailingOnly = TRUE) + inputFile <- args[1] + outputFile <- args[2] + mainTitle <- args[3] + xLab <- args[4] + logTransform <- as.logical(args[5]) + legendPos <- args[6] + lineWidth <- as.numeric(args[7]) + + data <- read.csv(inputFile, header = TRUE, sep = "{sep_char}", row.names = 1) + + data_matrix <- as.matrix(data) + if(!is.numeric(data_matrix)) {{ + stop("Input data must be numeric after the first column.") + }} + + if (logTransform) {{ + offset <- 1e-6 + data_matrix[data_matrix <= 0] <- offset + data_matrix <- log2(data_matrix) + }} + + png(outputFile, width = 800, height = 600) + + plotDensities(data_matrix, + main = mainTitle, + xlab = xLab, + legend = legendPos, + lwd = lineWidth) + + dev.off() + """ + + 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 + + # --- Subprocess Execution --- + command: List[str] = [ + "Rscript", + script_path, + str(expression_file), + str(output_file), + main_title, + xlab, + str(log_transform).upper(), + legend_position, + str(line_width), + ] + + command_str = " ".join(command) + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file)], + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + error_message = ( + f"R script execution failed with return code {e.returncode}.\n" + f"Command: {command_str}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) + raise RuntimeError(error_message) + finally: + os.remove(script_path) + + +@mcp.tool +def geneplotter_plot_pca( + expression_file: Path, + output_file: Path, + metadata_file: Optional[Path] = None, + grouping_column: Optional[str] = None, + pc_x: int = 1, + pc_y: int = 2, + main_title: str = "PCA Plot", + scale_data: bool = True, + center_data: bool = True, + point_size: float = 3.0, + file_separator: str = "tab", +) -> Dict[str, Any]: + """ + Performs PCA on expression data and generates a 2D scatter plot. + + This tool is used for exploratory data analysis to visualize sample + relationships. Points can be colored by providing a metadata file. + Requires R packages 'ggplot2' and 'RColorBrewer'. + + Args: + expression_file: Path to the expression data. Columns should be samples, + rows should be features. A header with sample names and + a first column with feature names are expected. + output_file: Path to save the output PNG image. + metadata_file: Optional. Path to a metadata file. The first column must + contain sample names matching the expression file's header. + grouping_column: The column name in metadata_file to use for coloring points. + Required if metadata_file is provided. + pc_x: The principal component to plot on the x-axis. + pc_y: The principal component to plot on the y-axis. + main_title: The main title for the plot. + scale_data: If True, scale variables to have unit variance before PCA. + center_data: If True, center variables to have mean zero before PCA. + point_size: Size of the points in the plot. + file_separator: The separator used in the input and metadata files ('tab' or 'comma'). + + Returns: + A dictionary containing the execution command, stdout, stderr, and a + list with the path to the output plot file. + """ + # --- Input Validation --- + if not expression_file.is_file(): + raise FileNotFoundError(f"Input file not found: {expression_file}") + if metadata_file and not metadata_file.is_file(): + raise FileNotFoundError(f"Metadata file not found: {metadata_file}") + if metadata_file and not grouping_column: + raise ValueError("grouping_column is required when metadata_file is provided.") + if not metadata_file and grouping_column: + raise ValueError("metadata_file is required when grouping_column is provided.") + if pc_x <= 0 or pc_y <= 0 or pc_x == pc_y: + raise ValueError("pc_x and pc_y must be different positive integers.") + if output_file.suffix.lower() != ".png": + raise ValueError("output_file must have a .png extension.") + if file_separator not in ["tab", "comma"]: + raise ValueError("file_separator must be 'tab' or 'comma'.") + + output_file.parent.mkdir(parents=True, exist_ok=True) + sep_char = "\t" if file_separator == "tab" else "," + + # --- R Script --- + r_script_content = f""" + library(ggplot2) + library(RColorBrewer) + + args <- commandArgs(trailingOnly = TRUE) + inputFile <- args[1] + outputFile <- args[2] + metadataFile <- args[3] + groupingColumn <- args[4] + pcX <- as.integer(args[5]) + pcY <- as.integer(args[6]) + mainTitle <- args[7] + scaleData <- as.logical(args[8]) + centerData <- as.logical(args[9]) + pointSize <- as.numeric(args[10]) + + expr_data <- read.csv(inputFile, header = TRUE, sep = "{sep_char}", row.names = 1) + data_for_pca <- t(expr_data) + + pca_result <- prcomp(data_for_pca, center = centerData, scale. = scaleData) + pca_summary <- summary(pca_result) + variance_explained <- pca_summary$importance[2, ] * 100 + xlab_text <- sprintf("PC%d (%.2f%% variance)", pcX, variance_explained[pcX]) + ylab_text <- sprintf("PC%d (%.2f%% variance)", pcY, variance_explained[pcY]) + + plot_data <- as.data.frame(pca_result$x) + + p <- ggplot(plot_data, aes_string(x = paste0("PC", pcX), y = paste0("PC", pcY))) + + if (metadataFile != "NULL") {{ + metadata <- read.csv(metadataFile, header = TRUE, sep = "{sep_char}", row.names = 1) + + if(!all(rownames(data_for_pca) %in% rownames(metadata))) {{ + stop("Not all samples in expression data are present in metadata file.") + }} + metadata_sorted <- metadata[rownames(data_for_pca), , drop = FALSE] + + if (!(groupingColumn %in% colnames(metadata_sorted))) {{ + stop(paste("Grouping column '", groupingColumn, "' not found in metadata file.", sep="")) + }} + plot_data$Group <- factor(metadata_sorted[[groupingColumn]]) + p <- p + geom_point(aes(color = Group), size = pointSize) + scale_color_brewer(palette = "Set1") + }} else {{ + p <- p + geom_point(size = pointSize) + }} + + p <- p + labs(title = mainTitle, x = xlab_text, y = ylab_text) + theme_bw() + ggsave(outputFile, plot = p, width = 8, height = 6, units = "in", dpi = 300) + """ + + 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 + + # --- Subprocess Execution --- + command: List[str] = [ + "Rscript", + script_path, + str(expression_file), + str(output_file), + str(metadata_file) if metadata_file else "NULL", + str(grouping_column) if grouping_column else "NULL", + str(pc_x), + str(pc_y), + main_title, + str(scale_data).upper(), + str(center_data).upper(), + str(point_size), + ] + + command_str = " ".join(command) + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file)], + } + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.") + except subprocess.CalledProcessError as e: + error_message = ( + f"R script execution failed with return code {e.returncode}.\n" + f"Command: {command_str}\n" + f"Stdout: {e.stdout}\n" + f"Stderr: {e.stderr}" + ) + raise RuntimeError(error_message) + finally: + os.remove(script_path) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-geneplotter/app/bioconductor-geneplotter_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-geneplotter/app/bioconductor-geneplotter_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..54951763fdcb4e86383e60e373262226eb1ba525 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-geneplotter/app/bioconductor-geneplotter_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-geneplotter/app/bioconductor-geneplotter_server.py') +SERVER_NAME = 'biosci_bioconductor_geneplotter' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-geneplotter/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-geneplotter/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-geneplotter/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-geneplotter/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-geneplotter/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..026bcda856f99b635b1b6d84ba99f4b936d948d7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-geneplotter/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-geneplotter: + build: . + image: mcp-bioconductor-geneplotter:latest + container_name: mcp-bioconductor-geneplotter + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-geneplotter + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-geneplotter/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-geneplotter/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..140b2e80539603f5b9039b3b6fdfde9efa0c3d43 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-geneplotter/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-geneplotter + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-geneplotter/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-geneplotter/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-geneplotter/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomeinfodbdata/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomeinfodbdata/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..dc26f6e5aed612e1d00f134418a4dfb7f9cfe0cb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomeinfodbdata/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-genomeinfodbdata via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-genomeinfodbdata -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-genomeinfodbdata_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-genomeinfodbdata_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-genomeinfodbdata_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomeinfodbdata/app/bioconductor-genomeinfodbdata_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomeinfodbdata/app/bioconductor-genomeinfodbdata_server.py new file mode 100644 index 0000000000000000000000000000000000000000..01172e946bbc296476712c464e9a98a8dd117e2b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomeinfodbdata/app/bioconductor-genomeinfodbdata_server.py @@ -0,0 +1,180 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, List, Dict, Any + +# Set up a logger for better debugging and information +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') + +# This is a placeholder for the actual MCP decorator. +# The final code will be compatible with the MCP framework. +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 standalone script, it just acts as a pass-through. + wrapper.__doc__ = func.__doc__ + wrapper.__annotations__ = func.__annotations__ + return wrapper + +@mcp.tool +def rscript_runner( + script_file: Optional[Path] = None, + expressions: Optional[List[str]] = None, + script_args: Optional[List[str]] = None, + verbose: bool = False, + default_packages: Optional[str] = None, + vanilla: bool = False, + save: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: bool = False, + restore: bool = False, +) -> Dict[str, Any]: + """ + Executes an R script or R expressions using the Rscript command-line tool. + + This tool serves as a general-purpose wrapper for Rscript, allowing for the execution + of either a specified R script file or a list of R expressions. + + Args: + script_file: Path to the R script file to execute. Mutually exclusive with 'expressions'. + expressions: A list of R expressions to execute. Mutually exclusive with 'script_file'. + script_args: A list of arguments to be passed to the R script. + verbose: If True, enables verbose output from Rscript. + default_packages: A comma-separated list of package names to be loaded by default. + vanilla: If True, combines --no-save, --no-restore, --no-site-file, --no-init-file, and --no-environ. + This provides a "clean" R session. + save: If True, the workspace is saved at the end of the session. Ignored if 'vanilla' is True. + no_environ: If True, site and user environment files are not read. Ignored if 'vanilla' is True. + no_site_file: If True, the site-wide Rprofile is not read. Ignored if 'vanilla' is True. + no_init_file: If True, the user's R profile is not read. Ignored if 'vanilla' is True. + restore: If True, previously saved objects are restored at startup. Ignored if 'vanilla' is True. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of potential output files. + """ + # --- Input Validation --- + if not script_file and not expressions: + raise ValueError("You must provide either 'script_file' or 'expressions'.") + if script_file and expressions: + raise ValueError("'script_file' and 'expressions' are mutually exclusive.") + if script_file and not script_file.is_file(): + raise FileNotFoundError(f"The specified script file does not exist: {script_file}") + + # --- Command Construction --- + command = ["Rscript"] + + if vanilla: + command.append("--vanilla") + else: + if save: + command.append("--save") + if no_environ: + command.append("--no-environ") + if no_site_file: + command.append("--no-site-file") + if no_init_file: + command.append("--no-init-file") + if restore: + command.append("--restore") + + if verbose: + command.append("--verbose") + + if default_packages: + command.extend(["--default-packages", default_packages]) + + if expressions: + for expr in expressions: + command.extend(["-e", expr]) + + if script_file: + command.append(str(script_file)) + + if script_args: + command.extend(script_args) + + command_str = " ".join(command) + logging.info(f"Executing command: {command_str}") + + # --- Subprocess Execution --- + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + stdout = result.stdout + stderr = result.stderr + logging.info("Rscript executed successfully.") + + except FileNotFoundError: + logging.error("Rscript not found. Please ensure R is installed and in your system's PATH.") + raise + except subprocess.CalledProcessError as e: + logging.error(f"Rscript execution failed with return code {e.returncode}") + logging.error(f"Stderr: {e.stderr}") + logging.error(f"Stdout: {e.stdout}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + # --- Structured Result Return --- + # Note: Predicting output files from a generic script runner is not feasible. + # The user of this tool is responsible for knowing what files their script creates. + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": stderr, + "output_files": [] + } + +@mcp.tool +def rscript_version() -> Dict[str, Any]: + """ + Retrieves the version of the Rscript interpreter and the R language. + + This is equivalent to running 'Rscript --version' on the command line. + + Returns: + A dictionary containing the executed command and the version information + captured from stderr (as Rscript prints version info to stderr). + """ + command = ["Rscript", "--version"] + command_str = " ".join(command) + logging.info(f"Executing command: {command_str}") + + try: + # Rscript prints version information to stderr, so we capture it. + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + # The primary output is in stderr for the --version flag + version_info = result.stderr + + except FileNotFoundError: + logging.error("Rscript not found. Please ensure R is installed and in your system's PATH.") + raise + except subprocess.CalledProcessError as e: + logging.error(f"Rscript --version failed with return code {e.returncode}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + } + + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": version_info, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomeinfodbdata/app/bioconductor-genomeinfodbdata_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomeinfodbdata/app/bioconductor-genomeinfodbdata_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..08d533246b60c98b5a276012a57b31f2229d4d32 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomeinfodbdata/app/bioconductor-genomeinfodbdata_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomeinfodbdata/app/bioconductor-genomeinfodbdata_server.py') +SERVER_NAME = 'biosci_bioconductor_genomeinfodbdata' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomeinfodbdata/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomeinfodbdata/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomeinfodbdata/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomeinfodbdata/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomeinfodbdata/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..417a651e07b0490b797620fdf758562f52d5a1cb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomeinfodbdata/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-genomeinfodbdata: + build: . + image: mcp-bioconductor-genomeinfodbdata:latest + container_name: mcp-bioconductor-genomeinfodbdata + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-genomeinfodbdata + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomeinfodbdata/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomeinfodbdata/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e178851c0df5db898851d3336adcacfea12f5cad --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomeinfodbdata/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-genomeinfodbdata + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomeinfodbdata/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomeinfodbdata/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomeinfodbdata/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicalignments/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicalignments/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..1df8854d574f92a14aab64756ce0ad45c64c831b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicalignments/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-genomicalignments via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-genomicalignments -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-genomicalignments_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-genomicalignments_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-genomicalignments_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicalignments/app/bioconductor-genomicalignments_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicalignments/app/bioconductor-genomicalignments_server.py new file mode 100644 index 0000000000000000000000000000000000000000..79e51f43e85e32b85069400a61361f6ed6508abb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicalignments/app/bioconductor-genomicalignments_server.py @@ -0,0 +1,239 @@ +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") +""" + +# @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() diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicalignments/app/bioconductor-genomicalignments_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicalignments/app/bioconductor-genomicalignments_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..18433d2ebd827be8748dbeb101bb2b986e22a4f2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicalignments/app/bioconductor-genomicalignments_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicalignments/app/bioconductor-genomicalignments_server.py') +SERVER_NAME = 'biosci_bioconductor_genomicalignments' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicalignments/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicalignments/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicalignments/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicalignments/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicalignments/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..abb740c24ddfef04f23dc41a049518a7b7c7e21f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicalignments/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-genomicalignments: + build: . + image: mcp-bioconductor-genomicalignments:latest + container_name: mcp-bioconductor-genomicalignments + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-genomicalignments + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicalignments/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicalignments/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0d43bf092a97ea39850977042b15a1c8a2d642c7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicalignments/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-genomicalignments + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicalignments/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicalignments/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicalignments/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicfeatures/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicfeatures/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9ce330750f20d1fec8196e0bc3c8a1de5fbd3e99 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicfeatures/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-genomicfeatures via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-genomicfeatures -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-genomicfeatures_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-genomicfeatures_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-genomicfeatures_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicfeatures/app/bioconductor-genomicfeatures_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicfeatures/app/bioconductor-genomicfeatures_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c08cb1984359657020a5c6b1e1ca7e63d745eac3 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicfeatures/app/bioconductor-genomicfeatures_server.py @@ -0,0 +1,170 @@ +import subprocess +import tempfile +import shlex +from pathlib import Path +from typing import Optional, Dict, List + +# @mcp.tool() is a placeholder for the actual decorator. +# The code is written to be compatible with the MCP framework. + +@mcp.tool() +def make_txdb_from_gff( + gff_file: Path, + output_db_path: Path, + format: Optional[str] = None, + data_source: Optional[str] = None, + organism: Optional[str] = None, + taxonomy_id: Optional[int] = None, + chrominfo_file: Optional[Path] = None, + metadata_file: Optional[Path] = None, + pruning_mode: str = "coarse", + on_foreign_chrom: str = "abort", + infer_cds: bool = False, + infer_utr: bool = True, +) -> Dict: + """ + Creates a TranscriptDb (TxDb) SQLite database from a GFF or GTF file. + + This tool serves as a wrapper for the `makeTxDbFromGFF` function from the + R/Bioconductor GenomicFeatures package. It parses a gene annotation file + (GFF3 or GTF) and stores the transcript metadata in a structured SQLite + database, which is highly efficient for downstream analysis. + + Args: + gff_file: Path to the input GFF3 or GTF file. + output_db_path: Path where the output SQLite TxDb file will be saved. + format: The format of the input file. Can be 'gff3' or 'gtf'. + If not provided, the tool attempts to infer it from the file extension. + data_source: A string describing the source of the data (e.g., "Ensembl v104"). + organism: The scientific name of the organism (e.g., "Homo sapiens"). + taxonomy_id: The NCBI Taxonomy ID for the organism. + chrominfo_file: Optional path to a two-column, tab-separated file containing + chromosome names and their lengths. + metadata_file: Optional path to a two-column, tab-separated file containing + metadata as name-value pairs to be stored in the database. + pruning_mode: Sets the strictness for handling problematic transcripts. + Must be one of 'coarse', 'fine', or 'strict'. + on_foreign_chrom: Action to take for features on chromosomes not listed in + `chrominfo_file`. Must be one of 'abort', 'drop', or 'as.is'. + infer_cds: If TRUE, infer CDS features from annotated stop codons. + infer_utr: If TRUE, infer UTR features (5' and 3') when not explicitly provided. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a + mapping to the generated output database file. + """ + # 1. Input Validation + if not gff_file.is_file(): + raise FileNotFoundError(f"Input GFF/GTF file not found: {gff_file}") + + if chrominfo_file and not chrominfo_file.is_file(): + raise FileNotFoundError(f"Chrominfo file not found: {chrominfo_file}") + + if metadata_file and not metadata_file.is_file(): + raise FileNotFoundError(f"Metadata file not found: {metadata_file}") + + if format and format.lower() not in ["gff3", "gtf"]: + raise ValueError("Parameter 'format' must be either 'gff3' or 'gtf'.") + + allowed_pruning = ["coarse", "fine", "strict"] + if pruning_mode not in allowed_pruning: + raise ValueError(f"Parameter 'pruning_mode' must be one of {allowed_pruning}.") + + allowed_foreign_chrom = ["abort", "drop", "as.is"] + if on_foreign_chrom not in allowed_foreign_chrom: + raise ValueError(f"Parameter 'on_foreign_chrom' must be one of {allowed_foreign_chrom}.") + + output_db_path.parent.mkdir(parents=True, exist_ok=True) + + # 2. R Script Generation + # Use R-friendly paths (forward slashes) for cross-platform compatibility + gff_file_r = str(gff_file).replace('\\', '/') + output_db_path_r = str(output_db_path).replace('\\', '/') + + r_script_lines = [ + "suppressPackageStartupMessages(library(GenomicFeatures))", + "", + "# Build the argument list for makeTxDbFromGFF", + f'txdb_args <- list(file = "{gff_file_r}")', + ] + + # Add optional arguments to the list + if format: + r_script_lines.append(f'txdb_args$format <- "{format.lower()}"') + if data_source: + r_script_lines.append(f'txdb_args$dataSource <- "{data_source}"') + if organism: + r_script_lines.append(f'txdb_args$organism <- "{organism}"') + if taxonomy_id is not None: + r_script_lines.append(f'txdb_args$taxonomyId <- {taxonomy_id}') + + r_script_lines.append(f'txdb_args$pruning.mode <- "{pruning_mode}"') + r_script_lines.append(f'txdb_args$on.foreign.chrom <- "{on_foreign_chrom}"') + r_script_lines.append(f'txdb_args$infer_cds <- {"TRUE" if infer_cds else "FALSE"}') + r_script_lines.append(f'txdb_args$infer_utr <- {"TRUE" if infer_utr else "FALSE"}') + + if chrominfo_file: + chrominfo_file_r = str(chrominfo_file).replace('\\', '/') + r_script_lines.extend([ + f'chrominfo_df <- read.table("{chrominfo_file_r}", sep="\\t", header=FALSE, col.names=c("chrom", "length"), stringsAsFactors=FALSE)', + 'txdb_args$chrominfo <- chrominfo_df' + ]) + + if metadata_file: + metadata_file_r = str(metadata_file).replace('\\', '/') + r_script_lines.extend([ + f'metadata_df <- read.table("{metadata_file_r}", sep="\\t", header=FALSE, col.names=c("name", "value"), stringsAsFactors=FALSE)', + 'txdb_args$metadata <- metadata_df' + ]) + + r_script_lines.extend([ + "", + "# Execute the function with the constructed arguments", + "txdb <- do.call(makeTxDbFromGFF, txdb_args)", + "", + "# Save the resulting database", + f'saveDb(txdb, file="{output_db_path_r}")', + 'message("TxDb database created successfully.")' + ]) + + r_script_content = "\n".join(r_script_lines) + + script_path = None + try: + with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R", encoding='utf-8') as r_script_file: + r_script_file.write(r_script_content) + script_path = r_script_file.name + + # 3. Subprocess Execution + cmd = ["Rscript", script_path] + command_executed = shlex.join(cmd) + + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + encoding='utf-8' + ) + + # 4. Structured Result Return + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"txdb_database": str(output_db_path)} + } + + except subprocess.CalledProcessError as e: + # R often prints errors to stdout, so combine them for a comprehensive message + error_message = ( + f"R script execution failed with exit code {e.returncode}.\n" + f"STDOUT:\n{e.stdout}\n" + f"STDERR:\n{e.stderr}\n" + ) + raise RuntimeError(error_message) from e + + finally: + # Clean up the temporary script file + if script_path and Path(script_path).exists(): + Path(script_path).unlink() diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicfeatures/app/bioconductor-genomicfeatures_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicfeatures/app/bioconductor-genomicfeatures_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..74beea75c4dc00d1eca821fc4bdd3c69b4163675 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicfeatures/app/bioconductor-genomicfeatures_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicfeatures/app/bioconductor-genomicfeatures_server.py') +SERVER_NAME = 'biosci_bioconductor_genomicfeatures' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicfeatures/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicfeatures/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicfeatures/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicfeatures/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicfeatures/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..0ed64c15246a6e42f3ed448bcf13f62762db3b12 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicfeatures/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-genomicfeatures: + build: . + image: mcp-bioconductor-genomicfeatures:latest + container_name: mcp-bioconductor-genomicfeatures + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-genomicfeatures + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicfeatures/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicfeatures/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..077be5894b7e52c31a6f405538213f1090d401b7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicfeatures/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-genomicfeatures + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicfeatures/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicfeatures/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-genomicfeatures/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-go.db/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-go.db/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2069a4e8592c1da90c7837bb6d4c45e57bd872d8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-go.db/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-go.db via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-go.db -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-go.db_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-go.db_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-go.db_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-go.db/app/bioconductor-go.db_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-go.db/app/bioconductor-go.db_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4a09956198630ec0735b212eb2a3f512798d6621 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-go.db/app/bioconductor-go.db_server.py @@ -0,0 +1,188 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any + +# MCP decorator is not imported as per instructions. +# It is assumed to be available in the execution environment. + +# @mcp.tool() +def list_go_db_columns() -> Dict[str, Any]: + """ + Lists all available columns for querying in the Bioconductor GO.db. + + This function executes an R script to load the GO.db package and + extract the names of all queryable columns. It is useful for discovering + what data can be retrieved using the `query_go_db` function. + + Requirements: + - R must be installed and in the system's PATH. + - The R packages 'BiocManager', 'AnnotationDbi', and 'GO.db' must be installed. + (e.g., in R: BiocManager::install(c("AnnotationDbi", "GO.db"))) + """ + r_script = "library(GO.db); cat(columns(GO.db), sep='\\n')" + command = ["Rscript", "-e", r_script] + command_executed = " ".join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + # The columns are returned as a newline-separated string + columns_list = result.stdout.strip().split('\n') + return { + "command_executed": command_executed, + "stdout": f"Available columns: {', '.join(columns_list)}", + "stderr": result.stderr, + "columns": columns_list, + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'Rscript' not found. Please ensure R is installed and in your PATH.", + "error": "Dependency not found" + } + except subprocess.CalledProcessError as e: + stderr = e.stderr + if "there is no package called" in stderr: + stderr += "\n\nHint: Please ensure the 'GO.db' and 'AnnotationDbi' R packages are installed." + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": stderr, + "error": "R script execution failed" + } + +# @mcp.tool() +def query_go_db( + go_ids: List[str], + columns: Optional[List[str]] = None, + output_file: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Query the Bioconductor GO.db to retrieve information about Gene Ontology terms. + + This tool uses R/Bioconductor's GO.db annotation package to fetch details + for a given list of GO IDs. You can specify which columns of data to retrieve. + + Requirements: + - R must be installed and in the system's PATH. + - The R packages 'BiocManager', 'AnnotationDbi', and 'GO.db' must be installed. + (e.g., in R: BiocManager::install(c("AnnotationDbi", "GO.db"))) + + Args: + go_ids: A list of Gene Ontology (GO) IDs to query (e.g., ['GO:0005575', 'GO:0008150']). + columns: A list of columns to retrieve. Defaults to ['GOID', 'TERM', 'DEFINITION', 'ONTOLOGY']. + Use the `list_go_db_columns` tool to see all available columns. + output_file: Optional path to save the output as a tab-separated (TSV) file. + If not provided, the output is returned in stdout. + """ + # --- Input Validation --- + if not go_ids: + raise ValueError("The 'go_ids' list cannot be empty.") + + for go_id in go_ids: + if not isinstance(go_id, str) or not go_id.startswith("GO:"): + raise ValueError(f"Invalid GO ID format: '{go_id}'. Expected format is 'GO:#######'.") + + if columns is None: + # Default columns provide the most common information + columns_to_query = ["GOID", "TERM", "DEFINITION", "ONTOLOGY"] + else: + if not isinstance(columns, list) or not all(isinstance(c, str) for c in columns): + raise TypeError("The 'columns' parameter must be a list of strings.") + columns_to_query = columns + + # --- R Script Construction --- + # Convert Python lists to R vector syntax: c("item1", "item2") + r_go_ids = 'c({})'.format(','.join(f'"{gid}"' for gid in go_ids)) + r_columns = 'c({})'.format(','.join(f'"{col}"' for col in columns_to_query)) + + # Using a temporary file for the output if no output_file is specified by the user + # This avoids complex stdout redirection and ensures clean capture + temp_dir = tempfile.TemporaryDirectory() + final_output_path = Path(output_file) if output_file else Path(temp_dir.name) / "go_query_results.tsv" + + r_script = f""" + # Suppress package startup messages for cleaner output + suppressPackageStartupMessages(library(AnnotationDbi)) + suppressPackageStartupMessages(library(GO.db)) + + go_keys <- {r_go_ids} + cols_to_get <- {r_columns} + output_path <- "{str(final_output_path)}" + + # Perform the query + results <- tryCatch( + AnnotationDbi::select(GO.db, keys=go_keys, columns=cols_to_get, keytype="GOID"), + error = function(e) {{ + write(paste("Error during AnnotationDbi::select:", e$message), stderr()) + return(NULL) + }} + ) + + # Write results to the specified output file + if (!is.null(results)) {{ + write.table( + results, + file=output_path, + sep="\\t", + row.names=FALSE, + quote=FALSE + ) + }} + """ + + command = ["Rscript", "-e", r_script] + command_executed = " ".join(command) + output_files_list = [] + + try: + # --- Subprocess Execution --- + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + + stdout_content = "" + if final_output_path.exists() and final_output_path.stat().st_size > 0: + output_files_list.append(str(final_output_path)) + # If no output file was requested by the user, read the temp file content for stdout + if not output_file: + stdout_content = final_output_path.read_text() + else: + # Handle cases where the R script runs but produces no output (e.g., no matches) + stdout_content = "Query executed successfully, but no results were found for the given GO IDs." + + return { + "command_executed": command_executed, + "stdout": stdout_content, + "stderr": result.stderr, + "output_files": output_files_list, + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'Rscript' not found. Please ensure R is installed and in your PATH.", + "error": "Dependency not found" + } + except subprocess.CalledProcessError as e: + stderr = e.stderr + if "there is no package called" in stderr: + stderr += "\n\nHint: Please ensure the 'GO.db' and 'AnnotationDbi' R packages are installed." + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": stderr, + "error": "R script execution failed" + } + finally: + # Clean up the temporary directory + temp_dir.cleanup() diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-go.db/app/bioconductor-go.db_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-go.db/app/bioconductor-go.db_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..bfcac25303616fc3345c9ddbc3e5a66e85099288 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-go.db/app/bioconductor-go.db_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-go.db/app/bioconductor-go.db_server.py') +SERVER_NAME = 'biosci_bioconductor_go_db' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-go.db/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-go.db/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-go.db/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-go.db/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-go.db/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..bcb222a73c2f27a64f265287d9ff4aa040928e68 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-go.db/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-go.db: + build: . + image: mcp-bioconductor-go.db:latest + container_name: mcp-bioconductor-go.db + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-go.db + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-go.db/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-go.db/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0607214ee0c410fe2635325e9264b0cba5fd89bb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-go.db/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-go.db + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-go.db/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-go.db/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-go.db/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gosemsim/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gosemsim/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..79759355a85d632d7922ea3c56930957dd4d59fa --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gosemsim/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-gosemsim via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-gosemsim -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-gosemsim_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-gosemsim_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-gosemsim_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gosemsim/app/bioconductor-gosemsim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gosemsim/app/bioconductor-gosemsim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ebbc0235d7f4f0bbde1d9573e8b5c8e69843c7f9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gosemsim/app/bioconductor-gosemsim_server.py @@ -0,0 +1,273 @@ +import subprocess +import json +import tempfile +from pathlib import Path +from typing import List, Optional, Literal, Union + +@mcp.tool() +def go_similarity( + term1: str, + term2: str, + org_db: str = "org.Hs.eg.db", + ont: Literal["BP", "MF", "CC"] = "BP", + measure: Literal["Resnik", "Lin", "Rel", "Jiang", "Wang"] = "Wang", + keytype: str = "ENTREZID" +): + """ + Calculate semantic similarity between two GO terms using GOSemSim. + + Args: + term1: First GO term ID (e.g., 'GO:0004022'). + term2: Second GO term ID (e.g., 'GO:0005515'). + org_db: The annotation OrgDb package (e.g., 'org.Hs.eg.db' for human). + ont: One of "BP", "MF", or "CC" ontologies. + measure: Semantic similarity method ("Resnik", "Lin", "Rel", "Jiang", or "Wang"). + keytype: Key type of the gene identifiers in the OrgDb. + """ + if not term1.startswith("GO:") or not term2.startswith("GO:"): + return {"error": "GO terms must start with 'GO:' prefix."} + + r_script = f""" + suppressPackageStartupMessages(library(GOSemSim)) + suppressPackageStartupMessages(library({org_db})) + + hsGO <- godata('{org_db}', ont='{ont}', computeIC=TRUE, keytype='{keytype}') + sim <- goSim('{term1}', '{term2}', semData=hsGO, measure='{measure}') + cat(sim) + """ + + return _execute_r_script(r_script) + +@mcp.tool() +def mgo_similarity( + terms: List[str], + org_db: str = "org.Hs.eg.db", + ont: Literal["BP", "MF", "CC"] = "BP", + measure: Literal["Resnik", "Lin", "Rel", "Jiang", "Wang"] = "Wang", + keytype: str = "ENTREZID" +): + """ + Calculate semantic similarity matrix for a list of GO terms. + + Args: + terms: List of GO term IDs. + org_db: The annotation OrgDb package. + ont: One of "BP", "MF", or "CC" ontologies. + measure: Semantic similarity method. + keytype: Key type of the gene identifiers. + """ + terms_r = 'c("' + '","'.join(terms) + '")' + r_script = f""" + suppressPackageStartupMessages(library(GOSemSim)) + suppressPackageStartupMessages(library({org_db})) + + hsGO <- godata('{org_db}', ont='{ont}', computeIC=TRUE, keytype='{keytype}') + sim_matrix <- mgoSim({terms_r}, semData=hsGO, measure='{measure}', combine=NULL) + write.csv(sim_matrix, row.names=TRUE) + """ + + return _execute_r_script(r_script) + +@mcp.tool() +def gene_similarity( + gene1: str, + gene2: str, + org_db: str = "org.Hs.eg.db", + ont: Literal["BP", "MF", "CC"] = "BP", + measure: Literal["Resnik", "Lin", "Rel", "Jiang", "Wang"] = "Wang", + combine: Literal["max", "avg", "rcmax", "BMA"] = "BMA", + keytype: str = "ENTREZID" +): + """ + Calculate semantic similarity between two genes based on their GO annotations. + + Args: + gene1: First gene ID. + gene2: Second gene ID. + org_db: The annotation OrgDb package. + ont: One of "BP", "MF", or "CC" ontologies. + measure: Semantic similarity method. + combine: Strategy to combine similarities of multiple GO terms ("max", "avg", "rcmax", "BMA"). + keytype: Key type of the gene identifiers (e.g., 'ENTREZID', 'SYMBOL'). + """ + r_script = f""" + suppressPackageStartupMessages(library(GOSemSim)) + suppressPackageStartupMessages(library({org_db})) + + hsGO <- godata('{org_db}', ont='{ont}', computeIC=TRUE, keytype='{keytype}') + sim <- geneSim('{gene1}', '{gene2}', semData=hsGO, measure='{measure}', combine='{combine}') + print(sim) + """ + + return _execute_r_script(r_script) + +@mcp.tool() +def mgene_similarity( + genes: List[str], + org_db: str = "org.Hs.eg.db", + ont: Literal["BP", "MF", "CC"] = "BP", + measure: Literal["Resnik", "Lin", "Rel", "Jiang", "Wang"] = "Wang", + combine: Literal["max", "avg", "rcmax", "BMA"] = "BMA", + keytype: str = "ENTREZID" +): + """ + Calculate semantic similarity matrix for a list of genes. + + Args: + genes: List of gene IDs. + org_db: The annotation OrgDb package. + ont: One of "BP", "MF", or "CC" ontologies. + measure: Semantic similarity method. + combine: Strategy to combine similarities. + keytype: Key type of the gene identifiers. + """ + genes_r = 'c("' + '","'.join(genes) + '")' + r_script = f""" + suppressPackageStartupMessages(library(GOSemSim)) + suppressPackageStartupMessages(library({org_db})) + + hsGO <- godata('{org_db}', ont='{ont}', computeIC=TRUE, keytype='{keytype}') + sim_matrix <- mgeneSim({genes_r}, semData=hsGO, measure='{measure}', combine='{combine}') + write.csv(sim_matrix, row.names=TRUE) + """ + + return _execute_r_script(r_script) + +@mcp.tool() +def cluster_similarity( + cluster1: List[str], + cluster2: List[str], + org_db: str = "org.Hs.eg.db", + ont: Literal["BP", "MF", "CC"] = "BP", + measure: Literal["Resnik", "Lin", "Rel", "Jiang", "Wang"] = "Wang", + combine: Literal["max", "avg", "rcmax", "BMA"] = "BMA", + keytype: str = "ENTREZID" +): + """ + Calculate semantic similarity between two clusters (sets) of genes. + + Args: + cluster1: List of gene IDs in the first cluster. + cluster2: List of gene IDs in the second cluster. + org_db: The annotation OrgDb package. + ont: One of "BP", "MF", or "CC" ontologies. + measure: Semantic similarity method. + combine: Strategy to combine similarities. + keytype: Key type of the gene identifiers. + """ + c1_r = 'c("' + '","'.join(cluster1) + '")' + c2_r = 'c("' + '","'.join(cluster2) + '")' + + r_script = f""" + suppressPackageStartupMessages(library(GOSemSim)) + suppressPackageStartupMessages(library({org_db})) + + hsGO <- godata('{org_db}', ont='{ont}', computeIC=TRUE, keytype='{keytype}') + sim <- clusterSim({c1_r}, {c2_r}, semData=hsGO, measure='{measure}', combine='{combine}') + cat(sim) + """ + + return _execute_r_script(r_script) + +@mcp.tool() +def mcluster_similarity( + clusters_json: str, + org_db: str = "org.Hs.eg.db", + ont: Literal["BP", "MF", "CC"] = "BP", + measure: Literal["Resnik", "Lin", "Rel", "Jiang", "Wang"] = "Wang", + combine: Literal["max", "avg", "rcmax", "BMA"] = "BMA", + keytype: str = "ENTREZID" +): + """ + Calculate semantic similarity matrix between multiple clusters of genes. + + Args: + clusters_json: A JSON string representing a dictionary where keys are cluster names + and values are lists of gene IDs. + org_db: The annotation OrgDb package. + ont: One of "BP", "MF", or "CC" ontologies. + measure: Semantic similarity method. + combine: Strategy to combine similarities. + keytype: Key type of the gene identifiers. + """ + try: + clusters_dict = json.loads(clusters_json) + except json.JSONDecodeError: + return {"error": "Invalid JSON format for clusters_json."} + + # Construct R list of character vectors + r_list_elements = [] + for name, genes in clusters_dict.items(): + genes_str = 'c("' + '","'.join(genes) + '")' + r_list_elements.append(f'"{name}" = {genes_str}') + + clusters_r = "list(" + ", ".join(r_list_elements) + ")" + + r_script = f""" + suppressPackageStartupMessages(library(GOSemSim)) + suppressPackageStartupMessages(library({org_db})) + + hsGO <- godata('{org_db}', ont='{ont}', computeIC=TRUE, keytype='{keytype}') + clusters <- {clusters_r} + sim_matrix <- mclusterSim(clusters, semData=hsGO, measure='{measure}', combine='{combine}') + write.csv(sim_matrix, row.names=TRUE) + """ + + return _execute_r_script(r_script) + +def _execute_r_script(script_content: str): + """ + Internal helper to execute R code via Rscript. + """ + with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp: + tmp.write(script_content) + tmp_path = tmp.name + + try: + # Note: We assume Rscript is in the PATH and GOSemSim is installed. + # If using a specific conda environment, the user should run the MCP server within it. + result = subprocess.run( + ["Rscript", tmp_path], + capture_output=True, + text=True, + check=True + ) + + return { + "command_executed": f"Rscript {tmp_path}", + "stdout": result.stdout.strip(), + "stderr": result.stderr.strip(), + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": f"Rscript {tmp_path}", + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R execution failed. Ensure R and GOSemSim are installed and the OrgDb package is available.", + "status": "error" + } + finally: + if Path(tmp_path).exists(): + Path(tmp_path).unlink() + +@mcp.tool() +def list_supported_orgdbs(): + """ + Returns a list of commonly used Bioconductor OrgDb packages for GOSemSim. + """ + org_dbs = { + "human": "org.Hs.eg.db", + "mouse": "org.Mm.eg.db", + "rat": "org.Rn.eg.db", + "fly": "org.Dm.eg.db", + "zebrafish": "org.Dr.eg.db", + "yeast": "org.Sc.sgd.db", + "arabidopsis": "org.At.tair.db", + "chicken": "org.Gg.eg.db", + "bovine": "org.Bt.eg.db", + "worm": "org.Ce.eg.db", + "pig": "org.Ss.eg.db", + "rhesus": "org.Mmu.eg.db" + } + return {"supported_org_dbs": org_dbs} \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gosemsim/app/bioconductor-gosemsim_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gosemsim/app/bioconductor-gosemsim_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6fe69ca16f4eb0f0c51ade0c53de6bdc8df84fff --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gosemsim/app/bioconductor-gosemsim_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gosemsim/app/bioconductor-gosemsim_server.py') +SERVER_NAME = 'biosci_bioconductor_gosemsim' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gosemsim/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gosemsim/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gosemsim/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gosemsim/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gosemsim/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e0264312aed56c58603128d118ddb6f05d42616d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gosemsim/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-gosemsim: + build: . + image: mcp-bioconductor-gosemsim:latest + container_name: mcp-bioconductor-gosemsim + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-gosemsim + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gosemsim/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gosemsim/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8f13aa43e05a5c4edac218b82b7b0981931e9030 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gosemsim/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-gosemsim + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gosemsim/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gosemsim/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gosemsim/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-graph/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-graph/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d094aacd7f9cef99a6c0332a22fdfeb4a493e2f8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-graph/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-graph via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-graph -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-graph_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-graph_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-graph_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-graph/app/bioconductor-graph_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-graph/app/bioconductor-graph_server.py new file mode 100644 index 0000000000000000000000000000000000000000..11340420d6881d042ecb132835d015e02de86e6c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-graph/app/bioconductor-graph_server.py @@ -0,0 +1,127 @@ +import subprocess +import shlex +from pathlib import Path +from typing import Optional, List + +# Assuming mcp is available in the environment +# import mcp + +@mcp.tool() +def rscript( + script_file: Optional[Path] = None, + expression: Optional[str] = None, + script_args: Optional[List[str]] = None, + verbose: bool = False, + default_packages: Optional[List[str]] = None, + slave: bool = False, + no_environ: bool = False, + no_site_file: bool = False, + no_init_file: bool = False, + restore: bool = False, + save: bool = False, + no_renviron: bool = False, +): + """ + Executes an R script or a given R expression using the Rscript front-end. + + This tool serves as a wrapper around the command-line Rscript utility, + allowing for non-interactive execution of R code. You must provide either + a path to an R script file or an R expression string. + + Args: + script_file: Path to the R script file to be executed. + expression: A string containing one or more R expressions to be evaluated. + script_args: A list of arguments to be passed to the R script itself. + verbose: If True, prints more information on progress. Corresponds to --verbose. + default_packages: A list of R packages to be attached on startup. + Defaults to 'datasets,utils,grDevices,graphics,stats,methods'. + slave: If True, makes R run as quietly as possible. Corresponds to --slave. + no_environ: If True, does not read the site and user environment files. + no_site_file: If True, does not read the site-wide Rprofile. + no_init_file: If True, does not read the user Rprofile. + restore: If True, restores the previously saved workspace. + save: If True, saves the workspace at the end of the session. + no_renviron: If True, does not read the site or user Renviron files. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # 1. Input Validation + if not (script_file or expression): + raise ValueError("You must provide either 'script_file' or 'expression'.") + if script_file and expression: + raise ValueError("You cannot provide both 'script_file' and 'expression'.") + + if script_file: + if not script_file.is_file(): + raise FileNotFoundError(f"The specified script file does not exist: {script_file}") + + # 2. Command Construction + cmd = ["Rscript"] + + if verbose: + cmd.append("--verbose") + if slave: + cmd.append("--slave") + 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 save: + cmd.append("--save") + if no_renviron: + cmd.append("--no-Renviron") + + if default_packages: + packages_str = ",".join(default_packages) + cmd.append(f"--default-packages={packages_str}") + + if expression: + cmd.extend(["-e", expression]) + elif script_file: + cmd.append(str(script_file)) + + if script_args: + cmd.extend(script_args) + + command_executed = shlex.join(cmd) + + # 3. Subprocess Execution + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + stdout = result.stdout + stderr = result.stderr + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'Rscript' command not found. Please ensure R is installed and in your system's PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + # 4. Structured Result Return + # Rscript itself doesn't have a dedicated output file parameter. + # Any files created are the result of the script's own logic. + # We return an empty list here, as the tool wrapper cannot know what files the script might create. + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-graph/app/bioconductor-graph_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-graph/app/bioconductor-graph_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e2649db66c771f5a1aa62604294606d3828ca08d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-graph/app/bioconductor-graph_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-graph/app/bioconductor-graph_server.py') +SERVER_NAME = 'biosci_bioconductor_graph' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-graph/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-graph/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-graph/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-graph/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-graph/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e381d6f96261f88e640b44f179e11c5daaf6a92d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-graph/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-graph: + build: . + image: mcp-bioconductor-graph:latest + container_name: mcp-bioconductor-graph + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-graph + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-graph/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-graph/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bf5c6395ba1581a2cb6bfed8ca295707e071d324 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-graph/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-graph + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-graph/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-graph/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-graph/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gsva/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gsva/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8ebd79da057998281de6f71ad1cfb659acc1f297 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gsva/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.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-gsva via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-gsva -y && conda clean -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-gsva_server.py /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-gsva_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --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-gsva_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gsva/app/bioconductor-gsva_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gsva/app/bioconductor-gsva_server.py new file mode 100644 index 0000000000000000000000000000000000000000..58fb676f7ac21eb2dc924b9e2f5894575e0aedf5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gsva/app/bioconductor-gsva_server.py @@ -0,0 +1,207 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, Literal, List +import sys + +# MCP decorator placeholder, as per the instructions. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +@mcp.tool() +def gsva( + expr_file: Path, + gene_sets_file: Path, + output_file: Optional[Path] = None, + method: Literal["gsva", "ssgsea", "zscore", "plage"] = "gsva", + kcdf: Literal["Gaussian", "Poisson", "none"] = "Gaussian", + abs_ranking: bool = False, + min_sz: int = 1, + max_sz: Optional[int] = None, + parallel_sz: int = 1, + mx_diff: bool = True, + tau: float = 1.0, + ssgsea_norm: bool = True, + verbose: bool = True, +) -> dict: + """ + Performs Gene Set Variation Analysis (GSVA) on gene expression data. + + This tool is a wrapper around the `gsva` function from the Bioconductor GSVA package. + It calculates sample-wise gene set enrichment scores as a function of genes inside and + outside the gene set, respectively. The tool requires R and the 'Rscript' + executable to be in the system's PATH. + + Args: + expr_file: Path to the gene expression data file (e.g., TSV, CSV). + The file should have genes as rows and samples as columns. + The first column must contain unique gene identifiers. + gene_sets_file: Path to the gene sets file in GMT format. + output_file: Optional path for the output TSV file. If not provided, a file + named 'gsva_results.tsv' will be created in a temporary directory + and its path will be returned. + method: The GSVA method to use. + kcdf: Character string denoting the kernel to use during the non-parametric + estimation of the cumulative distribution function of expression + levels across samples. 'Gaussian' is recommended for continuous data, + 'Poisson' for integer counts. + abs_ranking: For 'gsva' method, whether to use absolute values of rankings. + min_sz: Minimum size of the gene sets to be considered. + max_sz: Maximum size of the gene sets to be considered. If None, no maximum size is enforced. + parallel_sz: Number of parallel processes to use (cores). + mx_diff: For 'gsva' and 'ssgsea' methods, whether to calculate enrichment scores + as the difference between the largest positive and negative deviations + from the random walk. + tau: Exponent defining the weight of the tail in the random walk score. + Only used for the 'gsva' method. + ssgsea_norm: For 'ssgsea' method, whether to normalize enrichment scores. + verbose: If True, the R script will print progress messages to stdout. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not expr_file.exists(): + raise FileNotFoundError(f"Expression file not found: {expr_file}") + if not gene_sets_file.exists(): + raise FileNotFoundError(f"Gene sets file not found: {gene_sets_file}") + if min_sz < 0: + raise ValueError("min_sz must be a non-negative integer.") + if max_sz is not None and max_sz < min_sz: + raise ValueError("max_sz must be greater than or equal to min_sz.") + if parallel_sz < 1: + raise ValueError("parallel_sz must be at least 1.") + if tau <= 0 and method == "gsva": + raise ValueError("tau must be a positive number for the 'gsva' method.") + + with tempfile.TemporaryDirectory() as temp_dir: + temp_path = Path(temp_dir) + + # Define output file path + if output_file: + # Ensure output directory exists + output_file.parent.mkdir(parents=True, exist_ok=True) + final_output_path = output_file + else: + final_output_path = temp_path / "gsva_results.tsv" + + r_script_path = temp_path / "run_gsva.R" + + # Convert Python types to R-compatible strings + r_abs_ranking = "TRUE" if abs_ranking else "FALSE" + r_mx_diff = "TRUE" if mx_diff else "FALSE" + r_ssgsea_norm = "TRUE" if ssgsea_norm else "FALSE" + r_verbose = "TRUE" if verbose else "FALSE" + r_max_sz = "Inf" if max_sz is None else str(max_sz) + + # --- R Script Generation --- + r_script_content = f""" + # This script automatically installs required Bioconductor packages. + if (!requireNamespace("BiocManager", quietly = TRUE)) + install.packages("BiocManager", repos="http://cran.us.r-project.org") + + packages <- c("GSVA", "GSEABase") + for (pkg in packages) {{ + if (!require(pkg, character.only = TRUE)) {{ + cat(paste("Installing", pkg, "...\\n")) + BiocManager::install(pkg, update=FALSE, ask=FALSE) + library(pkg, character.only = TRUE) + }} + }} + + # --- Arguments --- + expr_file <- "{expr_file.resolve()}" + gene_sets_file <- "{gene_sets_file.resolve()}" + output_file <- "{final_output_path.resolve()}" + method <- "{method}" + kcdf <- "{kcdf}" + abs_ranking <- {r_abs_ranking} + min_sz <- {min_sz} + max_sz <- {r_max_sz} + parallel_sz <- {parallel_sz} + mx_diff <- {r_mx_diff} + tau <- {tau} + ssgsea_norm <- {r_ssgsea_norm} + verbose <- {r_verbose} + + # --- Data Loading --- + if (verbose) cat("Loading expression data from:", expr_file, "\\n") + # Assuming a standard tab-separated file with a header and row names (gene IDs) + expr_data <- tryCatch({{ + as.matrix(read.table(expr_file, header=TRUE, row.names=1, sep='\\t', check.names=FALSE, quote="")) + }}, error = function(e) {{ + # Try with comma separator if tab fails + if (verbose) cat("Failed to read as TSV, trying CSV...\\n") + as.matrix(read.table(expr_file, header=TRUE, row.names=1, sep=',', check.names=FALSE, quote="")) + }}) + + if (verbose) cat("Loading gene sets from:", gene_sets_file, "\\n") + gene_sets <- getGmt(gene_sets_file) + + # --- Run GSVA --- + if (verbose) cat("Running GSVA with method:", method, "\\n") + gsva_results <- gsva( + expr = expr_data, + gset.idx.list = gene_sets, + method = method, + kcdf = kcdf, + abs.ranking = abs_ranking, + min.sz = min_sz, + max.sz = max_sz, + parallel.sz = parallel_sz, + mx.diff = mx_diff, + tau = tau, + ssgsea.norm = ssgsea_norm, + verbose = verbose + ) + + # --- Save Results --- + if (verbose) cat("Saving results to:", output_file, "\\n") + write.table(gsva_results, file=output_file, sep='\\t', quote=FALSE, col.names=NA) + + if (verbose) cat("GSVA analysis completed successfully.\\n") + """ + + with open(r_script_path, "w") as f: + f.write(r_script_content) + + # --- Subprocess Execution --- + command = ["Rscript", str(r_script_path)] + command_str = " ".join(map(str, command)) + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + cwd=temp_path, + ) + + output_files_list = [str(final_output_path)] if final_output_path.exists() else [] + + return { + "command_executed": command_str, + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files_list, + } + except FileNotFoundError: + # This happens if 'Rscript' is not in the system's PATH + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: 'Rscript' command not found. Please ensure R is installed and in your system's PATH.", + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gsva/app/bioconductor-gsva_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gsva/app/bioconductor-gsva_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8dafc62d85ac13e71d61dc3c4f3314ba10270b03 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gsva/app/bioconductor-gsva_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gsva/app/bioconductor-gsva_server.py') +SERVER_NAME = 'biosci_bioconductor_gsva' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gsva/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gsva/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b4964f9f87d7439fea449eca0d8b3eb185825066 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gsva/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-gsva: + build: . + image: mcp-bioconductor-gsva:latest + container_name: mcp-bioconductor-gsva + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-gsva + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gsva/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gsva/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..198d9d117bd9b55b6abc459e12bbedf2ab5a8b35 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gsva/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-gsva + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gsva/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gsva/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-gsva/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-infercnv/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-infercnv/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2a7999e32fcac07aa795437e3ed33b833e69b59f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-infercnv/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.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-infercnv via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-infercnv -y && conda clean -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-infercnv_server.py /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-infercnv_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --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-infercnv_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-infercnv/app/bioconductor-infercnv_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-infercnv/app/bioconductor-infercnv_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8683bd1fa8381f10ed74f5e0bee078ca4e8b0a0d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-infercnv/app/bioconductor-infercnv_server.py @@ -0,0 +1,290 @@ +import subprocess +import os +from pathlib import Path +from typing import Optional, List +import tempfile +import shlex + +@mcp.tool() +def infercnv_run( + raw_counts_matrix: str, + annotations_file: str, + gene_order_file: str, + out_dir: str, + ref_group_names: Optional[List[str]] = None, + cutoff: float = 1.0, + min_cells_per_gene: int = 3, + cluster_by_groups: bool = True, + denoise: bool = False, + hmm: bool = False, + hmm_type: str = "i6", + analysis_mode: str = "samples", + num_threads: int = 1, + plot_steps: bool = False, + no_plot: bool = False, + window_length: int = 101, + max_centered_threshold: float = 3.0, + leiden_resolution: float = 0.05, +): + """ + Run the full InferCNV pipeline to identify somatic copy number alterations in single-cell RNA-seq data. + + Args: + raw_counts_matrix: Path to the matrix of gene expression counts (genes as rows, cells as columns). + annotations_file: Path to the cell annotations file (cell name and group). + gene_order_file: Path to the gene positions file (gene, chromosome, start, stop). + out_dir: Directory to save the output files. + ref_group_names: List of group names to use as reference (normal) cells. If None, all cells are used. + cutoff: Threshold for gene expression. Use 1.0 for Smart-seq2 and 0.1 for 10x Genomics. + min_cells_per_gene: Minimum number of cells a gene must be expressed in to be kept. + cluster_by_groups: Whether to cluster cells by their annotation groups. + denoise: Whether to apply denoising filters. + hmm: Whether to run the Hidden Markov Model (HMM) to predict CNV states. + hmm_type: Type of HMM to use ('i6' for 6-state model, 'i3' for 3-state model). + analysis_mode: Analysis mode ('samples' or 'subclusters'). + num_threads: Number of CPU threads to use for parallel processing. + plot_steps: Whether to generate plots for every intermediate step. + no_plot: If True, skips the final heatmap generation. + window_length: Length of the moving average window for smoothing. + max_centered_threshold: Maximum value for centering the expression data. + leiden_resolution: Resolution for Leiden clustering if analysis_mode is 'subclusters'. + """ + # Input validation + raw_path = Path(raw_counts_matrix) + ann_path = Path(annotations_file) + gene_path = Path(gene_order_file) + out_path = Path(out_dir) + + if not raw_path.exists(): + return {"error": f"Raw counts matrix not found: {raw_counts_matrix}"} + if not ann_path.exists(): + return {"error": f"Annotations file not found: {annotations_file}"} + if not gene_path.exists(): + return {"error": f"Gene order file not found: {gene_order_file}"} + + if hmm_type not in ["i6", "i3"]: + return {"error": "hmm_type must be either 'i6' or 'i3'"} + + if analysis_mode not in ["samples", "subclusters"]: + return {"error": "analysis_mode must be either 'samples' or 'subclusters'"} + + os.makedirs(out_path, exist_ok=True) + + # Prepare R vector for reference groups + if ref_group_names: + ref_groups_r = "c(" + ", ".join([f"'{g}'" for g in ref_group_names]) + ")" + else: + ref_groups_r = "NULL" + + # Construct R script + r_script_content = f""" +library(infercnv) + +# Create InferCNV Object +infercnv_obj = CreateInfercnvObject( + raw_counts_matrix = "{raw_path.absolute()}", + gene_order_file = "{gene_path.absolute()}", + annotations_file = "{ann_path.absolute()}", + ref_group_names = {ref_groups_r} +) + +# Run InferCNV Pipeline +infercnv_obj = infercnv::run( + infercnv_obj, + cutoff = {cutoff}, + min_cells_per_gene = {min_cells_per_gene}, + out_dir = "{out_path.absolute()}", + cluster_by_groups = {str(cluster_by_groups).upper()}, + denoise = {str(denoise).upper()}, + HMM = {str(hmm).upper()}, + HMM_type = "{hmm_type}", + analysis_mode = "{analysis_mode}", + num_threads = {num_threads}, + plot_steps = {str(plot_steps).upper()}, + no_plot = {str(no_plot).upper()}, + window_length = {window_length}, + max_centered_threshold = {max_centered_threshold}, + leiden_resolution = {leiden_resolution} +) +""" + + try: + with tempfile.NamedTemporaryFile(suffix=".R", mode="w", delete=False) as tmp: + tmp.write(r_script_content) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + # Cleanup temp file + os.unlink(tmp_path) + + # Identify output files + output_files = [str(f) for f in out_path.glob("*") if f.is_file()] + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + "status": "success" + } + + except subprocess.CalledProcessError as e: + if os.path.exists(tmp_path): + os.unlink(tmp_path) + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "InferCNV execution failed." + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def infercnv_plot( + infercnv_obj_path: str, + out_dir: str, + output_filename: str = "infercnv_plot", + color_safe_pal: bool = False, + title: str = "InferCNV Heatmap", + cluster_by_groups: bool = True, + x_center: float = 1.0, + x_range: Optional[float] = None, + custom_color_pal: Optional[List[str]] = None, +): + """ + Generate or regenerate plots from a saved InferCNV object. + + Args: + infercnv_obj_path: Path to the saved .rds or .obj InferCNV object. + out_dir: Directory to save the plot. + output_filename: Name of the output plot file (without extension). + color_safe_pal: Use a color-blind safe palette. + title: Title of the plot. + cluster_by_groups: Whether to cluster by groups in the plot. + x_center: Value to center the color scale on (usually 1.0). + x_range: Range of values to display (e.g., 0.1 means 0.9 to 1.1). + custom_color_pal: Optional list of colors for the heatmap palette. + """ + obj_path = Path(infercnv_obj_path) + out_path = Path(out_dir) + + if not obj_path.exists(): + return {"error": f"InferCNV object not found: {infercnv_obj_path}"} + + os.makedirs(out_path, exist_ok=True) + + x_range_r = f"{x_range}" if x_range is not None else "NULL" + color_pal_r = "NULL" + if custom_color_pal: + color_pal_r = "c(" + ", ".join([f"'{c}'" for c in custom_color_pal]) + ")" + + r_script_content = f""" +library(infercnv) +infercnv_obj = readRDS("{obj_path.absolute()}") + +plot_cnv( + infercnv_obj, + out_dir = "{out_path.absolute()}", + output_filename = "{output_filename}", + color_safe_pal = {str(color_safe_pal).upper()}, + title = "{title}", + cluster_by_groups = {str(cluster_by_groups).upper()}, + x_center = {x_center}, + x_range = {x_range_r}, + custom_color_pal = {color_pal_r} +) +""" + + try: + with tempfile.NamedTemporaryFile(suffix=".R", mode="w", delete=False) as tmp: + tmp.write(r_script_content) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + os.unlink(tmp_path) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(f) for f in out_path.glob(f"{output_filename}*")], + "status": "success" + } + + except subprocess.CalledProcessError as e: + if os.path.exists(tmp_path): + os.unlink(tmp_path) + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "InferCNV plotting failed." + } + except Exception as e: + return {"error": str(e)} + +@mcp.tool() +def infercnv_filter_genes( + raw_counts_matrix: str, + gene_order_file: str, + output_matrix_path: str, + min_cells_per_gene: int = 3, +): + """ + Pre-filter a counts matrix to remove genes expressed in fewer than a threshold number of cells. + + Args: + raw_counts_matrix: Path to the input counts matrix. + gene_order_file: Path to the gene order file. + output_matrix_path: Path to save the filtered matrix. + min_cells_per_gene: Minimum number of cells a gene must be expressed in. + """ + raw_path = Path(raw_counts_matrix) + gene_path = Path(gene_order_file) + out_path = Path(output_matrix_path) + + if not raw_path.exists(): + return {"error": f"Input matrix not found: {raw_counts_matrix}"} + + r_script_content = f""" +library(infercnv) +# Load data +counts = read.table("{raw_path.absolute()}", header=TRUE, row.names=1, check.names=FALSE) +# Filter +gene_counts = rowSums(counts > 0) +filtered_counts = counts[gene_counts >= {min_cells_per_gene}, ] +# Save +write.table(filtered_counts, file="{out_path.absolute()}", quote=FALSE, sep='\\t') +""" + + try: + with tempfile.NamedTemporaryFile(suffix=".R", mode="w", delete=False) as tmp: + tmp.write(r_script_content) + tmp_path = tmp.name + + cmd = ["Rscript", tmp_path] + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + os.unlink(tmp_path) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_path)], + "status": "success" + } + except subprocess.CalledProcessError as e: + if os.path.exists(tmp_path): + os.unlink(tmp_path) + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Filtering failed." + } + except Exception as e: + return {"error": str(e)} \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-infercnv/app/bioconductor-infercnv_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-infercnv/app/bioconductor-infercnv_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4cca777fad0e4810e65f5dfbf87c581110c5192e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-infercnv/app/bioconductor-infercnv_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-infercnv/app/bioconductor-infercnv_server.py') +SERVER_NAME = 'biosci_bioconductor_infercnv' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-infercnv/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-infercnv/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f701e922db8fed281ae7e21356ec9c7d1a54f5e2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-infercnv/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-infercnv: + build: . + image: mcp-bioconductor-infercnv:latest + container_name: mcp-bioconductor-infercnv + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-infercnv + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-infercnv/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-infercnv/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3f15fb47aebdab67c6414b91b31d218a96f2e752 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-infercnv/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-infercnv + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-infercnv/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-infercnv/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-infercnv/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-iranges/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-iranges/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..78c8aad093ce7b8c16bd39ced21755f4ca8bea80 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-iranges/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-iranges via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-iranges -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-iranges_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-iranges_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-iranges_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-iranges/app/bioconductor-iranges_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-iranges/app/bioconductor-iranges_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c3338fa966c83d7a2aa4f39137514d6cdd3ec6dd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-iranges/app/bioconductor-iranges_server.py @@ -0,0 +1,284 @@ +import subprocess +import os +from pathlib import Path +from typing import Optional, List, Union + +@mcp.tool() +def iranges_transform( + input_csv: str, + output_csv: str, + operation: str = "shift", + shift_amount: int = 0, + width_amount: int = -1, + side: str = "both", + fix: str = "start" +): + """ + Perform transformations on integer ranges such as shifting, resizing, or flanking. + + Args: + input_csv: Path to input CSV file containing 'start' and 'end' (or 'width') columns. + output_csv: Path where the transformed ranges will be saved. + operation: Transformation to perform: 'shift', 'resize', 'flank', or 'narrow'. + shift_amount: Amount to shift ranges (used if operation is 'shift'). + width_amount: New width or flanking width (used if operation is 'resize' or 'flank'). + side: For 'flank', which side to generate: 'start', 'end', or 'both'. + fix: For 'resize', which part of the range to fix: 'start', 'end', or 'center'. + """ + if not Path(input_csv).exists(): + return {"error": f"Input file {input_csv} not found."} + + valid_ops = ["shift", "resize", "flank", "narrow"] + if operation not in valid_ops: + return {"error": f"Invalid operation. Must be one of {valid_ops}"} + + # Construct R script + r_cmd = f""" + library(IRanges) + df <- read.csv('{input_csv}') + ir <- IRanges(start=df$start, end=df$end) + + if ('{operation}' == 'shift') {{ + res <- shift(ir, shift={shift_amount}) + }} else if ('{operation}' == 'resize') {{ + res <- resize(ir, width={width_amount}, fix='{fix}') + }} else if ('{operation}' == 'flank') {{ + is_both <- if('{side}' == 'both') TRUE else FALSE + res <- flank(ir, width={width_amount}, start=('{side}' == 'start'), both=is_both) + }} else if ('{operation}' == 'narrow') {{ + res <- narrow(ir, start=NA, end=NA, width={width_amount}) + }} + + write.csv(as.data.frame(res), '{output_csv}', row.names=FALSE) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_cmd], + check=True, + capture_output=True, + text=True + ) + return { + "command_executed": f"Rscript -e \"{operation} on {input_csv}\"", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_csv] + } + except subprocess.CalledProcessError as e: + return { + "error": "R execution failed", + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def iranges_set_operations( + input_csv: str, + output_csv: str, + operation: str = "reduce", + min_gapwidth: int = 1 +): + """ + Perform set-like operations on ranges such as merging overlapping intervals or finding gaps. + + Args: + input_csv: Path to input CSV file containing 'start' and 'end' columns. + output_csv: Path where the resulting ranges will be saved. + operation: Operation to perform: 'reduce' (merge overlapping), 'disjoin' (find elementary ranges), or 'gaps'. + min_gapwidth: Minimum gap width for the 'reduce' operation. + """ + if not Path(input_csv).exists(): + return {"error": f"Input file {input_csv} not found."} + + r_cmd = f""" + library(IRanges) + df <- read.csv('{input_csv}') + ir <- IRanges(start=df$start, end=df$end) + + if ('{operation}' == 'reduce') {{ + res <- reduce(ir, min.gapwidth={min_gapwidth}) + }} else if ('{operation}' == 'disjoin') {{ + res <- disjoin(ir) + }} else if ('{operation}' == 'gaps') {{ + res <- gaps(ir) + }} + + write.csv(as.data.frame(res), '{output_csv}', row.names=FALSE) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_cmd], + check=True, + capture_output=True, + text=True + ) + return { + "command_executed": f"Rscript -e \"{operation} on {input_csv}\"", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_csv] + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} + +@mcp.tool() +def iranges_overlap_analysis( + query_csv: str, + subject_csv: str, + output_csv: str, + find_overlaps: bool = True, + maxgap: int = -1, + minoverlap: int = 0, + overlap_type: str = "any" +): + """ + Find overlaps or count overlaps between two sets of ranges (Query and Subject). + + Args: + query_csv: CSV file for query ranges. + subject_csv: CSV file for subject ranges. + output_csv: Path to save the overlap mapping (query hits and subject hits). + find_overlaps: If True, returns mapping of hits. If False, returns counts per query. + maxgap: Maximum gap allowed between ranges to be considered overlapping. + minoverlap: Minimum number of overlapping positions. + overlap_type: Type of overlap: 'any', 'start', 'end', 'within', or 'equal'. + """ + if not Path(query_csv).exists() or not Path(subject_csv).exists(): + return {"error": "One or both input files not found."} + + r_cmd = f""" + library(IRanges) + q_df <- read.csv('{query_csv}') + s_df <- read.csv('{subject_csv}') + query <- IRanges(start=q_df$start, end=q_df$end) + subject <- IRanges(start=s_df$start, end=s_df$end) + + if ({str(find_overlaps).upper()}) {{ + hits <- findOverlaps(query, subject, maxgap={maxgap}, minoverlap={minoverlap}, type='{overlap_type}') + res <- as.data.frame(hits) + }} else {{ + counts <- countOverlaps(query, subject, maxgap={maxgap}, minoverlap={minoverlap}, type='{overlap_type}') + res <- data.frame(query_index=1:length(query), overlap_count=counts) + }} + + write.csv(res, '{output_csv}', row.names=FALSE) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_cmd], + check=True, + capture_output=True, + text=True + ) + return { + "command_executed": "IRanges::findOverlaps/countOverlaps", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_csv] + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} + +@mcp.tool() +def iranges_nearest_methods( + query_csv: str, + subject_csv: str, + output_csv: str, + method: str = "nearest" +): + """ + Find nearest, preceding, or following ranges between query and subject. + + Args: + query_csv: CSV file for query ranges. + subject_csv: CSV file for subject ranges. + output_csv: Path to save the results (mapping of query index to subject index). + method: Method to use: 'nearest', 'precede', or 'follow'. + """ + if not Path(query_csv).exists() or not Path(subject_csv).exists(): + return {"error": "Input files not found."} + + r_cmd = f""" + library(IRanges) + q_df <- read.csv('{query_csv}') + s_df <- read.csv('{subject_csv}') + query <- IRanges(start=q_df$start, end=q_df$end) + subject <- IRanges(start=s_df$start, end=s_df$end) + + if ('{method}' == 'nearest') {{ + idx <- nearest(query, subject) + }} else if ('{method}' == 'precede') {{ + idx <- precede(query, subject) + }} else if ('{method}' == 'follow') {{ + idx <- follow(query, subject) + }} + + res <- data.frame(query_index=1:length(query), subject_index=idx) + write.csv(res, '{output_csv}', row.names=FALSE) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_cmd], + check=True, + capture_output=True, + text=True + ) + return { + "command_executed": f"IRanges::{method}", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_csv] + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} + +@mcp.tool() +def iranges_coverage( + input_csv: str, + output_csv: str +): + """ + Calculate the coverage (number of ranges covering each integer position). + + Args: + input_csv: Path to input CSV file containing 'start' and 'end' columns. + output_csv: Path to save the coverage data (position and value). + """ + if not Path(input_csv).exists(): + return {"error": f"Input file {input_csv} not found."} + + r_cmd = f""" + library(IRanges) + df <- read.csv('{input_csv}') + ir <- IRanges(start=df$start, end=df$end) + cov <- coverage(ir) + + # Convert Rle to data frame for export + res <- data.frame( + value = as.vector(cov), + width = runLength(cov) + ) + # Expand or keep as run-length encoded? Let's provide a summary-like table + # To keep it simple and usable, we export the Rle components + write.csv(res, '{output_csv}', row.names=FALSE) + """ + + try: + result = subprocess.run( + ["Rscript", "-e", r_cmd], + check=True, + capture_output=True, + text=True + ) + return { + "command_executed": "IRanges::coverage", + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_csv] + } + except subprocess.CalledProcessError as e: + return {"error": "R execution failed", "stderr": e.stderr} \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-iranges/app/bioconductor-iranges_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-iranges/app/bioconductor-iranges_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..75e878ed77b94194fd9f3598675b098ec3f24eec --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-iranges/app/bioconductor-iranges_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-iranges/app/bioconductor-iranges_server.py') +SERVER_NAME = 'biosci_bioconductor_iranges' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-iranges/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-iranges/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-iranges/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-iranges/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-iranges/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7a44a8a7f67111158d1ce5c6143cbe40c2b20625 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-iranges/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-iranges: + build: . + image: mcp-bioconductor-iranges:latest + container_name: mcp-bioconductor-iranges + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-iranges + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-iranges/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-iranges/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e7776983b41417b9ccff7c889b7607cae4724926 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-iranges/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-iranges + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-iranges/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-iranges/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-iranges/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-keggrest/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-keggrest/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..61124c030833e7bfe2a16651cd9cf937150cfeb6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-keggrest/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-keggrest via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-keggrest -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-keggrest_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-keggrest_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-keggrest_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-keggrest/app/bioconductor-keggrest_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-keggrest/app/bioconductor-keggrest_server.py new file mode 100644 index 0000000000000000000000000000000000000000..933724b47d84cd424c63d76e5742b16ebb929caa --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-keggrest/app/bioconductor-keggrest_server.py @@ -0,0 +1,446 @@ +import subprocess +import tempfile +import logging +from pathlib import Path +from typing import List, Optional, Dict, Union + +# Mock decorator for standalone validation. In a real MCP environment, this would be `from mcp import mcp`. +class mcp: + @staticmethod + def tool(func): + # This decorator is a placeholder and doesn't modify the function. + return func + +# Configure logging +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) + +def _run_r_script(r_script_content: str, command_name: str) -> Dict[str, Union[str, List[str]]]: + """ + Executes an R script using Rscript and captures its output. + + Args: + r_script_content: A string containing the R code to execute. + command_name: The name of the calling function for logging purposes. + + Returns: + A dictionary containing the executed command, stdout, and stderr. + + Raises: + subprocess.CalledProcessError: If the Rscript command returns a non-zero exit code. + """ + command_str = "" + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, encoding='utf-8') as tmp_script: + script_path = Path(tmp_script.name) + tmp_script.write(r_script_content) + + command = ["Rscript", str(script_path)] + command_str = " ".join(command) + logger.info(f"Executing command for {command_name}: {command_str}") + + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + return { + "command_executed": command_str, + "stdout": process.stdout, + "stderr": process.stderr, + } + except FileNotFoundError: + logger.error("Rscript not found. Please ensure R is installed and in the system's PATH.") + raise + finally: + if 'script_path' in locals() and script_path.exists(): + script_path.unlink() + +@mcp.tool +def kegg_info(database: str) -> Dict[str, Union[str, List]]: + """ + Retrieves information about a KEGG database. + + This tool corresponds to the KEGGREST::keggInfo function. It requires an + environment with R and the bioconductor-keggrest package installed. + + Args: + database: The name of the KEGG database (e.g., 'pathway', 'genes', 'compound'). + + Returns: + A dictionary containing the command executed, stdout (database info), and stderr. + """ + if not database: + raise ValueError("The 'database' parameter cannot be empty.") + + r_script = f""" + library(KEGGREST) + tryCatch({{ + info <- keggInfo("{database}") + cat(info) + }}, error = function(e) {{ + stop(e) + }}) + """ + + try: + result = _run_r_script(r_script, "kegg_info") + return { + "command_executed": result["command_executed"], + "stdout": result["stdout"], + "stderr": result["stderr"], + "output_files": [] + } + except subprocess.CalledProcessError as e: + logger.error(f"R script execution failed for kegg_info: {e.stderr}") + return { + "command_executed": e.cmd, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed. Check if the database name is correct and KEGGREST is installed." + } + +@mcp.tool +def kegg_list(database: str, organism: Optional[str] = None) -> Dict[str, Union[str, List]]: + """ + Lists all entries in a KEGG database, optionally for a specific organism. + + This tool corresponds to the KEGGREST::keggList function. It outputs a + two-column TSV (id, description) to stdout. It requires an environment + with R and the bioconductor-keggrest package installed. + + Args: + database: The name of the KEGG database (e.g., 'pathway', 'organism'). + organism: Optional KEGG organism code (e.g., 'hsa' for Homo sapiens). + + Returns: + A dictionary containing the command executed, stdout (TSV list), and stderr. + """ + if not database: + raise ValueError("The 'database' parameter cannot be empty.") + + if organism: + kegg_call = f'keggList("{database}", "{organism}")' + else: + kegg_call = f'keggList("{database}")' + + r_script = f""" + library(KEGGREST) + tryCatch({{ + result_list <- {kegg_call} + if (length(result_list) > 0) {{ + df <- data.frame(id=names(result_list), description=result_list, stringsAsFactors=FALSE) + write.table(df, file=stdout(), sep="\\t", row.names=FALSE, col.names=TRUE, quote=FALSE) + }} else {{ + cat("No entries found.\\n") + }} + }}, error = function(e) {{ + stop(e) + }}) + """ + + try: + result = _run_r_script(r_script, "kegg_list") + return { + "command_executed": result["command_executed"], + "stdout": result["stdout"], + "stderr": result["stderr"], + "output_files": [] + } + except subprocess.CalledProcessError as e: + logger.error(f"R script execution failed for kegg_list: {e.stderr}") + return { + "command_executed": e.cmd, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed. Check parameters and KEGGREST installation." + } + +@mcp.tool +def kegg_find( + database: str, + query: List[str], + option: str = "all" +) -> Dict[str, Union[str, List]]: + """ + Finds entries in a KEGG database by keyword, formula, etc. + + This tool corresponds to the KEGGREST::keggFind function. It outputs a + two-column TSV (id, description) to stdout. It requires an environment + with R and the bioconductor-keggrest package installed. + + Args: + database: The name of the KEGG database to search. + query: A list of keywords to search for. + option: The search option. Must be one of 'all', 'mol_weight', + 'exact_mass', or 'formula'. Defaults to 'all'. + + Returns: + A dictionary containing the command executed, stdout (TSV results), and stderr. + """ + if not database: + raise ValueError("The 'database' parameter cannot be empty.") + if not query: + raise ValueError("The 'query' list cannot be empty.") + + valid_options = {"all", "mol_weight", "exact_mass", "formula"} + if option not in valid_options: + raise ValueError(f"Invalid 'option'. Must be one of {valid_options}.") + + r_query_vector = "c(" + ", ".join(f'"{q}"' for q in query) + ")" + + r_script = f""" + library(KEGGREST) + tryCatch({{ + query_vec <- {r_query_vector} + result_list <- keggFind("{database}", query_vec, option="{option}") + if (length(result_list) > 0) {{ + df <- data.frame(id=names(result_list), description=result_list, stringsAsFactors=FALSE) + write.table(df, file=stdout(), sep="\\t", row.names=FALSE, col.names=TRUE, quote=FALSE) + }} else {{ + cat("No entries found for the given query.\\n") + }} + }}, error = function(e) {{ + stop(e) + }}) + """ + + try: + result = _run_r_script(r_script, "kegg_find") + return { + "command_executed": result["command_executed"], + "stdout": result["stdout"], + "stderr": result["stderr"], + "output_files": [] + } + except subprocess.CalledProcessError as e: + logger.error(f"R script execution failed for kegg_find: {e.stderr}") + return { + "command_executed": e.cmd, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed. Check parameters and KEGGREST installation." + } + +@mcp.tool +def kegg_get( + dbentries: List[str], + option: str = "aaseq", + output_file: Optional[Path] = None +) -> Dict[str, Union[str, List]]: + """ + Retrieves KEGG database entries for a given set of KEGG identifiers. + + This tool corresponds to the KEGGREST::keggGet function. It requires an + environment with R and bioconductor-keggrest. For the 'image' option, + the 'png' R package is also required. + + Args: + dbentries: A list of KEGG identifiers to retrieve. + option: The type of data to retrieve. Must be one of 'aaseq', 'ntseq', + 'mol', 'kcf', 'image', 'kgml'. Defaults to 'aaseq'. + output_file: Optional path to save the output. Required for 'image' option. + If not provided for text options, output is returned in stdout. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output_files. + """ + if not dbentries: + raise ValueError("The 'dbentries' list cannot be empty.") + + valid_options = {"aaseq", "ntseq", "mol", "kcf", "image", "kgml"} + if option not in valid_options: + raise ValueError(f"Invalid 'option'. Must be one of {valid_options}.") + + r_dbentries_vector = "c(" + ", ".join(f'"{d}"' for d in dbentries) + ")" + output_files = [] + + if option == "image": + if len(dbentries) > 1: + raise ValueError("Only one entry can be retrieved at a time for the 'image' option.") + if not output_file: + raise ValueError("The 'output_file' parameter is required for the 'image' option.") + + output_file.parent.mkdir(parents=True, exist_ok=True) + output_files.append(str(output_file)) + + r_script = f""" + if (!requireNamespace("png", quietly = TRUE)) {{ + stop("The 'png' R package is required for the 'image' option. Please install it.") + }} + library(KEGGREST) + library(png) + tryCatch({{ + png_data <- keggGet("{dbentries[0]}", "image") + writePNG(png_data, target="{str(output_file)}") + cat("Image successfully saved to {str(output_file)}\\n") + }}, error = function(e) {{ + stop(e) + }}) + """ + else: + r_script = f""" + library(KEGGREST) + tryCatch({{ + dbentries_vec <- {r_dbentries_vector} + results_list <- keggGet(dbentries_vec, option="{option}") + + if (is.list(results_list)) {{ + for (entry_name in names(results_list)) {{ + cat(paste0(">", entry_name, "\\n")) + content <- paste(results_list[[entry_name]], collapse="\\n") + cat(content) + cat("\\n") + }} + }} else {{ + cat(paste0(">", dbentries_vec[1], "\\n")) + content <- paste(results_list, collapse="\\n") + cat(content) + cat("\\n") + }} + }}, error = function(e) {{ + stop(e) + }}) + """ + + try: + result = _run_r_script(r_script, "kegg_get") + stdout_content = result["stdout"] + + if output_file and option != "image": + output_file.parent.mkdir(parents=True, exist_ok=True) + with open(output_file, "w", encoding='utf-8') as f: + f.write(stdout_content) + output_files.append(str(output_file)) + stdout_content = f"Output successfully saved to {str(output_file)}" + + return { + "command_executed": result["command_executed"], + "stdout": stdout_content, + "stderr": result["stderr"], + "output_files": output_files + } + except subprocess.CalledProcessError as e: + logger.error(f"R script execution failed for kegg_get: {e.stderr}") + return { + "command_executed": e.cmd, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed. Check parameters and KEGGREST installation." + } + +@mcp.tool +def kegg_conv(target_db: str, source_ids: List[str]) -> Dict[str, Union[str, List]]: + """ + Converts KEGG identifiers to/from outside database identifiers. + + This tool corresponds to the KEGGREST::keggConv function. It outputs a + two-column TSV (source_id, target_id) to stdout. It requires an environment + with R and the bioconductor-keggrest package installed. + + Args: + target_db: The target database or organism code (e.g., 'eco', 'ncbi-geneid'). + source_ids: A list of source database identifiers (e.g., ['hsa:10458', 'ece:Z5100']). + + Returns: + A dictionary containing the command executed, stdout (TSV results), and stderr. + """ + if not target_db: + raise ValueError("The 'target_db' parameter cannot be empty.") + if not source_ids: + raise ValueError("The 'source_ids' list cannot be empty.") + + r_source_vector = "c(" + ", ".join(f'"{s}"' for s in source_ids) + ")" + + r_script = f""" + library(KEGGREST) + tryCatch({{ + source_vec <- {r_source_vector} + result_list <- keggConv("{target_db}", source_vec) + if (length(result_list) > 0) {{ + df <- data.frame(source_id=names(result_list), target_id=result_list, stringsAsFactors=FALSE) + write.table(df, file=stdout(), sep="\\t", row.names=FALSE, col.names=TRUE, quote=FALSE) + }} else {{ + cat("No conversion results found.\\n") + }} + }}, error = function(e) {{ + stop(e) + }}) + """ + + try: + result = _run_r_script(r_script, "kegg_conv") + return { + "command_executed": result["command_executed"], + "stdout": result["stdout"], + "stderr": result["stderr"], + "output_files": [] + } + except subprocess.CalledProcessError as e: + logger.error(f"R script execution failed for kegg_conv: {e.stderr}") + return { + "command_executed": e.cmd, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed. Check parameters and KEGGREST installation." + } + +@mcp.tool +def kegg_link(target_db: str, source_db_or_ids: List[str]) -> Dict[str, Union[str, List]]: + """ + Finds related entries by linking two KEGG databases or a set of entries to a database. + + This tool corresponds to the KEGGREST::keggLink function. It outputs a + two-column TSV (source_id, target_id) to stdout. It requires an environment + with R and the bioconductor-keggrest package installed. + + Args: + target_db: The target database (e.g., 'pathway'). + source_db_or_ids: A list containing either a single source database name + (e.g., ['hsa']) or multiple source entry IDs + (e.g., ['hsa:1234', 'hsa:5678']). + + Returns: + A dictionary containing the command executed, stdout (TSV results), and stderr. + """ + if not target_db: + raise ValueError("The 'target_db' parameter cannot be empty.") + if not source_db_or_ids: + raise ValueError("The 'source_db_or_ids' list cannot be empty.") + + r_source_vector = "c(" + ", ".join(f'"{s}"' for s in source_db_or_ids) + ")" + + r_script = f""" + library(KEGGREST) + tryCatch({{ + source_vec <- {r_source_vector} + result_list <- keggLink("{target_db}", source_vec) + if (length(result_list) > 0) {{ + df <- data.frame(source_id=names(result_list), target_id=result_list, stringsAsFactors=FALSE) + write.table(df, file=stdout(), sep="\\t", row.names=FALSE, col.names=TRUE, quote=FALSE) + }} else {{ + cat("No linked entries found.\\n") + }} + }}, error = function(e) {{ + stop(e) + }}) + """ + + try: + result = _run_r_script(r_script, "kegg_link") + return { + "command_executed": result["command_executed"], + "stdout": result["stdout"], + "stderr": result["stderr"], + "output_files": [] + } + except subprocess.CalledProcessError as e: + logger.error(f"R script execution failed for kegg_link: {e.stderr}") + return { + "command_executed": e.cmd, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "R script execution failed. Check parameters and KEGGREST installation." + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-keggrest/app/bioconductor-keggrest_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-keggrest/app/bioconductor-keggrest_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9cbd8c890161c5a58c7c0bb6ab3daac4d9e229b1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-keggrest/app/bioconductor-keggrest_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-keggrest/app/bioconductor-keggrest_server.py') +SERVER_NAME = 'biosci_bioconductor_keggrest' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-keggrest/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-keggrest/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-keggrest/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-keggrest/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-keggrest/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b59215b718958fa8391ccf923a5c42292d83fc55 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-keggrest/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-keggrest: + build: . + image: mcp-bioconductor-keggrest:latest + container_name: mcp-bioconductor-keggrest + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-keggrest + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-keggrest/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-keggrest/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..463bf05c34256a44f7cfa3a9b883412278c134bc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-keggrest/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-keggrest + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-keggrest/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-keggrest/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-keggrest/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-limma/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-limma/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..525795313103fb6713b9d1f764668bfc4b01ffd9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-limma/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install bioconductor-limma via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-limma -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/bioconductor-limma_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/bioconductor-limma_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/bioconductor-limma_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-limma/app/bioconductor-limma_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-limma/app/bioconductor-limma_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2931e806194ac1e4e7a96f0cbec34f87131c77bb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-limma/app/bioconductor-limma_server.py @@ -0,0 +1,172 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Dict + +# The mcp.tool decorator is supplied by the MCP framework. +# It is commented out here to allow for standalone code analysis. +# @mcp.tool() + +def limma_voom_differential_expression( + expression_matrix: Path, + design_matrix: Path, + contrast_matrix: Path, + output_prefix: str = "limma_results", + gene_id_column: str = "GeneID", + normalize_method: str = "quantile", + p_adjust_method: str = "BH", + lfc_threshold: float = 0.0, +) -> Dict: + """ + Performs differential expression analysis using the limma-voom pipeline. + + This tool wraps the common limma workflow for RNA-Seq data. It takes a raw count + matrix, a design matrix specifying the experimental groups, and a contrast + matrix defining the comparisons of interest. It uses voom for mean-variance + modeling, fits linear models, and uses empirical Bayes moderation to find + differentially expressed genes. + + Args: + expression_matrix: Path to the input file with gene expression counts. + Rows should be genes and columns should be samples. + design_matrix: Path to the design matrix file, describing the experimental + design. Rows correspond to samples and columns to coefficients. + contrast_matrix: Path to the contrast matrix file, specifying the comparisons + to be made between the coefficients of the linear model. + output_prefix: Prefix for the output file(s). + gene_id_column: Name of the column in the expression matrix that contains + gene identifiers. + normalize_method: Normalization method to be applied by voom. + Options: "none", "scale", "quantile", "cyclicloess". + p_adjust_method: Method for multiple testing correction. + Options: "holm", "hochberg", "hommel", "bonferroni", + "BH", "BY", "fdr", "none". + lfc_threshold: Log-fold change threshold to test against. A value of 0 tests + for any change. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a + dictionary of output files. + """ + # 1. Input Validation + if not expression_matrix.exists(): + raise FileNotFoundError(f"Expression matrix not found: {expression_matrix}") + if not design_matrix.exists(): + raise FileNotFoundError(f"Design matrix not found: {design_matrix}") + if not contrast_matrix.exists(): + raise FileNotFoundError(f"Contrast matrix not found: {contrast_matrix}") + + allowed_norm_methods = ["none", "scale", "quantile", "cyclicloess"] + if normalize_method not in allowed_norm_methods: + raise ValueError( + f"Invalid normalize_method '{normalize_method}'. " + f"Must be one of {allowed_norm_methods}" + ) + + allowed_padjust_methods = [ + "holm", "hochberg", "hommel", "bonferroni", "BH", "BY", "fdr", "none" + ] + if p_adjust_method not in allowed_padjust_methods: + raise ValueError( + f"Invalid p_adjust_method '{p_adjust_method}'. " + f"Must be one of {allowed_padjust_methods}" + ) + + # 2. Define output file path + output_file = Path(f"{output_prefix}_differential_expression.tsv") + + # 3. Generate R script content + # This script loads data, runs the voom-limma pipeline, and writes results. + r_script_content = f""" + # Ensure limma is installed and loaded + if (!requireNamespace("limma", quietly = TRUE)) {{ + if (!requireNamespace("BiocManager", quietly = TRUE)) + install.packages("BiocManager") + BiocManager::install("limma", update=FALSE, ask=FALSE) + }} + library(limma) + + # --- 1. Load Data --- + # Expression data (counts) + counts <- read.csv("{expression_matrix.resolve()}", row.names="{gene_id_column}", check.names=FALSE) + # Design matrix + design <- as.matrix(read.csv("{design_matrix.resolve()}", row.names=1, check.names=FALSE)) + # Contrast matrix + contrast.matrix <- as.matrix(read.csv("{contrast_matrix.resolve()}", row.names=1, check.names=FALSE)) + + # --- 2. Pre-processing and Voom Transformation --- + # Create DGEList object + dge <- DGEList(counts=counts) + # Filter out lowly expressed genes + keep <- filterByExpr(dge, design) + dge <- dge[keep,,keep.lib.sizes=FALSE] + # Calculate normalization factors + dge <- calcNormFactors(dge) + # Apply voom transformation + v <- voom(dge, design, plot=FALSE, normalize.method="{normalize_method}") + + # --- 3. Linear Model Fitting --- + # Fit the linear model for each gene + fit <- lmFit(v, design) + # Apply the contrast matrix to get the desired comparisons + fit2 <- contrasts.fit(fit, contrast.matrix) + # Apply empirical Bayes moderation + fit2 <- eBayes(fit2) + + # --- 4. Extract and Save Results --- + # Get the top differentially expressed genes for all contrasts + results <- topTable(fit2, adjust.method="{p_adjust_method}", number=Inf, lfc={lfc_threshold}, sort.by="P") + + # Write the results to a file + write.table(results, file="{output_file.resolve()}", sep="\\t", quote=FALSE, row.names=TRUE, col.names=NA) + + cat("Limma-voom analysis complete. Results saved to {output_file.resolve()}\\n") + """ + + # 4. Execute the R script using a temporary file + script_path = None + try: + with tempfile.NamedTemporaryFile( + mode='w', suffix=".R", delete=False + ) as tmp_script: + tmp_script.write(r_script_content) + script_path = tmp_script.name + + cmd = ["Rscript", script_path] + command_executed = " ".join(cmd) + + process = subprocess.run( + cmd, + text=True, + capture_output=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + + except FileNotFoundError: + raise RuntimeError( + "Rscript not found. Please ensure R is installed and in your system's PATH." + ) + except subprocess.CalledProcessError as e: + error_message = ( + f"R script execution failed with return code {e.returncode}.\n" + f"Command: {e.cmd}\n" + f"Stdout:\n{e.stdout}\n" + f"Stderr:\n{e.stderr}" + ) + raise RuntimeError(error_message) from e + finally: + # Clean up the temporary script file + if script_path and Path(script_path).exists(): + Path(script_path).unlink() + + # 5. Return structured output + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": { + "differential_expression_results": str(output_file) + } + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-limma/app/bioconductor-limma_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-limma/app/bioconductor-limma_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f5fc76757aafa6e203112ee4c60fe34fc92c8452 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-limma/app/bioconductor-limma_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-limma/app/bioconductor-limma_server.py') +SERVER_NAME = 'biosci_bioconductor_limma' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-limma/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-limma/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-limma/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-limma/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-limma/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..29e9a31d1a7db8397f8930371cdcc4af13dd8878 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-limma/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-limma: + build: . + image: mcp-bioconductor-limma:latest + container_name: mcp-bioconductor-limma + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-limma + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-limma/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-limma/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4dc498b72bbe5cd0bbee0f558f371c3866f3c61d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-limma/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-limma + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-limma/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-limma/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-limma/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-metabolomicsworkbenchr/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-metabolomicsworkbenchr/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3610c0c4ce00dcc7bd542c046f85f7b176810e64 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-metabolomicsworkbenchr/app/bioconductor-metabolomicsworkbenchr_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-metabolomicsworkbenchr/app/bioconductor-metabolomicsworkbenchr_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d021107adef815a0455074c82ed24143c01f7fb1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-metabolomicsworkbenchr/app/bioconductor-metabolomicsworkbenchr_server.py @@ -0,0 +1,117 @@ +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`. + +@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}" + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-metabolomicsworkbenchr/app/bioconductor-metabolomicsworkbenchr_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-metabolomicsworkbenchr/app/bioconductor-metabolomicsworkbenchr_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2f2f308f9d4eb835982a7da5d11e998465f01793 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-metabolomicsworkbenchr/app/bioconductor-metabolomicsworkbenchr_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-metabolomicsworkbenchr/app/bioconductor-metabolomicsworkbenchr_server.py') +SERVER_NAME = 'biosci_bioconductor_metabolomicsworkbenchr' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-metabolomicsworkbenchr/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-metabolomicsworkbenchr/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c2a2cdedf09310946c0907818a3eeadb20437bc4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-metabolomicsworkbenchr/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-metabolomicsworkbenchr/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9bde03c685868257823a92c9790c2ff89f26edee --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/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/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-metabolomicsworkbenchr/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-metabolomicsworkbenchr/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-metabolomicsworkbenchr/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-mosim/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-mosim/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4e5ae9b6e22413ed1bf33d860c1e348d015a1f58 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-mosim/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.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-mosim via conda (e.g., from bioconda) +RUN conda install -c bioconda bioconductor-mosim -y && conda clean -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-mosim_server.py /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-mosim_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --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-mosim_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-mosim/app/bioconductor-mosim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-mosim/app/bioconductor-mosim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..178f761efc45e22f5d69b71caaef2bd532e7a98f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-mosim/app/bioconductor-mosim_server.py @@ -0,0 +1,207 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Dict, Any +import logging + +# Set up logging +logging.basicConfig(level=logging.INFO) +log = logging.getLogger(__name__) + +# Per the instructions, the mcp decorator is assumed to be available in the execution environment. +# We define a placeholder here for standalone validation. +class mcp: + @staticmethod + def tool(): + def decorator(f): + return f + return decorator + +@mcp.tool() +def start_simulation( + sim_name: str, + omics_list: List[str], + omics_distributions: List[str], + n_samples: int, + n_features: List[int], + omics_network_file: Path, + prop_causal: float, + prop_shared_causal: float, + output_path: Path, + seed: int = 123, + save_results: bool = True, + verbose: bool = True, +) -> Dict[str, Any]: + """ + Runs a multi-omics simulation using the bioconductor-mosim R package. + + This tool acts as a wrapper around the `mosim::startSimulation` R function. + It requires R, the Rscript executable in the system's PATH, and the + Bioconductor 'mosim' package to be installed in the R environment. + + Args: + sim_name: Name for the simulation. A directory with this name will be created in the output_path. + omics_list: A list of omics types to be simulated (e.g., ["RNA", "protein"]). + omics_distributions: A list of distributions for each omic (e.g., ["NB", "normal"]). Must be the same length as omics_list. + n_samples: The number of samples to simulate. Must be a positive integer. + n_features: A list of the number of features for each omic. Must be the same length as omics_list. + omics_network_file: Path to a CSV file representing the adjacency matrix of the omics network. The first column should contain feature names (row names). + prop_causal: The proportion of causal features. Must be between 0.0 and 1.0. + prop_shared_causal: The proportion of causal features that are shared among omics. Must be between 0.0 and 1.0. + output_path: The directory where the simulation results will be saved. + seed: An integer to be used as the random seed. + save_results: If True, the simulation results will be saved to files. + verbose: If True, the simulation progress will be printed to standard output. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not sim_name: + raise ValueError("sim_name cannot be empty.") + if not omics_list: + raise ValueError("omics_list cannot be empty.") + if len(omics_list) != len(omics_distributions): + raise ValueError("omics_list and omics_distributions must have the same length.") + if len(omics_list) != len(n_features): + raise ValueError("omics_list and n_features must have the same length.") + if n_samples <= 0: + raise ValueError("n_samples must be a positive integer.") + for n in n_features: + if n <= 0: + raise ValueError("All values in n_features must be positive integers.") + if not (0.0 <= prop_causal <= 1.0): + raise ValueError("prop_causal must be between 0.0 and 1.0.") + if not (0.0 <= prop_shared_causal <= 1.0): + raise ValueError("prop_shared_causal must be between 0.0 and 1.0.") + + if not omics_network_file.is_file(): + raise FileNotFoundError(f"Omics network file not found at: {omics_network_file}") + + # --- File Path Handling --- + try: + output_path.mkdir(parents=True, exist_ok=True) + except OSError as e: + raise OSError(f"Could not create output directory {output_path}: {e}") + + # --- R Script Generation --- + # Convert Python lists to R vector strings, e.g., ["a", "b"] -> 'c("a", "b")' + r_omics_list = 'c(' + ', '.join(f'"{o}"' for o in omics_list) + ')' + r_omics_distributions = 'c(' + ', '.join(f'"{d}"' for d in omics_distributions) + ')' + r_n_features = 'c(' + ', '.join(map(str, n_features)) + ')' + + # Convert Python bool to R TRUE/FALSE + r_save_results = "TRUE" if save_results else "FALSE" + r_verbose = "TRUE" if verbose else "FALSE" + + r_script_content = f""" + # Check if mosim is installed, if not, stop with an error + if (!requireNamespace("mosim", quietly = TRUE)) {{ + stop("The 'mosim' package is not installed. Please install it from Bioconductor.", call. = FALSE) + }} + library(mosim) + + # --- Parameters --- + sim_name_val <- "{sim_name}" + omics_list_val <- {r_omics_list} + omics_distributions_val <- {r_omics_distributions} + n_samples_val <- {n_samples} + n_features_val <- {r_n_features} + omics_network_path <- "{omics_network_file.resolve()}" + prop_causal_val <- {prop_causal} + prop_shared_causal_val <- {prop_shared_causal} + output_path_val <- "{output_path.resolve()}" + seed_val <- {seed} + save_results_val <- {r_save_results} + verbose_val <- {r_verbose} + + # --- Data Loading --- + # Assuming the network file is a CSV with a header and row names in the first column + tryCatch({{ + omics_network_df <- read.csv(omics_network_path, header=TRUE, row.names=1, check.names=FALSE) + }}, error = function(e) {{ + stop(paste("Failed to read omics network file:", e$message), call. = FALSE) + }}) + + # --- Simulation --- + set.seed(seed_val) + + cat("Starting mosim simulation...\\n") + + tryCatch({{ + simulation_results <- mosim::startSimulation( + sim_name = sim_name_val, + omics_list = omics_list_val, + omics_distributions = omics_distributions_val, + n_samples = n_samples_val, + n_features = n_features_val, + omics_network = omics_network_df, + prop_causal = prop_causal_val, + prop_shared_causal = prop_shared_causal_val, + output_path = output_path_val, + seed = seed_val, + save_results = save_results_val, + verbose = verbose_val + ) + }}, error = function(e) {{ + stop(paste("Error during mosim::startSimulation:", e$message), call. = FALSE) + }}) + + cat("Simulation completed successfully.\\n") + """ + + # --- Subprocess Execution --- + command = [] + r_script_path = None + try: + with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, dir=".") 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)] + log.info(f"Executing command: {' '.join(command)}") + + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + stdout_str = process.stdout + stderr_str = process.stderr + + # --- Collect Output Files --- + output_files = [] + if save_results: + simulation_output_dir = output_path / sim_name + if simulation_output_dir.is_dir(): + output_files = [str(f.resolve()) for f in simulation_output_dir.glob('**/*') if f.is_file()] + else: + log.warning(f"Expected output directory '{simulation_output_dir}' was not created by mosim.") + stderr_str += f"\n[MCP WARNING] Expected output directory '{simulation_output_dir}' was not created by mosim." + + return { + "command_executed": " ".join(command), + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": output_files + } + + except FileNotFoundError: + raise RuntimeError("Rscript not found. Please ensure R is installed and 'Rscript' is in your system's PATH.") + except subprocess.CalledProcessError as e: + log.error(f"R script execution failed with return code {e.returncode}") + log.error(f"STDOUT: {e.stdout}") + log.error(f"STDERR: {e.stderr}") + # Return a structured error response + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": f"R script execution failed with return code {e.returncode}. Check stderr for details from R." + } + finally: + # Clean up the temporary R script + if r_script_path and r_script_path.exists(): + r_script_path.unlink() diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-mosim/app/bioconductor-mosim_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-mosim/app/bioconductor-mosim_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..33bbe92d4808d58b90f4d410adaf04b0f73ca958 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-mosim/app/bioconductor-mosim_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-mosim/app/bioconductor-mosim_server.py') +SERVER_NAME = 'biosci_bioconductor_mosim' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-mosim/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-mosim/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..a63563333da7f44cdd4997ed3050fff8fb05f7a7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-mosim/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-bioconductor-mosim: + build: . + image: mcp-bioconductor-mosim:latest + container_name: mcp-bioconductor-mosim + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=bioconductor-mosim + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-mosim/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-mosim/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1d19ee09029b7f73facf98be195e04fba8c25a83 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-mosim/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - bioconductor-mosim + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-mosim/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-mosim/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-mosim/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp