diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gdk-pixbuf/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gdk-pixbuf/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..4e11ed308814069ff4043570f1a8226e507fa4e3 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gdk-pixbuf/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-gdk-pixbuf: + build: . + image: mcp-gdk-pixbuf:latest + container_name: mcp-gdk-pixbuf + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=gdk-pixbuf + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gdk-pixbuf/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gdk-pixbuf/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1e46bc91521db8ab30f0be25483ca64a1664bc79 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gdk-pixbuf/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - gdk-pixbuf + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gdk-pixbuf/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gdk-pixbuf/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gdk-pixbuf/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..188c5a0ebc4e1d619d9d94783f0cc6b22d07e3f2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install gecode via conda (e.g., from bioconda) +RUN conda install -c bioconda gecode -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/gecode_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/gecode_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/gecode_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/app/gecode_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/app/gecode_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7b31a75a197287fe8b09b8a94664cc02be886588 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/app/gecode_server.py @@ -0,0 +1,136 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +@mcp.tool() +def fzn_gecode( + fzn_file: str, + all_solutions: bool = False, + num_solutions: int = 1, + parallel: int = 1, + time_limit: int = 0, + statistics: bool = False, + free_search: bool = False, + seed: int = 0, + output_file: Optional[str] = None, +) -> Dict[str, Any]: + """ + Execute the Gecode FlatZinc interpreter to solve constraint problems. + + Args: + fzn_file: Path to the FlatZinc (.fzn) input file. + all_solutions: Search for all solutions (overrides num_solutions). + num_solutions: Number of solutions to search for (default 1, use 0 for all). + parallel: Number of threads to use for parallel search (default 1). + time_limit: Time limit in milliseconds (0 for no limit). + statistics: Print solver statistics after execution. + free_search: Use free search (ignore search annotations in the FZN file). + seed: Random seed for the solver. + output_file: Redirect solver output to a specific file. + """ + # Input validation + fzn_path = Path(fzn_file) + if not fzn_path.exists(): + return { + "error": f"Input FlatZinc file not found: {fzn_file}", + "command_executed": "" + } + + if not fzn_path.suffix == ".fzn": + # Warning: Gecode expects .fzn files, but we proceed as the user might have renamed it + pass + + # Construct command + cmd = ["fzn-gecode"] + + # Handle solution count + if all_solutions: + cmd.append("-a") + elif num_solutions != 1: + if num_solutions < 0: + return {"error": "num_solutions must be non-negative", "command_executed": ""} + cmd.extend(["-n", str(num_solutions)]) + + # Parallelism + if parallel < 1: + return {"error": "parallel threads must be at least 1", "command_executed": ""} + cmd.extend(["-p", str(parallel)]) + + # Time limit + if time_limit > 0: + cmd.extend(["-t", str(time_limit)]) + elif time_limit < 0: + return {"error": "time_limit must be non-negative", "command_executed": ""} + + # Boolean flags + if statistics: + cmd.append("-s") + if free_search: + cmd.append("-f") + + # Seed + if seed != 0: + cmd.extend(["-r", str(seed)]) + + # Output file + if output_file: + cmd.extend(["-o", output_file]) + + # Positional argument + cmd.append(str(fzn_path)) + + try: + # Execute the solver + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [output_file] if output_file else [] + } + + except subprocess.CalledProcessError as e: + return { + "error": f"Gecode execution failed with exit code {e.returncode}", + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr + } + except FileNotFoundError: + return { + "error": "fzn-gecode binary not found. Ensure Gecode is installed and in your PATH.", + "command_executed": " ".join(cmd) + } + +@mcp.tool() +def gecode_version() -> Dict[str, Any]: + """ + Check the installed version of Gecode via fzn-gecode. + """ + cmd = ["fzn-gecode", "--help"] # fzn-gecode usually prints version in help or doesn't have a --version flag + + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=False # Help might return non-zero in some versions + ) + + # Extract version if possible, otherwise return full help text + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr + } + except Exception as e: + return { + "error": str(e), + "command_executed": " ".join(cmd) + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/app/gecode_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/app/gecode_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9c3f4ff6047b033ced816419c7ece84e3930b576 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/app/gecode_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/app/gecode_server.py') +SERVER_NAME = 'biosci_gecode' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..ca9ecb1af7004f343b32366cf068817cb4ab3891 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-gecode: + build: . + image: mcp-gecode:latest + container_name: mcp-gecode + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=gecode + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7a165e14d0d6ef65359e61a9f7283f7010690b73 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - gecode + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gemini/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gemini/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gemini/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..32942a00b2b3eaaff07033c3392ce0e04240dc8f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install gene-trajectory-python via conda (e.g., from bioconda) +RUN conda install -c bioconda gene-trajectory-python -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/gene-trajectory-python_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/gene-trajectory-python_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/gene-trajectory-python_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/app/gene-trajectory-python_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/app/gene-trajectory-python_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2fe6d6a68ebadba6390913c669b688fdc57ef1cc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/app/gene-trajectory-python_server.py @@ -0,0 +1,207 @@ +import subprocess +import tempfile +import sys +from pathlib import Path +from typing import Optional, Dict, List + +# MCP-related imports are intentionally omitted as per the instructions. +# from mcp import tool + +# @mcp.tool() +def run_gene_trajectory( + adata_path: Path, + output_adata_path: Path, + obsm_key: str = 'X_pca', + n_variable_genes: int = 2000, + layer: Optional[str] = None, + n_components: int = 50, + n_neighbors: int = 15, + use_highly_variable: bool = True, + resolution: float = 1.0, + n_clusters: Optional[int] = None, + n_groups: int = 100, + n_pcs: int = 50, + n_diff_maps: int = 15, + t: int = 1, + random_state: int = 0, + output_trajectory_plot: Optional[Path] = None, + trajectory_plot_basis: str = 'X_diffmap_eval', + output_heatmap_plot: Optional[Path] = None, + heatmap_plot_n_genes: int = 10, + output_feature_plot: Optional[Path] = None, + feature_plot_basis: str = 'X_umap', +) -> Dict: + """ + Runs the full GeneTrajectory pipeline on a single-cell dataset. + + This tool identifies trajectories of genes rather than cells by calculating + optimal transport distances between gene distributions across the cell-cell graph. + It takes an AnnData object as input, performs the analysis, and saves the + updated AnnData object with trajectory information. Optional plots can also be generated. + + Args: + adata_path: Path to the input AnnData file (`.h5ad`). + output_adata_path: Path to save the output AnnData file (`.h5ad`) with results. + obsm_key: Key in `adata.obsm` for the PCA representation. + n_variable_genes: Number of highly variable genes to use. + layer: The layer in `adata` to use for computation. If None, `adata.X` is used. + n_components: Number of principal components to compute if `obsm_key` is not present. + n_neighbors: Number of neighbors for the cell-cell graph. + use_highly_variable: Whether to use highly variable genes. + resolution: Resolution for Leiden clustering. + n_clusters: Number of clusters for K-means in coarse-graining. If None, it's determined automatically. + n_groups: Number of groups for coarse-graining. + n_pcs: Number of principal components for the diffusion map. + n_diff_maps: Number of diffusion maps to compute. + t: Time step for the diffusion map. + random_state: Random state for reproducibility. + output_trajectory_plot: Optional path to save the gene trajectory plot as a PNG file. + trajectory_plot_basis: Basis to use for the trajectory plot (e.g., 'X_diffmap_eval'). + output_heatmap_plot: Optional path to save the gene program heatmap as a PNG file. + heatmap_plot_n_genes: Number of genes to display in the heatmap for each program. + output_feature_plot: Optional path to save the gene program feature plot as a PNG file. + feature_plot_basis: Basis to use for the feature plot (e.g., 'X_umap'). + + Returns: + A dictionary containing the executed command, stdout, stderr, and a + dictionary of output file paths. + """ + # 1. Input validation + if not adata_path.is_file(): + raise FileNotFoundError(f"Input AnnData file not found: {adata_path}") + if n_variable_genes <= 0: + raise ValueError("n_variable_genes must be a positive integer.") + if n_components <= 0: + raise ValueError("n_components must be a positive integer.") + if n_neighbors <= 0: + raise ValueError("n_neighbors must be a positive integer.") + if resolution <= 0: + raise ValueError("resolution must be a positive float.") + if n_groups <= 0: + raise ValueError("n_groups must be a positive integer.") + if n_pcs <= 0: + raise ValueError("n_pcs must be a positive integer.") + if n_diff_maps <= 0: + raise ValueError("n_diff_maps must be a positive integer.") + if t <= 0: + raise ValueError("t must be a positive integer.") + + with tempfile.TemporaryDirectory() as temp_dir_str: + temp_dir = Path(temp_dir_str) + script_path = temp_dir / "run_gene_trajectory_script.py" + + # 2. Generate the Python script to execute the library's functions + # This approach isolates the execution and dependencies from the MCP server. + script_content = f""" +import sys +import warnings +import anndata as ad +import gene_trajectory as gt +import matplotlib.pyplot as plt + +# Suppress common warnings from underlying libraries for cleaner output +warnings.filterwarnings("ignore", category=UserWarning, module='scanpy') +warnings.filterwarnings("ignore", category=FutureWarning) + +try: + # Load input data + adata = ad.read_h5ad(r'{adata_path.resolve()}') + + # Instantiate the GeneTrajectory model + model = gt.GeneTrajectory() + + # Run the full pipeline + adata_result = model.run( + adata, + obsm_key='{obsm_key}', + n_variable_genes={n_variable_genes}, + layer={repr(layer)}, + n_components={n_components}, + n_neighbors={n_neighbors}, + use_highly_variable={use_highly_variable}, + resolution={resolution}, + n_clusters={repr(n_clusters)}, + n_groups={n_groups}, + n_pcs={n_pcs}, + n_diff_maps={n_diff_maps}, + t={t}, + random_state={random_state}, + copy=True + ) + + # Save the resulting AnnData object + adata_result.write_h5ad(r'{output_adata_path.resolve()}') + + # Generate and save optional plots + if {output_trajectory_plot is not None}: + output_traj_plot_path = r'{str(output_trajectory_plot.resolve()) if output_trajectory_plot else ""}' + fig, ax = plt.subplots(figsize=(6, 6)) + model.plot_trajectory(basis='{trajectory_plot_basis}', ax=ax) + fig.savefig(output_traj_plot_path, bbox_inches='tight', dpi=300) + plt.close(fig) + + if {output_heatmap_plot is not None}: + output_heatmap_plot_path = r'{str(output_heatmap_plot.resolve()) if output_heatmap_plot else ""}' + # plot_program_heatmap returns a seaborn ClusterGrid object + grid = model.plot_program_heatmap(n_genes={heatmap_plot_n_genes}) + grid.savefig(output_heatmap_plot_path, bbox_inches='tight', dpi=300) + plt.close() + + if {output_feature_plot is not None}: + output_feature_plot_path = r'{str(output_feature_plot.resolve()) if output_feature_plot else ""}' + # Check if the required basis exists in the AnnData object + if '{feature_plot_basis}' not in adata_result.obsm: + print( + f"Warning: Basis '{feature_plot_basis}' not found in adata.obsm. Skipping feature plot.", + file=sys.stderr + ) + else: + fig, ax = plt.subplots(figsize=(6, 6)) + model.plot_program_feature(basis='{feature_plot_basis}', ax=ax) + fig.savefig(output_feature_plot_path, bbox_inches='tight', dpi=300) + plt.close(fig) + +except Exception as e: + print(f"An error occurred during GeneTrajectory execution: {{e}}", file=sys.stderr) + sys.exit(1) + +print("GeneTrajectory analysis completed successfully.") +""" + script_path.write_text(script_content) + + # 3. Execute the script in a subprocess + command = [sys.executable, str(script_path)] + command_str = " ".join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + cwd=temp_dir, + ) + except subprocess.CalledProcessError as e: + print(f"Error executing GeneTrajectory script.") + print(f"Return Code: {e.returncode}") + print(f"Stdout: {e.stdout}") + print(f"Stderr: {e.stderr}") + raise + + # 4. Collect output file paths for the structured result + output_files = {"processed_adata": str(output_adata_path)} + if output_trajectory_plot: + output_files["trajectory_plot"] = str(output_trajectory_plot) + if output_heatmap_plot: + output_files["heatmap_plot"] = str(output_heatmap_plot) + if output_feature_plot: + # Only report the file if it was actually created + if output_feature_plot.exists(): + output_files["feature_plot"] = str(output_feature_plot) + + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/app/gene-trajectory-python_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/app/gene-trajectory-python_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..28f1e739cc1d0ddf97b1ba8652474b5f51ddfe2e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/app/gene-trajectory-python_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/app/gene-trajectory-python_server.py') +SERVER_NAME = 'biosci_gene_trajectory_python' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b68133a781ac89b833e4be98d3c9a9cd38515c96 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-gene-trajectory-python: + build: . + image: mcp-gene-trajectory-python:latest + container_name: mcp-gene-trajectory-python + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=gene-trajectory-python + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5cb770853c3173ebb88d12829eac41c5511c2817 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - gene-trajectory-python + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..213a7bc07c5ea131bfbcb0ebc2ed9aa890fbd852 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install genecircuitry via conda (e.g., from bioconda) +RUN conda install -c bioconda genecircuitry -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/genecircuitry_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/genecircuitry_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/genecircuitry_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/app/genecircuitry_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/app/genecircuitry_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0270b930fb0ae560d203b32f50ba5efd48c34616 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/app/genecircuitry_server.py @@ -0,0 +1,149 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided by the MCP framework. +def tool(func): + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + return wrapper + +mcp = type("mcp", (), {"tool": tool}) + +@mcp.tool +def run_pipeline( + input_file: Path, + output_dir: Path, + steps: Optional[List[str]] = None, + skip_celloracle: bool = False, + skip_hotspot: bool = False, + seed: Optional[int] = None, + n_jobs: int = 1, + min_genes: Optional[int] = None, + cluster_key_stratification: Optional[str] = None, + parallel: bool = False, +): + """ + Runs the complete genecircuitry analysis pipeline for TRN analysis from single-cell data. + + This tool integrates Scanpy for preprocessing, CellOracle for GRN inference, + and Hotspot for identifying embedding-aware gene modules. + """ + # --- Input Validation --- + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + if n_jobs <= 0: + raise ValueError("n_jobs must be a positive integer.") + + allowed_steps = [ + "load", "preprocessing", "stratification", "clustering", + "celloracle", "hotspot", "grn_analysis", "summary" + ] + if steps: + for step in steps: + if step not in allowed_steps: + raise ValueError( + f"Invalid step '{step}'. Allowed steps are: {', '.join(allowed_steps)}" + ) + + if parallel and not cluster_key_stratification: + raise ValueError( + "When --parallel is enabled, --cluster-key-stratification must be provided." + ) + + # --- File Path Handling --- + try: + output_dir.mkdir(parents=True, exist_ok=True) + except OSError as e: + raise OSError(f"Failed to create output directory {output_dir}: {e}") + + # --- Command Construction --- + # The documentation suggests the main entry point is a script, but a `genecircuitry` + # CLI is also mentioned. We will assume the installed package provides this entry point. + cmd = [ + "genecircuitry", + "--input", str(input_file), + "--output", str(output_dir), + ] + + if steps: + cmd.append("--steps") + cmd.extend(steps) + + if skip_celloracle: + cmd.append("--skip-celloracle") + + if skip_hotspot: + cmd.append("--skip-hotspot") + + if seed is not None: + cmd.extend(["--seed", str(seed)]) + + cmd.extend(["--n-jobs", str(n_jobs)]) + + if min_genes is not None: + cmd.extend(["--min-genes", str(min_genes)]) + + if cluster_key_stratification: + cmd.extend(["--cluster-key-stratification", cluster_key_stratification]) + + if parallel: + cmd.append("--parallel") + + command_executed = " ".join(cmd) + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + cwd=output_dir, # Run from the output directory to keep logs/temp files contained + ) + except FileNotFoundError: + return { + "error": "genecircuitry command not found. Please ensure the tool is installed and in the system's PATH.", + "command_executed": command_executed, + "stdout": "", + "stderr": "Executable not found.", + } + except subprocess.CalledProcessError as e: + return { + "error": "GeneCircuitry pipeline failed.", + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + } + + # --- Structured Result Return --- + # Based on the documentation, these are the expected primary output files. + # The exact files generated may depend on the steps run. + output_files = { + "preprocessed_data": str(output_dir / "preprocessed_adata.h5ad"), + "analysis_summary": str(output_dir / "analysis_summary.txt"), + "celloracle_object": str(output_dir / "celloracle" / "oracle_object.celloracle.oracle"), + "celloracle_links": str(output_dir / "celloracle" / "grn_links.celloracle.links"), + "hotspot_autocorrelation": str(output_dir / "hotspot" / "autocorrelation_results.csv"), + "hotspot_significant_genes": str(output_dir / "hotspot" / "significant_genes.csv"), + "hotspot_gene_modules": str(output_dir / "hotspot" / "gene_modules.csv"), + "qc_figures_dir": str(output_dir / "figures" / "qc"), + "grn_analysis_figures_dir": str(output_dir / "figures" / "grn_analysis"), + } + + # Filter out files that might not have been created + final_output_files = { + key: path for key, path in output_files.items() if Path(path).exists() or Path(path).is_dir() + } + + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": final_output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/app/genecircuitry_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/app/genecircuitry_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4bfec86a52c8d6b3216c3b083897f3fa520c5eca --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/app/genecircuitry_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/app/genecircuitry_server.py') +SERVER_NAME = 'biosci_genecircuitry' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..4305260b7f842346d4014789333765ec1e58a88d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-genecircuitry: + build: . + image: mcp-genecircuitry:latest + container_name: mcp-genecircuitry + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=genecircuitry + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c13817ea451b574b9afccc6bc309ff83684f1444 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - genecircuitry + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..944c9b550be5e296d66666faf06685b27c88fe5b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install geneimpacts via conda (e.g., from bioconda) +RUN conda install -c bioconda geneimpacts -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/geneimpacts_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/geneimpacts_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/geneimpacts_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/app/geneimpacts_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/app/geneimpacts_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ea5770fd28f9db2d9201c7c5fc9b4850dc6fcda1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/app/geneimpacts_server.py @@ -0,0 +1,216 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, Dict, List, Any + +# This is a placeholder for the actual mcp decorator. +# Per the instructions, there is "NO NEED to import mcp". +def tool(*args, **kwargs): + def decorator(f): + return f + return decorator + +mcp = type("mcp", (), {"tool": tool}) + +# The Python script that will be executed by the MCP tool. +# This script uses the geneimpacts library to perform the core logic. +VCF_PROCESSING_SCRIPT = """ +import sys +import argparse +import re +from geneimpacts import Vep, SnpEff, BCFtools + +def get_parser_and_header(ann_type, ann_field, vcf_header_lines): + \"\"\"Find the INFO header and return the parser class and format string.\"\"\" + parser_class = None + if ann_type == 'vep': + parser_class = Vep + elif ann_type == 'snpeff': + parser_class = SnpEff + elif ann_type == 'bcftools': + parser_class = BCFtools + else: + # This case should be caught by argparse choices, but is here for safety. + raise ValueError(f"Unknown annotation type: {ann_type}") + + # Regex to find the format string within the VCF INFO header description + header_pattern = re.compile(f'##INFO=') + format_string = None + for line in vcf_header_lines: + match = header_pattern.search(line) + if match: + format_string = match.group(1).strip() + break + + if format_string is None: + raise ValueError(f"Could not find format string for INFO field '{ann_field}' in VCF header. " + f"Expected a ##INFO line with 'Format: ...' in the description.") + + return parser_class, format_string + +def get_top_impact_string(effects): + \"\"\"Get a string representation of the top impact(s).\"\"\" + if not effects: + return "." + + # Effect.top_severity can return a single object or a list if there's a tie + top_effects = effects[0].top_severity(effects) + if not isinstance(top_effects, list): + top_effects = [top_effects] + + # Create a unique, sorted list of strings for deterministic output + impact_strings = {f"{e.gene}|{e.impact_severity}|{e.impact}" for e in top_effects} + return ",".join(sorted(list(impact_strings))) + +def main(): + parser = argparse.ArgumentParser(description="Prioritize variant impacts in a VCF file using geneimpacts.") + parser.add_argument('input_vcf', help="Input VCF file.") + parser.add_argument('output_vcf', help="Output VCF file.") + parser.add_argument('--ann_type', required=True, choices=['vep', 'snpeff', 'bcftools'], help="Annotation type.") + parser.add_argument('--ann_field', required=True, help="INFO field containing the annotations (e.g., CSQ, ANN).") + parser.add_argument('--new_field', required=True, help="Name for the new INFO field with the top impact.") + args = parser.parse_args() + + header_lines = [] + variant_lines = [] + with open(args.input_vcf, 'r') as infile: + for line in infile: + if line.startswith('#'): + header_lines.append(line) + else: + variant_lines.append(line) + + try: + EffectParser, format_header = get_parser_and_header(args.ann_type, args.ann_field, header_lines) + except ValueError as e: + sys.stderr.write(str(e) + '\\n') + sys.exit(1) + + with open(args.output_vcf, 'w') as outfile: + # Write original header, inserting our new INFO field definition + for line in header_lines: + if line.startswith('#CHROM'): + new_header_line = f'##INFO=' + outfile.write(new_header_line + '\\n') + outfile.write(line) + + # Process and write variant lines + for line in variant_lines: + fields = line.strip().split('\\t') + info_col = fields[7] + + info_dict = {item.split('=', 1)[0]: item.split('=', 1)[1] if '=' in item else True for item in info_col.split(';')} + + top_impact_str = "." + if args.ann_field in info_dict and info_dict[args.ann_field] is not True: + ann_string = info_dict[args.ann_field] + try: + parser_instance = EffectParser(ann_string, header=format_header) + effects = list(parser_instance) + top_impact_str = get_top_impact_string(effects) + except Exception as e: + sys.stderr.write(f"Warning: Could not process variant {fields[0]}:{fields[1]}. Error: {e}\\n") + top_impact_str = "ERROR_PARSING" + + new_info_entry = f"{args.new_field}={top_impact_str}" + + if info_col == ".": + fields[7] = new_info_entry + else: + fields[7] = f"{info_col};{new_info_entry}" + + outfile.write('\\t'.join(fields) + '\\n') + +if __name__ == "__main__": + main() +""" + +@mcp.tool() +def prioritize( + vcf_file: Path, + annotation_type: str, + annotation_field: str, + output_vcf: Optional[Path] = None, + new_info_field: str = "GI_TOP" +) -> Dict[str, Any]: + """ + Prioritizes variant effects from VEP, SnpEff, or BCFtools annotations in a VCF file. + + This tool reads a VCF file, parses the specified annotation field, uses the + geneimpacts library to determine the most severe impact for each variant, and + writes a new VCF file with this information added to a new INFO field. + + Args: + vcf_file: Path to the input VCF file. + annotation_type: The type of annotation to parse. Must be one of 'vep', 'snpeff', or 'bcftools'. + annotation_field: The INFO field tag containing the annotations (e.g., 'CSQ' for VEP, 'ANN' for SnpEff). + output_vcf: Optional path for the output annotated VCF file. If not provided, a temporary file will be created. + new_info_field: The name for the new INFO field that will store the top impact. Defaults to 'GI_TOP'. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a dictionary of output files. + """ + # 1. Input validation + if not vcf_file.is_file(): + raise FileNotFoundError(f"Input VCF file not found: {vcf_file}") + + valid_ann_types = ['vep', 'snpeff', 'bcftools'] + if annotation_type not in valid_ann_types: + raise ValueError(f"Invalid annotation_type '{annotation_type}'. Must be one of {valid_ann_types}") + + if not new_info_field.isalnum() or new_info_field[0].isdigit(): + raise ValueError(f"new_info_field '{new_info_field}' must be alphanumeric and not start with a digit.") + + with tempfile.TemporaryDirectory() as temp_dir: + temp_dir_path = Path(temp_dir) + + # 2. File path handling + if output_vcf: + output_path = output_vcf + if not output_path.parent.exists(): + raise FileNotFoundError(f"Parent directory for output file does not exist: {output_path.parent}") + else: + output_path = temp_dir_path / f"{vcf_file.stem}.geneimpacts.vcf" + + script_path = temp_dir_path / "vcf_processor.py" + script_path.write_text(VCF_PROCESSING_SCRIPT) + + # 3. Subprocess execution + cmd = [ + "python", str(script_path), + str(vcf_file), + str(output_path), + "--ann_type", annotation_type, + "--ann_field", annotation_field, + "--new_field", new_info_field + ] + + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + cwd=temp_dir + ) + + # 4. Structured result return + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": { + "annotated_vcf": str(output_path) + } + } + except subprocess.CalledProcessError as e: + # 5. Error handling + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"geneimpacts wrapper script failed with exit code {e.returncode}", + "output_files": {} + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/app/geneimpacts_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/app/geneimpacts_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b02e03a3b1597af9a272a37a88563dd58feab827 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/app/geneimpacts_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/app/geneimpacts_server.py') +SERVER_NAME = 'biosci_geneimpacts' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e1424409c91a5cbcae6d38cd7d93f102148e4eff --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-geneimpacts: + build: . + image: mcp-geneimpacts:latest + container_name: mcp-geneimpacts + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=geneimpacts + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4023730e6af4aafca019059182af9c5ac28b8e53 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - geneimpacts + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genenotebook/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genenotebook/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genenotebook/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ddf766830fcfcfd2147a46b06c8ed5b06222e739 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install genoboo via conda (e.g., from bioconda) +RUN conda install -c bioconda genoboo -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/genoboo_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/genoboo_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/genoboo_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/app/genoboo_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/app/genoboo_server.py new file mode 100644 index 0000000000000000000000000000000000000000..22cd6dfad8906eec5f75b872fa0f9c8e9d29f27e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/app/genoboo_server.py @@ -0,0 +1,200 @@ +import subprocess +from pathlib import Path +from typing import Optional + +# Note: The @mcp.tool decorator is used for MCP integration and is assumed to be available in the execution environment. +# No import is included here as per the instructions. + + +@mcp.tool() +def run_genenotebook(port: int = 3000, timeout: int = 60): + """ + Starts the GeneNoteBook server. + + This command initiates the server process, which does not terminate on its own. + A timeout is used to capture the initial startup logs and then terminate the process. + Managing the long-running server process is outside the scope of this tool. + The default admin account is username: 'admin', password: 'admin'. + """ + # Input validation + if not (1 <= port <= 65535): + raise ValueError("Port must be an integer between 1 and 65535.") + if timeout <= 0: + raise ValueError("Timeout must be a positive integer.") + + cmd = ["genenotebook", "run", "--port", str(port)] + command_executed = " ".join(cmd) + stdout_str = "" + stderr_str = "" + + try: + # Run the command with a timeout, as it's a server process. + # We don't use check=True because a timeout is the expected outcome. + process = subprocess.run( + cmd, capture_output=True, text=True, timeout=timeout + ) + stdout_str = process.stdout + stderr_str = process.stderr + # If it exits before timeout, it might be an error + if process.returncode != 0: + stderr_str += ( + f"\nProcess exited unexpectedly with code {process.returncode}." + ) + except subprocess.TimeoutExpired as e: + # This is the expected outcome for a server process. + stdout_str = e.stdout if e.stdout else "" + stderr_str = e.stderr if e.stderr else "" + stderr_str += f"\nProcess timed out after {timeout} seconds, as expected for a server startup." + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'genenotebook' command not found. Please ensure it is installed and in your PATH.", + "output_files": [], + } + + return { + "command_executed": command_executed, + "stdout": stdout_str, + "stderr": stderr_str, + "output_files": [], + } + + +@mcp.tool() +def add_genome( + genome_fasta: Path, + name: str, + username: str, + password: str, + port: int = 3000, +): + """ + Adds a genome from a FASTA file to a running GeneNoteBook instance. + + This tool requires a GeneNoteBook server to be running and accessible at the specified port. + """ + # Input validation + if not genome_fasta.is_file(): + raise FileNotFoundError(f"Input genome FASTA file not found: {genome_fasta}") + if not name: + raise ValueError("A name for the genome (-n) must be provided.") + if not username: + raise ValueError("A username (-u) must be provided.") + if not password: + raise ValueError("A password (-p) must be provided.") + if not (1 <= port <= 65535): + raise ValueError("Port must be an integer between 1 and 65535.") + + cmd = [ + "genenotebook", + "add", + "genome", + "-u", + username, + "-p", + password, + "--port", + str(port), + "-n", + name, + str(genome_fasta), + ] + command_executed = " ".join(cmd) + + try: + process = subprocess.run(cmd, check=True, capture_output=True, text=True) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'genenotebook' command not found. Please ensure it is installed and in your PATH.", + "output_files": [], + } + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [], + } + + +@mcp.tool() +def add_annotation( + annotation_gff3: Path, + name: str, + username: str, + password: str, + port: int = 3000, +): + """ + Adds an annotation file (GFF3) to a genome in a running GeneNoteBook instance. + + This tool requires a GeneNoteBook server to be running and accessible at the specified port. + The 'name' parameter should match the name of an existing genome in the database. + """ + # Input validation + if not annotation_gff3.is_file(): + raise FileNotFoundError( + f"Input annotation GFF3 file not found: {annotation_gff3}" + ) + if not name: + raise ValueError("A name for the target genome (-n) must be provided.") + if not username: + raise ValueError("A username (-u) must be provided.") + if not password: + raise ValueError("A password (-p) must be provided.") + if not (1 <= port <= 65535): + raise ValueError("Port must be an integer between 1 and 65535.") + + cmd = [ + "genenotebook", + "add", + "annotation", + "-u", + username, + "-p", + password, + "--port", + str(port), + "-n", + name, + str(annotation_gff3), + ] + command_executed = " ".join(cmd) + + try: + process = subprocess.run(cmd, check=True, capture_output=True, text=True) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'genenotebook' command not found. Please ensure it is installed and in your PATH.", + "output_files": [], + } + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": [], + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/app/genoboo_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/app/genoboo_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..dbd923e4dd3c2fc6d40db07535f17a33712acc6f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/app/genoboo_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/app/genoboo_server.py') +SERVER_NAME = 'biosci_genoboo' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d95e54fa9cf32a5059e622fc11a0b650f5f51331 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-genoboo: + build: . + image: mcp-genoboo:latest + container_name: mcp-genoboo + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=genoboo + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..291ae9aedc78182371625c2946aa17a140bebea7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - genoboo + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomad/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomad/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomad/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4a3f716070b1b34672491acdda037e2451615282 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install genomepy via conda (e.g., from bioconda) +RUN conda install -c bioconda genomepy -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/genomepy_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/genomepy_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/genomepy_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/app/genomepy_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/app/genomepy_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6be1e4ab791180740720fb72d0b34a5c603fa98c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/app/genomepy_server.py @@ -0,0 +1,346 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Literal, Dict, Any + +# Define common types for reusability and clarity +GenomeMaskType = Literal["hard", "soft", "none"] +ProviderType = Literal["GENCODE", "Ensembl", "UCSC", "NCBI", "Local", "URL"] +UCSCAnnotationType = Literal["ncbiRefSeq", "refGene", "ensGene", "knownGene"] +PluginName = Literal["blacklist", "bowtie2", "bwa", "gmap", "hisat2", "minimap2", "star"] + +def _run_genomepy_command( + command_args: List[str], + expected_output_paths: Optional[List[Path]] = None +) -> Dict[str, Any]: + """ + Helper function to run genomepy commands and handle output/errors. + """ + cmd = ["genomepy"] + command_args + command_executed = " ".join(map(str, cmd)) + stdout = "" + stderr = "" + output_files_found: List[str] = [] + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + stdout = result.stdout + stderr = result.stderr + + if expected_output_paths: + for p in expected_output_paths: + if p.exists(): + output_files_found.append(str(p.resolve())) + + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Command failed with exit code {e.returncode}", + "output_files": output_files_found, + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "genomepy command not found. Please ensure it is installed and in your PATH.", + "error": "genomepy executable not found", + "output_files": output_files_found, + } + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files_found, + } + +@mcp.tool() +def get_version() -> Dict[str, Any]: + """ + Show the genomepy version. + """ + return _run_genomepy_command(["--version"]) + +@mcp.tool() +def search( + term: str, + provider: Optional[ProviderType] = None, + size: bool = False, +) -> Dict[str, Any]: + """ + Search for genomes and gene annotations by name, taxonomy ID, or assembly accession ID. + + Args: + term: The search term (e.g., genome name, taxonomy ID, assembly accession ID). + provider: Limit the search result to a specific provider (e.g., "UCSC", "Ensembl"). + size: If True, get the absolute size of each genome (this option slows down the search). + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + if not term: + raise ValueError("Search term cannot be empty.") + + cmd_args = ["search", term] + if provider: + cmd_args.extend(["--provider", provider]) + if size: + cmd_args.append("--size") + + return _run_genomepy_command(cmd_args) + +@mcp.tool() +def install( + name_or_path_or_url: str, + annotation: bool = False, + provider: Optional[ProviderType] = None, + genomes_dir: Optional[Path] = None, + regex: Optional[str] = None, + no_match: bool = False, + mask: GenomeMaskType = "soft", + bgzip: bool = False, + localname: Optional[str] = None, + url_to_annotation: Optional[str] = None, + local_path_to_annotation: Optional[Path] = None, + force: bool = False, + threads: int = 8, + ucsc_annotation: Optional[UCSCAnnotationType] = None, +) -> Dict[str, Any]: + """ + Install a genome and optionally run active plugins. + Supports downloading from providers (Ensembl, UCSC, NCBI, GENCODE), URLs, or local files. + + Args: + name_or_path_or_url: The genome name, URL, or local file path to install. + annotation: If True, download gene annotation files along with the genome. + provider: Specify the provider by name (e.g., "UCSC", "Ensembl"). Required for URL/Local. + genomes_dir: Directory where genomes will be saved. Defaults to ~/.local/share/genomes/. + regex: A regular expression to filter for matching sequences (e.g., 'chr[0-9XY]+$'). + no_match: Use with --regex to filter for non-matching sequences. + mask: Masking type for genome sequences. Choices: "hard" (ACNNN), "soft" (ACgtN), "none" (ACGTN). + bgzip: If True, compress the downloaded data using bgzip. + localname: Local name for the genome (used when provider is URL or Local). + url_to_annotation: URL to an annotation file (used with --provider URL). + local_path_to_annotation: Filepath to a local annotation file (used with --provider Local). + force: If True, overwrite local files if they exist. + threads: Number of threads to use for aligner index creation (if plugins are active). + ucsc_annotation: Specific UCSC annotation type to download (e.g., "refGene", "ncbiRefSeq"). + Only applicable when --provider UCSC. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + if not name_or_path_or_url: + raise ValueError("Genome name, path, or URL cannot be empty.") + if threads < 1: + raise ValueError("Number of threads must be a positive integer.") + if no_match and not regex: + raise ValueError("--no-match requires --regex to be set.") + if url_to_annotation and provider != "URL": + raise ValueError("--URL-to-annotation can only be used with --provider URL.") + if local_path_to_annotation and provider != "Local": + raise ValueError("--Local-path-to-annotation can only be used with --provider Local.") + if ucsc_annotation and provider != "UCSC": + raise ValueError("--UCSC-annotation can only be used with --provider UCSC.") + if local_path_to_annotation and not Path(local_path_to_annotation).is_file(): + raise FileNotFoundError(f"Local annotation file not found: {local_path_to_annotation}") + + cmd_args = ["install", name_or_path_or_url] + + if annotation: + cmd_args.append("--annotation") + if provider: + cmd_args.extend(["--provider", provider]) + + final_genomes_dir = genomes_dir if genomes_dir else Path.home() / ".local" / "share" / "genomes" + final_genomes_dir.mkdir(parents=True, exist_ok=True) + cmd_args.extend(["--genomes_dir", str(final_genomes_dir)]) + + if regex: + cmd_args.extend(["--regex", regex]) + if no_match: + cmd_args.append("--no-match") + if mask != "soft": + cmd_args.extend(["--mask", mask]) + if bgzip: + cmd_args.append("--bgzip") + if localname: + cmd_args.extend(["--localname", localname]) + if url_to_annotation: + cmd_args.extend(["--URL-to-annotation", url_to_annotation]) + if local_path_to_annotation: + cmd_args.extend(["--Local-path-to-annotation", str(local_path_to_annotation)]) + if force: + cmd_args.append("--force") + if threads != 8: + cmd_args.extend(["--threads", str(threads)]) + if ucsc_annotation: + cmd_args.extend(["--UCSC-annotation", ucsc_annotation]) + + # Determine the local name for the genome, which forms the subfolder name + genome_local_name: str + if localname: + genome_local_name = localname + elif provider in ["Local", "URL"]: + base_name = Path(name_or_path_or_url).name + # Remove common genome file extensions to get the base name genomepy uses for folders + suffixes_to_remove = [".fa.gz", ".fasta.gz", ".fa", ".fasta", ".tar.gz", ".tar"] + for suffix in suffixes_to_remove: + if base_name.endswith(suffix): + base_name = base_name[:-len(suffix)] + break + genome_local_name = base_name + else: + genome_local_name = name_or_path_or_url + + # Predict potential output files + expected_output_paths: List[Path] = [] + genome_output_folder = final_genomes_dir / genome_local_name + + fasta_filename = f"{genome_local_name}.fa.gz" if bgzip else f"{genome_local_name}.fa" + expected_output_paths.append(genome_output_folder / fasta_filename) + expected_output_paths.append(genome_output_folder / f"{fasta_filename}.fai") # pyfaidx index + expected_output_paths.append(genome_output_folder / "README.txt") # Reproducibility file + + if annotation: + expected_output_paths.append(genome_output_folder / f"{genome_local_name}.annotation.gtf") + expected_output_paths.append(genome_output_folder / f"{genome_local_name}.annotation.bed") + + return _run_genomepy_command(cmd_args, expected_output_paths=expected_output_paths) + +@mcp.tool() +def annotation( + genome_name: str, + provider: Optional[ProviderType] = None, + genomes_dir: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Show the first lines of each available gene annotation for a specified genome. + + Args: + genome_name: The name of the genome for which to inspect annotations. + provider: Limit to a specific provider. + genomes_dir: Directory where genomes are stored. Defaults to ~/.local/share/genomes/. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + if not genome_name: + raise ValueError("Genome name cannot be empty.") + + cmd_args = ["annotation", genome_name] + if provider: + cmd_args.extend(["--provider", provider]) + if genomes_dir: + if not genomes_dir.is_dir(): + raise FileNotFoundError(f"Genomes directory not found: {genomes_dir}") + cmd_args.extend(["--genomes_dir", str(genomes_dir)]) + + return _run_genomepy_command(cmd_args) + +@mcp.tool() +def clean() -> Dict[str, Any]: + """ + Remove local provider data and cached genome lists. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + return _run_genomepy_command(["clean"]) + +@mcp.tool() +def config_generate() -> Dict[str, Any]: + """ + Generate a default genomepy configuration file (~/.config/genomepy/genomepy.yaml). + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + config_file = Path.home() / ".config" / "genomepy" / "genomepy.yaml" + return _run_genomepy_command(["config", "generate"], expected_output_paths=[config_file]) + +@mcp.tool() +def genomes( + provider: Optional[ProviderType] = None, + size: bool = False, +) -> Dict[str, Any]: + """ + List available genomes, optionally filtered by provider and including genome sizes. + + Args: + provider: Limit the genome list to a specific provider. + size: If True, get the absolute size of each genome (this option slows down the search). + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + cmd_args = ["genomes"] + if provider: + cmd_args.extend(["--provider", provider]) + if size: + cmd_args.append("--size") + + return _run_genomepy_command(cmd_args) + +@mcp.tool() +def plugin_list() -> Dict[str, Any]: + """ + List currently enabled genomepy plugins. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + return _run_genomepy_command(["plugin", "list"]) + +@mcp.tool() +def plugin_enable( + plugin_name: PluginName, +) -> Dict[str, Any]: + """ + Enable a genomepy plugin. + Plugins are optional steps executed after installing an assembly (e.g., blacklist, aligner indexes). + + Args: + plugin_name: The name of the plugin to enable (e.g., "blacklist", "bwa", "star"). + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + if not plugin_name: + raise ValueError("Plugin name cannot be empty.") + + return _run_genomepy_command(["plugin", "enable", plugin_name]) + +@mcp.tool() +def plugin_disable( + plugin_name: PluginName, +) -> Dict[str, Any]: + """ + Disable a genomepy plugin. + + Args: + plugin_name: The name of the plugin to disable. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + if not plugin_name: + raise ValueError("Plugin name cannot be empty.") + + return _run_genomepy_command(["plugin", "disable", plugin_name]) + +@mcp.tool() +def providers() -> Dict[str, Any]: + """ + List all available genome providers. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + return _run_genomepy_command(["providers"]) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/app/genomepy_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/app/genomepy_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..28a37e0d5f4cb2510a6770c6fd397fb3260281e2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/app/genomepy_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/app/genomepy_server.py') +SERVER_NAME = 'biosci_genomepy' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..3455f14b494854c25f1106be5051c5bd220482dc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-genomepy: + build: . + image: mcp-genomepy:latest + container_name: mcp-genomepy + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=genomepy + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..79d3cd708200e3e876e83229c304fb979ca021d3 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - genomepy + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genometools-genometools/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genometools-genometools/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3aa064f05ec4b044e232cf92137728482c64dd39 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genometools-genometools/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install genometools-genometools via conda (e.g., from bioconda) +RUN conda install -c bioconda genometools-genometools -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/genometools-genometools_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/genometools-genometools_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/genometools-genometools_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genometools-genometools/app/genometools-genometools_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genometools-genometools/app/genometools-genometools_server.py new file mode 100644 index 0000000000000000000000000000000000000000..60e8ecec60826f557589ad6bbd517990d84be0be --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genometools-genometools/app/genometools-genometools_server.py @@ -0,0 +1,626 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# Helper function to build command list from parameters +def _build_command(base_cmd: List[str], params: dict) -> List[str]: + """Builds a command list from a dictionary of parameters.""" + cmd = list(base_cmd) + for key, value in params.items(): + if value is None: + continue + if isinstance(value, bool): + if value: + cmd.append(f"-{key}") + elif isinstance(value, list): + for item in value: + cmd.extend([f"-{key}", str(item)]) + else: + cmd.extend([f"-{key}", str(value)]) + return cmd + +@mcp.tool() +def gff3( + gff3_files: List[Path], + sort: bool = False, + sortlines: bool = False, + tidy: bool = False, + add_ids: bool = False, + check_ids: bool = False, + fail_on_warning: bool = False, + typecheck: Optional[Path] = None, + xrfcheck: Optional[str] = None, + show_retain_body: bool = False, + add_contigs: bool = False, + contigs_file: Optional[Path] = None, + offset: Optional[int] = None, + offset_file: Optional[Path] = None, + set_source: Optional[str] = None, + out_file: Optional[Path] = None, +) -> dict: + """ + Parse, check, and format GFF3 files. Output is written to stdout by default. + + Args: + gff3_files: One or more GFF3 files to process. + sort: Sort the GFF3 features. + sortlines: Sort the GFF3 file line by line. + tidy: Tidy up the GFF3 files. + add_ids: Add missing IDs to features. + check_ids: Check uniqueness of feature IDs. + fail_on_warning: Fail if a warning occurs during parsing. + typecheck: Check feature types against the given ontology file. + xrfcheck: Check attribute values against the given ontology. + show_retain_body: Show '##sequence-region' lines from input and add '##contig' lines for contigs not seen in input. + add_contigs: Add '##contig' lines for all contigs. + contigs_file: File containing contigs to add. + offset: Add this offset to all coordinates. + offset_file: File containing offsets for each sequence ID. + set_source: Set the source field of all top-level features to the given string. + out_file: Optional path to write the output GFF3. If not provided, output is in stdout. + """ + for f in gff3_files: + if not f.exists(): + raise FileNotFoundError(f"Input GFF3 file not found: {f}") + if typecheck and not typecheck.exists(): + raise FileNotFoundError(f"Typecheck ontology file not found: {typecheck}") + if contigs_file and not contigs_file.exists(): + raise FileNotFoundError(f"Contigs file not found: {contigs_file}") + if offset_file and not offset_file.exists(): + raise FileNotFoundError(f"Offset file not found: {offset_file}") + + cmd = ["gt", "gff3"] + if sort: cmd.append("-sort") + if sortlines: cmd.append("-sortlines") + if tidy: cmd.append("-tidy") + if add_ids: cmd.append("-addids") + if check_ids: cmd.append("-checkids") + if fail_on_warning: cmd.append("-fail") + if typecheck: cmd.extend(["-typecheck", str(typecheck)]) + if xrfcheck: cmd.extend(["-xrfcheck", xrfcheck]) + if show_retain_body: cmd.append("-show_retain_body") + if add_contigs: cmd.append("-addcontigs") + if contigs_file: cmd.extend(["-contigsfile", str(contigs_file)]) + if offset is not None: cmd.extend(["-offset", str(offset)]) + if offset_file: cmd.extend(["-offsetfile", str(offset_file)]) + if set_source: cmd.extend(["-setsource", set_source]) + if out_file: cmd.extend(["-o", str(out_file)]) + + cmd.extend([str(f) for f in gff3_files]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + output_files = [str(out_file)] if out_file and out_file.exists() else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"genometools gff3 failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) from e + +@mcp.tool() +def gff3validator( + gff3_files: List[Path], + typecheck: Optional[Path] = None, + xrfcheck: Optional[str] = None, +) -> dict: + """ + Validate GFF3 files according to the specification. + + Args: + gff3_files: One or more GFF3 files to validate. + typecheck: Check feature types against the given ontology file. + xrfcheck: Check attribute values against the given ontology. + """ + for f in gff3_files: + if not f.exists(): + raise FileNotFoundError(f"Input GFF3 file not found: {f}") + if typecheck and not typecheck.exists(): + raise FileNotFoundError(f"Typecheck ontology file not found: {typecheck}") + + cmd = ["gt", "gff3validator"] + if typecheck: cmd.extend(["-typecheck", str(typecheck)]) + if xrfcheck: cmd.extend(["-xrfcheck", xrfcheck]) + cmd.extend([str(f) for f in gff3_files]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"genometools gff3validator failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) from e + +@mcp.tool() +def sketch( + gff3_file: Path, + style_file: Path, + output_file: Path, + seqid: Optional[str] = None, + range_start: Optional[int] = None, + range_end: Optional[int] = None, + format: str = "png", + width: int = 800, + force: bool = False, +) -> dict: + """ + Create a graphical representation of genome annotations (AnnotationSketch). + + Args: + gff3_file: The GFF3 file to sketch. + style_file: A style file describing how to draw the annotations. + output_file: The path to the output image file. + seqid: The sequence ID to draw. If not given, all sequences are drawn. + range_start: The start of the range to draw. + range_end: The end of the range to draw. + format: The output format (png, pdf, ps, svg). + width: The width of the output image in pixels. + force: Force overwriting of the output file if it exists. + """ + if not gff3_file.exists(): + raise FileNotFoundError(f"Input GFF3 file not found: {gff3_file}") + if not style_file.exists(): + raise FileNotFoundError(f"Style file not found: {style_file}") + if (range_start is not None and range_end is None) or (range_start is None and range_end is not None): + raise ValueError("Both range_start and range_end must be specified if one is.") + if format not in ["png", "pdf", "ps", "svg"]: + raise ValueError("Invalid format. Must be one of 'png', 'pdf', 'ps', 'svg'.") + + cmd = ["gt", "sketch"] + cmd.extend(["-style", str(style_file)]) + cmd.extend(["-o", str(output_file)]) + if seqid: cmd.extend(["-seqid", seqid]) + if range_start is not None and range_end is not None: + cmd.extend(["-range", f"{range_start} {range_end}"]) + cmd.extend(["-format", format]) + cmd.extend(["-width", str(width)]) + if force: cmd.append("-force") + cmd.append(str(gff3_file)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + output_files = [str(output_file)] if output_file.exists() else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"genometools sketch failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) from e + +@mcp.tool() +def encseq_encode( + db_files: List[Path], + index_name: str, + sds: str = "yes", + md5: str = "yes", + sat: Optional[str] = None, + dna: bool = False, + protein: bool = False, + lossless: bool = False, + des: str = "yes", + ssp: str = "yes", +) -> dict: + """ + Encode sequence files into a compressed format (encseq). + + Args: + db_files: List of sequence files (e.g., FASTA) to encode. + index_name: Basename for the output index files. + sds: Skip description support (yes, no). + md5: Compute MD5 sums for sequences (yes, no). + sat: Suffix array type (e.g., direct, lcp, bwt). + dna: Assume DNA sequences. + protein: Assume protein sequences. + lossless: Use lossless encoding. + des: Create description table (yes, no). + ssp: Create sequence separator position table (yes, no). + """ + for f in db_files: + if not f.exists(): + raise FileNotFoundError(f"Input sequence file not found: {f}") + + cmd = ["gt", "encseq", "encode"] + cmd.extend(["-indexname", index_name]) + cmd.extend(["-sds", sds]) + cmd.extend(["-md5", md5]) + if sat: cmd.extend(["-sat", sat]) + if dna: cmd.append("-dna") + if protein: cmd.append("-protein") + if lossless: cmd.append("-lossless") + cmd.extend(["-des", des]) + cmd.extend(["-ssp", ssp]) + cmd.extend([str(f) for f in db_files]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + # Identify created index files + output_files = [] + extensions = [".esq", ".ssp", ".des", ".sds", ".md5", ".prj"] + if sat: + extensions.extend([".suf", ".lcp", ".bwt"]) + for ext in extensions: + f = Path(f"{index_name}{ext}") + if f.exists(): + output_files.append(str(f)) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"genometools encseq encode failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) from e + +@mcp.tool() +def ltrharvest( + index: str, + gff3_files: Optional[List[Path]] = None, + verbose: bool = False, + overlaps: str = "best", + seed: int = 0, + minlenltr: int = 100, + maxlenltr: int = 1000, + mindistltr: int = 1000, + maxdistltr: int = 25000, + similar: float = 85.0, + motif: Optional[str] = "tgca", + motifmis: int = 1, + xdrop: int = 5, + mat: Optional[Path] = None, + mis: int = -2, + ins: int = -3, + delete: int = -3, + vic: int = 60, + mintsd: int = 4, + maxtsd: int = 20, + fasta: Optional[Path] = None, + fastawidth: int = 0, + gff3_out: Optional[Path] = None, + out: Optional[str] = None, +) -> dict: + """ + De novo detection of LTR retrotransposons. + + Args: + index: Basename of the encoded sequence index. + gff3_files: Optional GFF3 files with sequence regions to process. + verbose: Be verbose. + overlaps: Handling of overlapping predictions (best, no, all, inner). + seed: Seed for random number generator. + minlenltr: Minimum length of LTRs in bp. + maxlenltr: Maximum length of LTRs in bp. + mindistltr: Minimum distance of LTRs in bp. + maxdistltr: Maximum distance of LTRs in bp. + similar: Similarity threshold in percent. + motif: 2 bp motif at LTR boundaries. + motifmis: Max number of mismatches in motif. + xdrop: X-drop extension threshold for alignment. + mat: Score matrix file. + mis: Mismatch score for alignment. + ins: Insertion score for alignment. + delete: Deletion score for alignment. + vic: Length of vicinity for TSD search. + mintsd: Minimum length of TSDs in bp. + maxtsd: Maximum length of TSDs in bp. + fasta: Output sequences for predicted LTRs to this file. + fastawidth: Width for FASTA output. + gff3_out: Output predictions to this GFF3 file. + out: Output FASTA and GFF3 to files with this prefix (mutually exclusive with -fasta and -gff3). + """ + if not Path(f"{index}.esq").exists(): + raise FileNotFoundError(f"Encoded sequence index not found for basename: {index}") + if out and (fasta or gff3_out): + raise ValueError("-out is mutually exclusive with -fasta and -gff3_out") + if overlaps not in ["best", "no", "all", "inner"]: + raise ValueError("Invalid value for 'overlaps'. Must be one of 'best', 'no', 'all', 'inner'.") + + cmd = ["gt", "ltrharvest", "-index", index] + if verbose: cmd.append("-v") + cmd.extend(["-overlaps", overlaps]) + cmd.extend(["-seed", str(seed)]) + cmd.extend(["-minlenltr", str(minlenltr)]) + cmd.extend(["-maxlenltr", str(maxlenltr)]) + cmd.extend(["-mindistltr", str(mindistltr)]) + cmd.extend(["-maxdistltr", str(maxdistltr)]) + cmd.extend(["-similar", str(similar)]) + if motif: cmd.extend(["-motif", motif]) + cmd.extend(["-motifmis", str(motifmis)]) + cmd.extend(["-xdrop", str(xdrop)]) + if mat: cmd.extend(["-mat", str(mat)]) + cmd.extend(["-mis", str(mis)]) + cmd.extend(["-ins", str(ins)]) + cmd.extend(["-del", str(delete)]) + cmd.extend(["-vic", str(vic)]) + cmd.extend(["-mintsd", str(mintsd)]) + cmd.extend(["-maxtsd", str(maxtsd)]) + if fasta: cmd.extend(["-fasta", str(fasta)]) + if fastawidth > 0: cmd.extend(["-fastawidth", str(fastawidth)]) + if gff3_out: cmd.extend(["-gff3", str(gff3_out)]) + if out: cmd.extend(["-out", out]) + if gff3_files: + for f in gff3_files: + if not f.exists(): raise FileNotFoundError(f"Input GFF3 file not found: {f}") + cmd.append(str(f)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + output_files = [] + if out: + gff_out_path = Path(f"{out}.gff3") + fasta_out_path = Path(f"{out}.fasta") + if gff_out_path.exists(): output_files.append(str(gff_out_path)) + if fasta_out_path.exists(): output_files.append(str(fasta_out_path)) + if fasta and fasta.exists(): output_files.append(str(fasta)) + if gff3_out and gff3_out.exists(): output_files.append(str(gff3_out)) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"genometools ltrharvest failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) from e + +@mcp.tool() +def ltrdigest( + gff3_file: Path, + sequence_index: str, + output_gff3: Path, + trna_library: Optional[Path] = None, + ppt_len: List[int] = [8, 30], + pbs_len: List[int] = [10, 30], + pbs_trna_ali_score_range: List[int] = [10, 30], + hmms: Optional[List[Path]] = None, + verbose: bool = False, +) -> dict: + """ + Annotate internal features of LTR retrotransposons. + + Args: + gff3_file: GFF3 file with LTR retrotransposon predictions (e.g., from ltrharvest). + sequence_index: Basename of the encoded sequence index. + output_gff3: Path for the output GFF3 file with annotations. + trna_library: FASTA file of tRNA sequences for PBS detection. + ppt_len: Range [min, max] for Polypurine Tract (PPT) length. + pbs_len: Range [min, max] for Primer Binding Site (PBS) length. + pbs_trna_ali_score_range: Range [min, max] for PBS-tRNA alignment score. + hmms: List of HMM profile files for protein domain searches. + verbose: Be verbose. + """ + if not gff3_file.exists(): + raise FileNotFoundError(f"Input GFF3 file not found: {gff3_file}") + if not Path(f"{sequence_index}.esq").exists(): + raise FileNotFoundError(f"Encoded sequence index not found for basename: {sequence_index}") + if trna_library and not trna_library.exists(): + raise FileNotFoundError(f"tRNA library file not found: {trna_library}") + if len(ppt_len) != 2 or len(pbs_len) != 2 or len(pbs_trna_ali_score_range) != 2: + raise ValueError("Length/score range parameters must be lists of two integers.") + + cmd = ["gt", "ltrdigest", "-seqfile", sequence_index] + if trna_library: cmd.extend(["-trnalib", str(trna_library)]) + cmd.extend(["-pptlen", f"{ppt_len[0]} {ppt_len[1]}"]) + cmd.extend(["-pbslen", f"{pbs_len[0]} {pbs_len[1]}"]) + cmd.extend(["-pbstrnaaliscorranges", f"{pbs_trna_ali_score_range[0]} {pbs_trna_ali_score_range[1]}"]) + if hmms: + for hmm in hmms: + if not hmm.exists(): raise FileNotFoundError(f"HMM file not found: {hmm}") + cmd.extend(["-hmms", str(hmm)]) + if verbose: cmd.append("-v") + cmd.extend(["-o", str(output_gff3)]) + cmd.append(str(gff3_file)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + output_files = [str(output_gff3)] if output_gff3.exists() else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"genometools ltrdigest failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) from e + +@mcp.tool() +def tallymer_create( + encoded_sequence: str, + index_name: str, + mer_size: int, + min_occ: int = 1, + prefix_length: int = 0, + counts: bool = False, + direction: str = "f", +) -> dict: + """ + Create a Tallymer index from an encoded sequence. + + Args: + encoded_sequence: Basename of the encoded sequence index. + index_name: Basename for the output Tallymer index. + mer_size: The k-mer size. + min_occ: Minimum occurrences of a k-mer to be included. + prefix_length: Set prefix length for bucket sort. + counts: Store k-mer counts in the index. + direction: Direction to consider (f: forward, r: reverse, p: both). + """ + if not Path(f"{encoded_sequence}.esq").exists(): + raise FileNotFoundError(f"Encoded sequence index not found: {encoded_sequence}") + if direction not in ["f", "r", "p"]: + raise ValueError("Direction must be 'f', 'r', or 'p'.") + + cmd = ["gt", "tallymer", "create"] + cmd.extend(["-esa", encoded_sequence]) + cmd.extend(["-indexname", index_name]) + cmd.extend(["-mersize", str(mer_size)]) + cmd.extend(["-minocc", str(min_occ)]) + cmd.extend(["-pl", str(prefix_length)]) + if counts: cmd.append("-counts") + cmd.extend(["-dir", direction]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + # Tallymer creates several files, e.g., .tis, .counts, .mer, etc. + # We list the most common ones. + output_files = [] + extensions = [".tis", ".mer", ".prj"] + if counts: extensions.append(".counts") + for ext in extensions: + f = Path(f"{index_name}{ext}") + if f.exists(): + output_files.append(str(f)) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"genometools tallymer create failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) from e + +@mcp.tool() +def tallymer_search( + query_file: Path, + index: str, + strand: str = "fp", + threshold: Optional[int] = None, + min_len: Optional[int] = None, + output_options: Optional[List[str]] = None, +) -> dict: + """ + Search for k-mers from a query file in a Tallymer index. Output is to stdout. + + Args: + query_file: FASTA file with query sequences. + index: Basename of the Tallymer index. + strand: Strand to search (f: forward, p: reverse, fp: both). + threshold: Report matches with count >= threshold. + min_len: Minimum length of a seed extension. + output_options: List of fields to output (e.g., qseqnum, qpos, counts). + """ + if not query_file.exists(): + raise FileNotFoundError(f"Query file not found: {query_file}") + if not Path(f"{index}.tis").exists(): + raise FileNotFoundError(f"Tallymer index not found: {index}") + if strand not in ["f", "p", "fp"]: + raise ValueError("Strand must be 'f', 'p', or 'fp'.") + + cmd = ["gt", "tallymer", "search"] + cmd.extend(["-q", str(query_file)]) + cmd.extend(["-index", index]) + cmd.extend(["-strand", strand]) + if threshold is not None: cmd.extend(["-t", str(threshold)]) + if min_len is not None: cmd.extend(["-l", str(min_len)]) + if output_options: + cmd.extend(["-output", " ".join(output_options)]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"genometools tallymer search failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) from e + +@mcp.tool() +def extractfeat( + gff3_file: Path, + seq_file: Path, + type: str, + join: bool = False, + translate: bool = False, + target_strand: Optional[str] = None, + seqid: Optional[str] = None, + out_file: Optional[Path] = None, +) -> dict: + """ + Extract features from a sequence file based on a GFF3 annotation. + + Args: + gff3_file: GFF3 annotation file. + seq_file: Sequence file (FASTA). + type: The feature type to extract (e.g., 'gene', 'exon'). + join: Join all features of the given type into a single sequence. + translate: Translate the extracted sequences into protein. + target_strand: Extract features only from this strand (+, -, .). + seqid: Extract features only from this sequence ID. + out_file: Optional path to write the output FASTA. If not provided, output is in stdout. + """ + if not gff3_file.exists(): + raise FileNotFoundError(f"GFF3 file not found: {gff3_file}") + if not seq_file.exists(): + raise FileNotFoundError(f"Sequence file not found: {seq_file}") + if target_strand and target_strand not in ["+", "-", "."]: + raise ValueError("target_strand must be '+', '-', or '.'") + + cmd = ["gt", "extractfeat", "-type", type] + cmd.extend(["-seqfile", str(seq_file)]) + if join: cmd.append("-join") + if translate: cmd.append("-translate") + if target_strand: cmd.extend(["-targetstrand", target_strand]) + if seqid: cmd.extend(["-seqid", seqid]) + if out_file: cmd.extend(["-o", str(out_file)]) + cmd.append(str(gff3_file)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + output_files = [str(out_file)] if out_file and out_file.exists() else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"genometools extractfeat failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) from e \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genometools-genometools/app/genometools-genometools_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genometools-genometools/app/genometools-genometools_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..014f0aa65ddc7017b960611e0ded3b94c948c8b7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genometools-genometools/app/genometools-genometools_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genometools-genometools/app/genometools-genometools_server.py') +SERVER_NAME = 'biosci_genometools_genometools' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genometools-genometools/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genometools-genometools/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genometools-genometools/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genometools-genometools/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genometools-genometools/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7d4bdd9749dbb57d3ecb9061ec9c6cc25cdf47ed --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genometools-genometools/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-genometools-genometools: + build: . + image: mcp-genometools-genometools:latest + container_name: mcp-genometools-genometools + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=genometools-genometools + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genometools-genometools/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genometools-genometools/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0d3bd9092b752d7f788179ea7d36ecd33ae19f0b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genometools-genometools/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - genometools-genometools + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genometools-genometools/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genometools-genometools/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genometools-genometools/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffread/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffread/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cb8645fc4708e0fb98fef13963f73292dc9b584e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffread/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install gffread via conda (e.g., from bioconda) +RUN conda install -c bioconda gffread -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/gffread_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/gffread_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/gffread_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffread/app/gffread_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffread/app/gffread_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e7fab064b02e2a07c2507b7100e21f5523499a6b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffread/app/gffread_server.py @@ -0,0 +1,443 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Union + +@mcp.tool() +def gffread_tool( + input_gff: Optional[Path] = None, + genomic_seqs: Optional[Path] = None, + seq_info_fsize: Optional[Path] = None, + output_file: Optional[Path] = None, + track_name: Optional[str] = None, + region: Optional[str] = None, + region_fully_contained: bool = False, + junction_match: Optional[str] = None, + no_pseudo: bool = False, + ids_list: Optional[Path] = None, + nids_list: Optional[Path] = None, + max_intron: Optional[int] = None, + min_length: Optional[int] = None, + discard_single_exon: bool = False, + coding_only: bool = False, + non_coding_only: bool = False, + ignore_locus: bool = False, + add_description_attribute: bool = False, + keep_all_gff_attrs: bool = False, + keep_exon_attrs: bool = False, + move_exon_attrs_to_transcript: bool = False, + output_attrs: Optional[str] = None, + keep_genes: bool = False, + keep_comments: bool = False, + process_other_records: bool = False, + discard_in_frame_stop_codons: bool = False, + adjust_cds_phase: bool = False, + check_single_exon_opposite_strand: bool = False, + add_coding_status_attrs: bool = False, + add_has_cds_attribute: bool = False, + adjust_stop_codon: bool = False, + discard_non_canonical_splice_sites: bool = False, + discard_incomplete_cds: bool = False, + input_is_bed: bool = False, + input_is_tlf: bool = False, + stream_processing: bool = False, + merge_transcripts: bool = False, + dup_info_file: Optional[Path] = None, + cluster_only: bool = False, + discard_shorter_contained: bool = False, + relax_boundary_containment: bool = False, + discard_overlapping_single_exon: bool = False, + force_exons: bool = False, + gene_to_exon: bool = False, + transcript_adopt_parent: bool = False, + decode_url_chars: bool = False, + merge_close_exons: bool = False, + output_junctions: bool = False, + exons_fasta_file: Optional[Path] = None, + w_add_bases: Optional[int] = None, + w_no_cds_info: bool = False, + cds_fasta_file: Optional[Path] = None, + tr_cds_fasta_file: Optional[Path] = None, + write_exon_coords_to_defline: bool = False, + use_star_for_stop_codon: bool = False, + ensembl_gtf_to_gff3: bool = False, + chr_replace_map: Optional[Path] = None, + output_gtf: bool = False, + output_bed: bool = False, + output_tlf: bool = False, + output_table: Optional[str] = None, + expose_warnings: bool = False, + sort_alphabetically: bool = False, + sort_by_ref_list: Optional[Path] = None, +) -> dict: + """ + Filter, convert, or cluster GFF/GTF/BED records, extract transcript sequences, and more. + + By default (i.e. without -O) only transcripts are processed, discarding any + other non-transcript features. Default output is a simplified GFF3 with only + the basic attributes. + + Args: + input_gff: Path to the input GFF/GTF/BED file. If not provided, gffread reads from stdin. + genomic_seqs: Full path to a multi-fasta file with genomic sequences, OR a directory + with single-fasta files (one per genomic sequence). Required for sequence extraction + when using options like -w, -x, -y, -V, -B, -P, --adj-stop. + seq_info_fsize: Tab-delimited file providing sequence info for -A option. + Format: . + output_file: Write the output records into this file instead of stdout. + track_name: Use in the 2nd column of each GFF/GTF output line. + region: Only show transcripts overlapping coordinate range .. + (on chromosome/contig , strand if provided). Format: `[]:-`. + region_fully_contained: For `region` option, discard all transcripts that are not fully + contained within the given range. + junction_match: Only output transcripts matching the given junction. Format: `:-`. + no_pseudo: Filter out records matching the 'pseudo' keyword. + ids_list: Discard records/transcripts if their IDs are not listed in this file. + nids_list: Discard records/transcripts if their IDs are listed in this file. + Mutually exclusive with `ids_list`. + max_intron: Discard transcripts having an intron larger than this value. Must be non-negative. + min_length: Discard transcripts shorter than this value (bases). Must be non-negative. + discard_single_exon: Discard single-exon transcripts. + coding_only: Discard mRNAs that have no CDS features. Mutually exclusive with `non_coding_only`. + non_coding_only: Discard mRNAs that have CDS features. Mutually exclusive with `coding_only`. + ignore_locus: Discard locus features and attributes found in the input. + add_description_attribute: Use the description field from `seq_info_fsize` and add it + as the value for a 'descr' attribute to the GFF record. Requires `seq_info_fsize`. + keep_all_gff_attrs: Keep all GFF attributes (for non-exon features). + keep_exon_attrs: For `keep_all_gff_attrs` option, do not attempt to reduce redundant + exon/CDS attributes. + move_exon_attrs_to_transcript: Do not keep exon attributes, move them to the transcript feature + (for GFF3 output). + output_attrs: Only output the GTF/GFF attributes listed in this comma-delimited list. + keep_genes: In transcript-only mode (default), also preserve gene records. + keep_comments: For GFF3 input/output, try to preserve comments. + process_other_records: Process other non-transcript GFF records (by default non-transcript + records are ignored). + discard_in_frame_stop_codons: Discard any mRNAs with CDS having in-frame stop codons. Requires `genomic_seqs`. + adjust_cds_phase: For `discard_in_frame_stop_codons` option, check and adjust the starting CDS phase + if the original phase leads to a translation with an in-frame stop codon. + check_single_exon_opposite_strand: For `discard_in_frame_stop_codons` option, single-exon transcripts + are also checked on the opposite strand. Requires `genomic_seqs`. + add_coding_status_attrs: Add transcript level GFF attributes about the coding status of each + transcript, including partialness or in-frame stop codons. Requires `genomic_seqs`. + add_has_cds_attribute: Add a "hasCDS" attribute with value "true" for transcripts that have CDS features. + adjust_stop_codon: Stop codon adjustment: enables `add_coding_status_attrs` and performs automatic + adjustment of the CDS stop coordinate if premature or downstream. + Implicitly enables -P, which requires `genomic_seqs`. + discard_non_canonical_splice_sites: Discard multi-exon mRNAs that have any intron with a non-canonical + splice site consensus (i.e. not GT-AG, GC-AG or AT-AC). + discard_incomplete_cds: Discard any mRNAs that either lack initial START codon + or the terminal STOP codon, or have an in-frame stop codon + (i.e. only print mRNAs with a complete CDS). + input_is_bed: Input should be parsed as BED format (automatic if the input filename ends with .bed*). + input_is_tlf: Input GFF-like one-line-per-transcript format without exon/CDS features + (automatic if the input filename ends with .tlf). + stream_processing: Fast processing of input GFF/BED transcripts as they are received + (no sorting, exons must be grouped by transcript in the input data). + merge_transcripts: Cluster the input transcripts into loci, discarding "redundant" transcripts + (those with the same exact introns and fully contained or equal boundaries). + Mutually exclusive with `cluster_only`. + dup_info_file: For `merge_transcripts` option, write duplication info to this file. + cluster_only: Same as `merge_transcripts` but without discarding any of the "duplicate" transcripts, + only create "locus" features. Mutually exclusive with `merge_transcripts`. + discard_shorter_contained: For `merge_transcripts` or `cluster_only` option: also discard as redundant + the shorter, fully contained transcripts (intron chains matching a part of the container). + relax_boundary_containment: For `merge_transcripts` or `cluster_only` option, no longer require boundary + containment when assessing redundancy (can be combined with `discard_shorter_contained`). + discard_overlapping_single_exon: For `merge_transcripts` or `cluster_only` option, enforce `relax_boundary_containment` + but also discard overlapping single-exon transcripts, even on the opposite strand + (can be combined with `discard_shorter_contained`). + force_exons: Make sure that the lowest level GFF features are considered "exon" features. + gene_to_exon: For single-line genes not parenting any transcripts, add an exon feature + spanning the entire gene (treat it as a transcript). + transcript_adopt_parent: Try to find a parent gene overlapping/containing a transcript + that does not have any explicit gene Parent. + decode_url_chars: Decode url encoded characters within attributes. + merge_close_exons: Merge very close exons into a single exon (when intron size<4). + output_junctions: Output the junctions and the corresponding transcripts. + exons_fasta_file: Write a fasta file with spliced exons for each transcript. Requires `genomic_seqs`. + w_add_bases: For the `exons_fasta_file` option, extract additional bases + both upstream and downstream of the transcript boundaries. Must be non-negative. + w_no_cds_info: For `exons_fasta_file`, disable the output of CDS info in the FASTA file. + cds_fasta_file: Write a fasta file with spliced CDS for each GFF transcript. Requires `genomic_seqs`. + tr_cds_fasta_file: Write a protein fasta file with the translation of CDS for each record. Requires `genomic_seqs`. + write_exon_coords_to_defline: For `exons_fasta_file`, `cds_fasta_file`, and `tr_cds_fasta_file` options, + write in the FASTA defline all the exon coordinates projected onto the spliced sequence. + use_star_for_stop_codon: For `tr_cds_fasta_file` option, use '*' instead of '.' as stop codon translation. + ensembl_gtf_to_gff3: Ensembl GTF to GFF3 conversion, adds version to IDs. + chr_replace_map: A name mapping table for converting reference sequence names, + having this 2-column format: . + output_gtf: Main output will be GTF instead of GFF3. Mutually exclusive with `output_bed`, `output_tlf`, `output_table`. + output_bed: Output records in BED format instead of default GFF3. Mutually exclusive with `output_gtf`, `output_tlf`, `output_table`. + output_tlf: Output "transcript line format". Mutually exclusive with `output_gtf`, `output_bed`, `output_table`. + output_table: Output a simple tab delimited format instead of GFF, with columns + having the values of GFF attributes given in . + Mutually exclusive with `output_gtf`, `output_bed`, `output_tlf`. + expose_warnings: Expose (warn about) duplicate transcript IDs and other potential + problems with the given GFF/GTF records. + sort_alphabetically: Chromosomes (reference sequences) are sorted alphabetically. + sort_by_ref_list: Sort the reference sequences by the order in which their + names are given in the file. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + command = ["gffread"] + output_files = [] + + # Input validation and command construction + if input_gff: + if not input_gff.is_file(): + raise FileNotFoundError(f"Input GFF file not found: {input_gff}") + command.append(str(input_gff)) + + if genomic_seqs: + if not genomic_seqs.exists(): # Check if it's a file or directory + raise FileNotFoundError(f"Genomic sequences file or directory not found: {genomic_seqs}") + command.extend(["-g", str(genomic_seqs)]) + + if seq_info_fsize: + if not seq_info_fsize.is_file(): + raise FileNotFoundError(f"Sequence info file not found: {seq_info_fsize}") + command.extend(["-s", str(seq_info_fsize)]) + + if ids_list and nids_list: + raise ValueError("Options --ids and --nids are mutually exclusive.") + if ids_list: + if not ids_list.is_file(): + raise FileNotFoundError(f"IDs list file not found: {ids_list}") + command.extend(["--ids", str(ids_list)]) + if nids_list: + if not nids_list.is_file(): + raise FileNotFoundError(f"NIDs list file not found: {nids_list}") + command.extend(["--nids", str(nids_list)]) + + if coding_only and non_coding_only: + raise ValueError("Options -C (coding only) and --nc (non-coding only) are mutually exclusive.") + + if merge_transcripts and cluster_only: + raise ValueError("Options -M/--merge and --cluster-only are mutually exclusive.") + + output_format_options_count = sum([output_gtf, output_bed, output_tlf, output_table is not None]) + if output_format_options_count > 1: + raise ValueError("Only one output format option (-T, --bed, --tlf, --table) can be specified.") + + # Add parameters to command list + if output_file: + command.extend(["-o", str(output_file)]) + output_files.append(str(output_file)) + + if track_name: + command.extend(["-t", track_name]) + if region: + command.extend(["-r", region]) + if region_fully_contained: + command.append("-R") + if junction_match: + command.extend(["--jmatch", junction_match]) + if no_pseudo: + command.append("--no-pseudo") + + if max_intron is not None: + if max_intron < 0: + raise ValueError("max_intron must be a non-negative integer.") + command.extend(["-i", str(max_intron)]) + if min_length is not None: + if min_length < 0: + raise ValueError("min_length must be a non-negative integer.") + command.extend(["-l", str(min_length)]) + if discard_single_exon: + command.append("-U") + if coding_only: + command.append("-C") + if non_coding_only: + command.append("--nc") + if ignore_locus: + command.append("--ignore-locus") + if add_description_attribute: + if not seq_info_fsize: + raise ValueError("Option -A requires -s to be provided.") + command.append("-A") + + if keep_all_gff_attrs: + command.append("-F") + if keep_exon_attrs: + if not keep_all_gff_attrs: + raise ValueError("--keep-exon-attrs requires -F option.") + command.append("--keep-exon-attrs") + if move_exon_attrs_to_transcript: + command.append("-G") + if output_attrs: + command.extend(["--attrs", output_attrs]) + if keep_genes: + command.append("--keep-genes") + if keep_comments: + command.append("--keep-comments") + if process_other_records: + command.append("-O") + + if discard_in_frame_stop_codons: + if not genomic_seqs: + raise ValueError("Option -V requires -g to be provided.") + command.append("-V") + if adjust_cds_phase: + if not discard_in_frame_stop_codons: + raise ValueError("Option -H requires -V option.") + command.append("-H") + if check_single_exon_opposite_strand: + if not discard_in_frame_stop_codons: + raise ValueError("Option -B requires -V option.") + if not genomic_seqs: # Redundant check, but good for clarity + raise ValueError("Option -B requires -g to be provided.") + command.append("-B") + if add_coding_status_attrs: + if not genomic_seqs: + raise ValueError("Option -P requires -g to be provided.") + command.append("-P") + if add_has_cds_attribute: + command.append("--add-hasCDS") + if adjust_stop_codon: + command.append("--adj-stop") + # --adj-stop implicitly enables -P, which requires -g + if not genomic_seqs: + raise ValueError("Option --adj-stop implicitly enables -P, which requires -g to be provided.") + + if discard_non_canonical_splice_sites: + command.append("-N") + if discard_incomplete_cds: + command.append("-J") + if input_is_bed: + command.append("--in-bed") + if input_is_tlf: + command.append("--in-tlf") + if stream_processing: + command.append("--stream") + + if merge_transcripts: + command.append("-M") + if dup_info_file: + if not merge_transcripts: + raise ValueError("Option -d requires -M/--merge option.") + command.extend(["-d", str(dup_info_file)]) + output_files.append(str(dup_info_file)) + if cluster_only: + command.append("--cluster-only") + + # Options -K, -Q, -Y require -M or --cluster-only + if discard_shorter_contained: + if not (merge_transcripts or cluster_only): + raise ValueError("Option -K requires -M/--merge or --cluster-only option.") + command.append("-K") + if relax_boundary_containment: + if not (merge_transcripts or cluster_only): + raise ValueError("Option -Q requires -M/--merge or --cluster-only option.") + command.append("-Q") + if discard_overlapping_single_exon: + if not (merge_transcripts or cluster_only): + raise ValueError("Option -Y requires -M/--merge or --cluster-only option.") + command.append("-Y") + + if force_exons: + command.append("--force-exons") + if gene_to_exon: + command.append("--gene2exon") + if transcript_adopt_parent: + command.append("--t-adopt") + if decode_url_chars: + command.append("-D") + if merge_close_exons: + command.append("-Z") + if output_junctions: + command.append("-j") + + if exons_fasta_file: + if not genomic_seqs: + raise ValueError("Option -w requires -g to be provided.") + command.extend(["-w", str(exons_fasta_file)]) + output_files.append(str(exons_fasta_file)) + if w_add_bases is not None: + if not exons_fasta_file: + raise ValueError("--w-add requires -w option.") + if w_add_bases < 0: + raise ValueError("w_add_bases must be a non-negative integer.") + command.extend(["--w-add", str(w_add_bases)]) + if w_no_cds_info: + if not exons_fasta_file: + raise ValueError("--w-nocds requires -w option.") + command.append("--w-nocds") + + if cds_fasta_file: + if not genomic_seqs: + raise ValueError("Option -x requires -g to be provided.") + command.extend(["-x", str(cds_fasta_file)]) + output_files.append(str(cds_fasta_file)) + if tr_cds_fasta_file: + if not genomic_seqs: + raise ValueError("Option -y requires -g to be provided.") + command.extend(["-y", str(tr_cds_fasta_file)]) + output_files.append(str(tr_cds_fasta_file)) + + if write_exon_coords_to_defline: + if not (exons_fasta_file or cds_fasta_file or tr_cds_fasta_file): + raise ValueError("Option -W requires at least one of -w, -x, or -y options.") + command.append("-W") + if use_star_for_stop_codon: + if not tr_cds_fasta_file: + raise ValueError("Option -S requires -y option.") + command.append("-S") + + if ensembl_gtf_to_gff3: + command.append("-L") + if chr_replace_map: + if not chr_replace_map.is_file(): + raise FileNotFoundError(f"Chromosome replacement map file not found: {chr_replace_map}") + command.extend(["-m", str(chr_replace_map)]) + + if output_gtf: + command.append("-T") + if output_bed: + command.append("--bed") + if output_tlf: + command.append("--tlf") + if output_table: + command.extend(["--table", output_table]) + + if expose_warnings: + command.append("-E") + + if sort_alphabetically: + command.append("--sort-alpha") + if sort_by_ref_list: + if not sort_by_ref_list.is_file(): + raise FileNotFoundError(f"Reference list file for sorting not found: {sort_by_ref_list}") + command.extend(["--sort-by", str(sort_by_ref_list)]) + + # Execute the command + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(p) for p in output_files] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"gffread command failed with exit code {e.returncode}: {e}", + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "gffread command not found. Please ensure it is installed and in your PATH.", + "error": "gffread command not found.", + "output_files": [] + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffread/app/gffread_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffread/app/gffread_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ec37b06e3bccdb09b6a1c00d8b2bf5615ab98f3a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffread/app/gffread_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffread/app/gffread_server.py') +SERVER_NAME = 'biosci_gffread' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffread/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffread/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffread/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffread/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffread/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..6f3f529a3ab14b57b391ae29bd92c8abf9c6f2db --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffread/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-gffread: + build: . + image: mcp-gffread:latest + container_name: mcp-gffread + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=gffread + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffread/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffread/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d6ad926439cb11f969083bde55d9b2f0c0715aae --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffread/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - gffread + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffread/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffread/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffread/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffutils/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffutils/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2e31cd043c911df0418526ab7803215b8f145169 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffutils/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install gffutils via conda (e.g., from bioconda) +RUN conda install -c bioconda gffutils -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/gffutils_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/gffutils_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/gffutils_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffutils/app/gffutils_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffutils/app/gffutils_server.py new file mode 100644 index 0000000000000000000000000000000000000000..19e3ec78e9ef6b04b65bb12ce475c402923a9acc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffutils/app/gffutils_server.py @@ -0,0 +1,616 @@ +import subprocess +from pathlib import Path +from typing import List, Optional + +# This is a placeholder for the actual decorator as per the user's request. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +def _add_flag(cmd: list, flag: str, value: bool): + """Helper to add a boolean flag to a command list if True.""" + if value: + cmd.append(flag) + +def _add_optional_arg(cmd: list, arg_name: str, value): + """Helper to add an optional argument with its value to a command list.""" + if value is not None: + cmd.extend([arg_name, str(value)]) + +@mcp.tool() +def gffutils_create( + db: Path, + gff_files: List[Path], + gff_dialect: Optional[str] = None, + id_spec: Optional[str] = None, + merge_strategy: str = "error", + transform: Optional[Path] = None, + force: bool = False, + verbose: bool = False, + disable_infer_transcripts: bool = False, + disable_infer_genes: bool = False, + disable_infer_extents: bool = False, + disable_infer_cds_extent: bool = False, + disable_infer_exon_extent: bool = False, + disable_infer_transcript_extent: bool = False, + disable_infer_gene_extent: bool = False, + disable_create_introns: bool = False, + disable_fix_strand: bool = False, + disable_fix_parent_child: bool = False, + disable_fix_start_stop: bool = False, + disable_fix_attributes: bool = False, + disable_fix_gff3_dialect: bool = False, + disable_fix_gtf_dialect: bool = False, + disable_dialect_check: bool = False, + disable_pragma_check: bool = False, + disable_order_check: bool = False, + disable_id_check: bool = False, + disable_feature_check: bool = False, + disable_relationship_check: bool = False, + disable_format_check: bool = False, + disable_all_fixes: bool = False, + disable_all_checks: bool = False, +): + """ + Creates a new gffutils database from GFF/GTF files. + """ + if not gff_files: + raise ValueError("At least one GFF/GTF file must be provided.") + for gff_file in gff_files: + if str(gff_file) != "-" and not gff_file.exists(): + raise FileNotFoundError(f"Input GFF/GTF file not found: {gff_file}") + if transform and not transform.exists(): + raise FileNotFoundError(f"Transform file not found: {transform}") + if merge_strategy not in ["merge", "create_unique", "error", "warning", "ignore"]: + raise ValueError(f"Invalid merge_strategy: {merge_strategy}") + + cmd = ["gffutils-cli", "create", str(db)] + cmd.extend([str(f) for f in gff_files]) + + _add_optional_arg(cmd, "--gff-dialect", gff_dialect) + _add_optional_arg(cmd, "--id-spec", id_spec) + _add_optional_arg(cmd, "--merge-strategy", merge_strategy) + _add_optional_arg(cmd, "--transform", transform) + _add_flag(cmd, "--force", force) + _add_flag(cmd, "--verbose", verbose) + + disable_flags = { + "--disable-infer-transcripts": disable_infer_transcripts, "--disable-infer-genes": disable_infer_genes, + "--disable-infer-extents": disable_infer_extents, "--disable-infer-cds-extent": disable_infer_cds_extent, + "--disable-infer-exon-extent": disable_infer_exon_extent, "--disable-infer-transcript-extent": disable_infer_transcript_extent, + "--disable-infer-gene-extent": disable_infer_gene_extent, "--disable-create-introns": disable_create_introns, + "--disable-fix-strand": disable_fix_strand, "--disable-fix-parent-child": disable_fix_parent_child, + "--disable-fix-start-stop": disable_fix_start_stop, "--disable-fix-attributes": disable_fix_attributes, + "--disable-fix-gff3-dialect": disable_fix_gff3_dialect, "--disable-fix-gtf-dialect": disable_fix_gtf_dialect, + "--disable-dialect-check": disable_dialect_check, "--disable-pragma-check": disable_pragma_check, + "--disable-order-check": disable_order_check, "--disable-id-check": disable_id_check, + "--disable-feature-check": disable_feature_check, "--disable-relationship-check": disable_relationship_check, + "--disable-format-check": disable_format_check, "--disable-all-fixes": disable_all_fixes, + "--disable-all-checks": disable_all_checks, + } + for flag, value in disable_flags.items(): + _add_flag(cmd, flag, value) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(db)], + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"gffutils-cli create failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def gffutils_update( + db: Path, + gff_files: List[Path], + gff_dialect: Optional[str] = None, + id_spec: Optional[str] = None, + merge_strategy: str = "error", + transform: Optional[Path] = None, + verbose: bool = False, + disable_infer_transcripts: bool = False, + disable_infer_genes: bool = False, + disable_infer_extents: bool = False, + disable_infer_cds_extent: bool = False, + disable_infer_exon_extent: bool = False, + disable_infer_transcript_extent: bool = False, + disable_infer_gene_extent: bool = False, + disable_create_introns: bool = False, + disable_fix_strand: bool = False, + disable_fix_parent_child: bool = False, + disable_fix_start_stop: bool = False, + disable_fix_attributes: bool = False, + disable_fix_gff3_dialect: bool = False, + disable_fix_gtf_dialect: bool = False, + disable_dialect_check: bool = False, + disable_pragma_check: bool = False, + disable_order_check: bool = False, + disable_id_check: bool = False, + disable_feature_check: bool = False, + disable_relationship_check: bool = False, + disable_format_check: bool = False, + disable_all_fixes: bool = False, + disable_all_checks: bool = False, +): + """ + Updates an existing gffutils database with new GFF/GTF files. + """ + if not db.exists(): + raise FileNotFoundError(f"Database to update not found: {db}") + if not gff_files: + raise ValueError("At least one GFF/GTF file must be provided.") + for gff_file in gff_files: + if str(gff_file) != "-" and not gff_file.exists(): + raise FileNotFoundError(f"Input GFF/GTF file not found: {gff_file}") + if transform and not transform.exists(): + raise FileNotFoundError(f"Transform file not found: {transform}") + if merge_strategy not in ["merge", "create_unique", "error", "warning", "ignore"]: + raise ValueError(f"Invalid merge_strategy: {merge_strategy}") + + cmd = ["gffutils-cli", "update", str(db)] + cmd.extend([str(f) for f in gff_files]) + + _add_optional_arg(cmd, "--gff-dialect", gff_dialect) + _add_optional_arg(cmd, "--id-spec", id_spec) + _add_optional_arg(cmd, "--merge-strategy", merge_strategy) + _add_optional_arg(cmd, "--transform", transform) + _add_flag(cmd, "--verbose", verbose) + + disable_flags = { + "--disable-infer-transcripts": disable_infer_transcripts, "--disable-infer-genes": disable_infer_genes, + "--disable-infer-extents": disable_infer_extents, "--disable-infer-cds-extent": disable_infer_cds_extent, + "--disable-infer-exon-extent": disable_infer_exon_extent, "--disable-infer-transcript-extent": disable_infer_transcript_extent, + "--disable-infer-gene-extent": disable_infer_gene_extent, "--disable-create-introns": disable_create_introns, + "--disable-fix-strand": disable_fix_strand, "--disable-fix-parent-child": disable_fix_parent_child, + "--disable-fix-start-stop": disable_fix_start_stop, "--disable-fix-attributes": disable_fix_attributes, + "--disable-fix-gff3-dialect": disable_fix_gff3_dialect, "--disable-fix-gtf-dialect": disable_fix_gtf_dialect, + "--disable-dialect-check": disable_dialect_check, "--disable-pragma-check": disable_pragma_check, + "--disable-order-check": disable_order_check, "--disable-id-check": disable_id_check, + "--disable-feature-check": disable_feature_check, "--disable-relationship-check": disable_relationship_check, + "--disable-format-check": disable_format_check, "--disable-all-fixes": disable_all_fixes, + "--disable-all-checks": disable_all_checks, + } + for flag, value in disable_flags.items(): + _add_flag(cmd, flag, value) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(db)], + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"gffutils-cli update failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def gffutils_merge( + dbs: List[Path], + output: Optional[Path] = None, + force: bool = False, +): + """ + Merges multiple gffutils databases into a single database. + """ + if not dbs: + raise ValueError("At least one database must be provided for merging.") + for db_path in dbs: + if not db_path.exists(): + raise FileNotFoundError(f"Input database not found: {db_path}") + + cmd = ["gffutils-cli", "merge"] + cmd.extend([str(db) for db in dbs]) + + _add_optional_arg(cmd, "--output", output) + _add_flag(cmd, "--force", force) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + output_files = [str(output)] if output else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"gffutils-cli merge failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def gffutils_clean( + db: Path, + output: Optional[Path] = None, + force: bool = False, +): + """ + Cleans a gffutils database by removing orphaned features. + """ + if not db.exists(): + raise FileNotFoundError(f"Input database not found: {db}") + + cmd = ["gffutils-cli", "clean", str(db)] + _add_optional_arg(cmd, "--output", output) + _add_flag(cmd, "--force", force) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + output_file = output if output else db + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file)], + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"gffutils-cli clean failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def gffutils_dump( + db: Path, + output: Optional[Path] = None, + dialect: Optional[str] = None, + featuretype: Optional[str] = None, + id: Optional[str] = None, + seqid: Optional[str] = None, + start: Optional[int] = None, + end: Optional[int] = None, + strand: Optional[str] = None, + revcomp: bool = False, + limit: Optional[int] = None, + offset: Optional[int] = None, + attribute_split_char: Optional[str] = None, + attributes: Optional[str] = None, + extra_attributes: Optional[str] = None, + no_attributes: bool = False, + raw: bool = False, + table: Optional[str] = None, + fasta: Optional[Path] = None, + chrom_lookup: Optional[Path] = None, +): + """ + Dumps data from a gffutils database to various formats. + """ + if not db.exists(): + raise FileNotFoundError(f"Input database not found: {db}") + if fasta and not fasta.exists(): + raise FileNotFoundError(f"FASTA file not found: {fasta}") + if chrom_lookup and not chrom_lookup.exists(): + raise FileNotFoundError(f"Chromosome lookup file not found: {chrom_lookup}") + if strand and strand not in ["+", "-", "."]: + raise ValueError(f"Invalid strand: {strand}. Must be '+', '-', or '.'.") + + cmd = ["gffutils-cli", "dump", str(db)] + _add_optional_arg(cmd, "--output", output) + _add_optional_arg(cmd, "--dialect", dialect) + _add_optional_arg(cmd, "--featuretype", featuretype) + _add_optional_arg(cmd, "--id", id) + _add_optional_arg(cmd, "--seqid", seqid) + _add_optional_arg(cmd, "--start", start) + _add_optional_arg(cmd, "--end", end) + _add_optional_arg(cmd, "--strand", strand) + _add_flag(cmd, "--revcomp", revcomp) + _add_optional_arg(cmd, "--limit", limit) + _add_optional_arg(cmd, "--offset", offset) + _add_optional_arg(cmd, "--attribute-split-char", attribute_split_char) + _add_optional_arg(cmd, "--attributes", attributes) + _add_optional_arg(cmd, "--extra-attributes", extra_attributes) + _add_flag(cmd, "--no-attributes", no_attributes) + _add_flag(cmd, "--raw", raw) + _add_optional_arg(cmd, "--table", table) + _add_optional_arg(cmd, "--fasta", fasta) + _add_optional_arg(cmd, "--chrom-lookup", chrom_lookup) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + output_files = [str(output)] if output else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"gffutils-cli dump failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def gffutils_gff( + db: Path, + ids: List[str], + output: Optional[Path] = None, + parents: bool = False, + children: bool = False, + ancestors: bool = False, + descendants: bool = False, + level: Optional[int] = None, + featuretype: Optional[str] = None, + reverse: bool = False, + limit: Optional[int] = None, +): + """ + Retrieves features and their relatives from a database in GFF format. + """ + if not db.exists(): + raise FileNotFoundError(f"Input database not found: {db}") + if not ids: + raise ValueError("At least one feature ID must be provided.") + + cmd = ["gffutils-cli", "gff", str(db)] + cmd.extend(ids) + + _add_optional_arg(cmd, "--output", output) + _add_flag(cmd, "--parents", parents) + _add_flag(cmd, "--children", children) + _add_flag(cmd, "--ancestors", ancestors) + _add_flag(cmd, "--descendants", descendants) + _add_optional_arg(cmd, "--level", level) + _add_optional_arg(cmd, "--featuretype", featuretype) + _add_flag(cmd, "--reverse", reverse) + _add_optional_arg(cmd, "--limit", limit) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + output_files = [str(output)] if output else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"gffutils-cli gff failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def gffutils_fasta( + db: Path, + fasta: Path, + ids: List[str], + output: Optional[Path] = None, + featuretype: Optional[str] = None, + attribute: Optional[str] = None, + use_strand: bool = False, + prefix: Optional[str] = None, +): + """ + Retrieves sequences for features from a database. + """ + if not db.exists(): + raise FileNotFoundError(f"Input database not found: {db}") + if not fasta.exists(): + raise FileNotFoundError(f"Input FASTA file not found: {fasta}") + if not ids: + raise ValueError("At least one feature ID must be provided.") + + cmd = ["gffutils-cli", "fasta", str(db)] + cmd.extend(ids) + cmd.extend(["--fasta", str(fasta)]) + + _add_optional_arg(cmd, "--output", output) + _add_optional_arg(cmd, "--featuretype", featuretype) + _add_optional_arg(cmd, "--attribute", attribute) + _add_flag(cmd, "--use-strand", use_strand) + _add_optional_arg(cmd, "--prefix", prefix) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + output_files = [str(output)] if output else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"gffutils-cli fasta failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def gffutils_bed( + db: Path, + output: Optional[Path] = None, + featuretype: Optional[str] = None, + name_attribute: str = "ID", + score_attribute: Optional[str] = None, + thick_attribute: Optional[str] = None, + block_attribute: Optional[str] = None, + track_line: Optional[str] = None, +): + """ + Converts features from a gffutils database to BED format. + """ + if not db.exists(): + raise FileNotFoundError(f"Input database not found: {db}") + + cmd = ["gffutils-cli", "bed", str(db)] + _add_optional_arg(cmd, "--output", output) + _add_optional_arg(cmd, "--featuretype", featuretype) + _add_optional_arg(cmd, "--name-attribute", name_attribute) + _add_optional_arg(cmd, "--score-attribute", score_attribute) + _add_optional_arg(cmd, "--thick-attribute", thick_attribute) + _add_optional_arg(cmd, "--block-attribute", block_attribute) + _add_optional_arg(cmd, "--track-line", track_line) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + output_files = [str(output)] if output else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"gffutils-cli bed failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def gffutils_stats( + db: Path, + output: Optional[Path] = None, + feature_counts: bool = False, + attribute_counts: Optional[str] = None, +): + """ + Prints statistics about a gffutils database. + """ + if not db.exists(): + raise FileNotFoundError(f"Input database not found: {db}") + + # Default behavior is to print feature counts + if not feature_counts and not attribute_counts: + feature_counts = True + + cmd = ["gffutils-cli", "stats", str(db)] + _add_optional_arg(cmd, "--output", output) + _add_flag(cmd, "--feature-counts", feature_counts) + _add_optional_arg(cmd, "--attribute-counts", attribute_counts) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + output_files = [str(output)] if output else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"gffutils-cli stats failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def gffutils_sort( + gff_file: Path, + output: Optional[Path] = None, + force: bool = False, + disable_infer_transcripts: bool = False, + disable_infer_genes: bool = False, + disable_infer_extents: bool = False, + disable_infer_cds_extent: bool = False, + disable_infer_exon_extent: bool = False, + disable_infer_transcript_extent: bool = False, + disable_infer_gene_extent: bool = False, + disable_create_introns: bool = False, + disable_fix_strand: bool = False, + disable_fix_parent_child: bool = False, + disable_fix_start_stop: bool = False, + disable_fix_attributes: bool = False, + disable_fix_gff3_dialect: bool = False, + disable_fix_gtf_dialect: bool = False, + disable_dialect_check: bool = False, + disable_pragma_check: bool = False, + disable_order_check: bool = False, + disable_id_check: bool = False, + disable_feature_check: bool = False, + disable_relationship_check: bool = False, + disable_format_check: bool = False, + disable_all_fixes: bool = False, + disable_all_checks: bool = False, +): + """ + Sorts a GFF/GTF file. + """ + if str(gff_file) != "-" and not gff_file.exists(): + raise FileNotFoundError(f"Input GFF/GTF file not found: {gff_file}") + + cmd = ["gffutils-cli", "sort", str(gff_file)] + _add_optional_arg(cmd, "--output", output) + _add_flag(cmd, "--force", force) + + disable_flags = { + "--disable-infer-transcripts": disable_infer_transcripts, "--disable-infer-genes": disable_infer_genes, + "--disable-infer-extents": disable_infer_extents, "--disable-infer-cds-extent": disable_infer_cds_extent, + "--disable-infer-exon-extent": disable_infer_exon_extent, "--disable-infer-transcript-extent": disable_infer_transcript_extent, + "--disable-infer-gene-extent": disable_infer_gene_extent, "--disable-create-introns": disable_create_introns, + "--disable-fix-strand": disable_fix_strand, "--disable-fix-parent-child": disable_fix_parent_child, + "--disable-fix-start-stop": disable_fix_start_stop, "--disable-fix-attributes": disable_fix_attributes, + "--disable-fix-gff3-dialect": disable_fix_gff3_dialect, "--disable-fix-gtf-dialect": disable_fix_gtf_dialect, + "--disable-dialect-check": disable_dialect_check, "--disable-pragma-check": disable_pragma_check, + "--disable-order-check": disable_order_check, "--disable-id-check": disable_id_check, + "--disable-feature-check": disable_feature_check, "--disable-relationship-check": disable_relationship_check, + "--disable-format-check": disable_format_check, "--disable-all-fixes": disable_all_fixes, + "--disable-all-checks": disable_all_checks, + } + for flag, value in disable_flags.items(): + _add_flag(cmd, flag, value) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + output_files = [str(output)] if output else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"gffutils-cli sort failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def gffutils_validate( + gff_file: Path, + limit: Optional[int] = None, +): + """ + Validates a GFF/GTF file, reporting any errors found. + """ + if str(gff_file) != "-" and not gff_file.exists(): + raise FileNotFoundError(f"Input GFF/GTF file not found: {gff_file}") + + cmd = ["gffutils-cli", "validate", str(gff_file)] + _add_optional_arg(cmd, "--limit", limit) + + # The 'validate' command returns a non-zero exit code upon finding validation errors. + # This is expected behavior, so we do not use check=True. + result = subprocess.run(cmd, capture_output=True, text=True) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "exit_code": result.returncode, + "output_files": [], + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffutils/app/gffutils_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffutils/app/gffutils_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c6e6a481eb54c8c145ded9a8647b71310165983b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffutils/app/gffutils_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffutils/app/gffutils_server.py') +SERVER_NAME = 'biosci_gffutils' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffutils/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffutils/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffutils/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffutils/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffutils/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..67ae2cd8b332e0d6da26f913571041928167367a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffutils/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-gffutils: + build: . + image: mcp-gffutils:latest + container_name: mcp-gffutils + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=gffutils + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffutils/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffutils/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..64b0b539cc71a8a18f8df34cb34b9ffd952c76ac --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffutils/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - gffutils + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffutils/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffutils/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gffutils/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ghostscript/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ghostscript/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c2fb11bf00d9b4ed357b531dfec5f8b12ddecf4f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ghostscript/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install ghostscript via conda (e.g., from bioconda) +RUN conda install -c bioconda ghostscript -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/ghostscript_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/ghostscript_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/ghostscript_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ghostscript/app/ghostscript_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ghostscript/app/ghostscript_server.py new file mode 100644 index 0000000000000000000000000000000000000000..61003b8a49c81881d6d01d795d6166f2e9d2cd5b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ghostscript/app/ghostscript_server.py @@ -0,0 +1,330 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Union + +@mcp.tool() +def gs_pdf_to_images( + input_file: str, + output_pattern: str, + device: str = "png16m", + dpi: int = 300, + first_page: int = 1, + last_page: Optional[int] = None, + antialiasing_level: int = 4 +): + """ + Convert PDF pages into image files (PNG, JPEG, etc.) using Ghostscript. + + :param input_file: Path to the source PDF file. + :param output_pattern: Output filename pattern (e.g., 'page_%03d.png'). + :param device: Ghostscript device (e.g., 'png16m', 'pngalpha', 'jpeg', 'tiff24nc'). + :param dpi: Resolution in dots per inch. + :param first_page: First page to process. + :param last_page: Last page to process (optional). + :param antialiasing_level: Graphics and text antialiasing level (1, 2, or 4). + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + + if antialiasing_level not in [1, 2, 4]: + return {"error": "antialiasing_level must be 1, 2, or 4"} + + cmd = [ + "gs", + "-dNOPAUSE", + "-dBATCH", + "-sDEVICE=" + device, + f"-r{dpi}", + f"-dTextAlphaBits={antialiasing_level}", + f"-dGraphicsAlphaBits={antialiasing_level}", + f"-dFirstPage={first_page}", + f"-sOutputFile={output_pattern}" + ] + + if last_page is not None: + cmd.append(f"-dLastPage={last_page}") + + cmd.append(str(input_path)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_pattern": output_pattern + } + except subprocess.CalledProcessError as e: + return { + "error": "Ghostscript execution failed", + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def gs_merge_pdfs( + input_files: List[str], + output_file: str +): + """ + Merge multiple PDF files into a single PDF document. + + :param input_files: List of paths to PDF files to merge. + :param output_file: Path to the resulting merged PDF file. + """ + valid_inputs = [] + for f in input_files: + p = Path(f) + if p.exists(): + valid_inputs.append(str(p)) + else: + return {"error": f"Input file not found: {f}"} + + if not valid_inputs: + return {"error": "No valid input files provided"} + + cmd = [ + "gs", + "-dNOPAUSE", + "-dBATCH", + "-sDEVICE=pdfwrite", + f"-sOutputFile={output_file}" + ] + valid_inputs + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_file": output_file + } + except subprocess.CalledProcessError as e: + return { + "error": "Ghostscript merge failed", + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def gs_compress_pdf( + input_file: str, + output_file: str, + pdf_settings: str = "ebook", + compatibility_level: float = 1.4 +): + """ + Optimize and compress a PDF file. + + :param input_file: Path to the source PDF. + :param output_file: Path to the compressed output PDF. + :param pdf_settings: Compression level: 'screen' (72dpi), 'ebook' (150dpi), 'printer' (300dpi), 'prepress' (300dpi color preserved). + :param compatibility_level: PDF compatibility version (e.g., 1.4, 1.5). + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + + valid_settings = ["screen", "ebook", "printer", "prepress", "default"] + if pdf_settings not in valid_settings: + return {"error": f"Invalid pdf_settings. Must be one of: {valid_settings}"} + + cmd = [ + "gs", + "-dNOPAUSE", + "-dBATCH", + "-sDEVICE=pdfwrite", + f"-dCompatibilityLevel={compatibility_level}", + f"-dPDFSETTINGS=/{pdf_settings}", + f"-sOutputFile={output_file}", + str(input_path) + ] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_file": output_file + } + except subprocess.CalledProcessError as e: + return { + "error": "Ghostscript compression failed", + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def gs_ps_to_pdf( + input_file: str, + output_file: str, + fit_page: bool = False +): + """ + Convert a PostScript (.ps or .eps) file to a PDF. + + :param input_file: Path to the PostScript file. + :param output_file: Path to the output PDF file. + :param fit_page: If True, scales the PostScript to fit the page size. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + + cmd = [ + "gs", + "-dNOPAUSE", + "-dBATCH", + "-sDEVICE=pdfwrite", + f"-sOutputFile={output_file}" + ] + + if fit_page: + cmd.append("-dEPSFitPage") + + cmd.append(str(input_path)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_file": output_file + } + except subprocess.CalledProcessError as e: + return { + "error": "Ghostscript conversion failed", + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def gs_pdf_to_pdfa( + input_file: str, + output_file: str, + pdfa_version: int = 2, + icc_profile: Optional[str] = None +): + """ + Convert a standard PDF to a PDF/A (Archival) format. + + :param input_file: Path to the source PDF. + :param output_file: Path to the output PDF/A file. + :param pdfa_version: PDF/A version (1, 2, or 3). + :param icc_profile: Optional path to an ICC color profile file. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + + if pdfa_version not in [1, 2, 3]: + return {"error": "pdfa_version must be 1, 2, or 3"} + + cmd = [ + "gs", + "-dNOPAUSE", + "-dBATCH", + "-sDEVICE=pdfwrite", + f"-dPDFA={pdfa_version}", + "-dNOOUTERSAVE", + f"-sOutputFile={output_file}" + ] + + if icc_profile: + icc_path = Path(icc_profile) + if icc_path.exists(): + cmd.append(f"-sDefaultRGBProfile={icc_profile}") + + cmd.append(str(input_path)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_file": output_file + } + except subprocess.CalledProcessError as e: + return { + "error": "Ghostscript PDF/A conversion failed", + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def gs_extract_pages( + input_file: str, + output_file: str, + first_page: int, + last_page: int +): + """ + Extract a specific range of pages from a PDF file. + + :param input_file: Path to the source PDF. + :param output_file: Path to the output PDF containing only the range. + :param first_page: The first page to extract. + :param last_page: The last page to extract. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + + if first_page < 1 or last_page < first_page: + return {"error": "Invalid page range specified"} + + cmd = [ + "gs", + "-dNOPAUSE", + "-dBATCH", + "-sDEVICE=pdfwrite", + f"-dFirstPage={first_page}", + f"-dLastPage={last_page}", + f"-sOutputFile={output_file}", + str(input_path) + ] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_file": output_file + } + except subprocess.CalledProcessError as e: + return { + "error": "Ghostscript extraction failed", + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def gs_get_version(): + """ + Retrieve the installed Ghostscript version information. + """ + cmd = ["gs", "--version"] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "version": result.stdout.strip(), + "stdout": result.stdout, + "stderr": result.stderr + } + except (subprocess.CalledProcessError, FileNotFoundError) as e: + return { + "error": "Ghostscript not found or failed to execute", + "details": str(e) + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ghostscript/app/ghostscript_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ghostscript/app/ghostscript_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c5438669ee4cb9b39df031a13aeeb34365f789e0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ghostscript/app/ghostscript_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ghostscript/app/ghostscript_server.py') +SERVER_NAME = 'biosci_ghostscript' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ghostscript/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ghostscript/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ghostscript/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ghostscript/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ghostscript/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..4cefca3541048a7f13f1ae824ad8814ad3c52a80 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ghostscript/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-ghostscript: + build: . + image: mcp-ghostscript:latest + container_name: mcp-ghostscript + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=ghostscript + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ghostscript/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ghostscript/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f653e177d06d22e92498eff1fbb62589dcf65a95 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ghostscript/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - ghostscript + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ghostscript/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ghostscript/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ghostscript/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gimmemotifs/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gimmemotifs/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e14079f468cab67e4e1cfbbdd17ae58ec98f0fca --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gimmemotifs/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install gimmemotifs via conda (e.g., from bioconda) +RUN conda install -c bioconda gimmemotifs -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/gimmemotifs_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/gimmemotifs_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/gimmemotifs_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gimmemotifs/app/gimmemotifs_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gimmemotifs/app/gimmemotifs_server.py new file mode 100644 index 0000000000000000000000000000000000000000..32ab8d337c1fc58fc32c5097ef9fb81dc30479f4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gimmemotifs/app/gimmemotifs_server.py @@ -0,0 +1,965 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict + +# NOTE: The @mcp.tool decorator is a placeholder. +# In a real MCP environment, this would be provided by the MCP framework. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +@mcp.tool() +def gimme_motifs( + inputfile: Path, + outputdir: str, + pfm: Optional[Path] = None, + genome: Optional[str] = None, + background: Optional[List[Path]] = None, + name: Optional[str] = None, + known: bool = False, + denovo: bool = False, + noreport: bool = False, + nogc: bool = False, + tools: Optional[str] = None, + threads: int = 8, + size: int = 200, + fraction: float = 0.1, + max_time: float = 120.0, + cluster: bool = False, + template: Optional[Path] = None, + queue: Optional[str] = None, + job_name: Optional[str] = None, + walltime: Optional[str] = None, + mem: Optional[str] = None, + ppn: Optional[int] = None, +) -> Dict: + """ + Predicts de novo motifs and/or calculates enrichment of known motifs. + + This is the main GimmeMotifs pipeline. It takes a file with genomic regions + and can perform de novo motif discovery and enrichment analysis of known motifs. + + Args: + inputfile: Path to a file with regions (BED, FASTA, etc.). + outputdir: Name of the output directory. + pfm: PFM file with motifs to use. + genome: Genome name or FASTA file. + background: List of background file(s). + name: Name for analysis. + known: Use known motifs for enrichment. + denovo: Predict de novo motifs. + noreport: Don't generate a report. + nogc: Don't use GC% bins for background generation. + tools: Comma-separated string of tools to use (e.g., 'Homer,MEME'). + threads: Number of threads to use. + size: Size of sequences to use for motif prediction. + fraction: Fraction of sequences to use for motif prediction. + max_time: Maximum time in minutes for a single tool to run. + cluster: Submit jobs to a cluster. + template: Cluster template file. + queue: Cluster queue. + job_name: Cluster job name. + walltime: Cluster walltime. + mem: Cluster memory. + ppn: Cluster processors per node. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + if not inputfile.is_file(): + raise FileNotFoundError(f"Input file not found: {inputfile}") + if pfm and not pfm.is_file(): + raise FileNotFoundError(f"PFM file not found: {pfm}") + if background: + for bg_file in background: + if not bg_file.is_file(): + raise FileNotFoundError(f"Background file not found: {bg_file}") + if template and not template.is_file(): + raise FileNotFoundError(f"Cluster template file not found: {template}") + if threads <= 0: + raise ValueError("Number of threads must be positive.") + if not (0 < fraction <= 1.0): + raise ValueError("Fraction must be between 0 and 1.") + if size <= 0: + raise ValueError("Sequence size must be positive.") + if max_time <= 0: + raise ValueError("Max time must be positive.") + + # Command construction + cmd = ["gimme", "motifs", str(inputfile), outputdir] + + if pfm: + cmd.extend(["--pfm", str(pfm)]) + if genome: + cmd.extend(["-g", genome]) + if background: + for bg_file in background: + cmd.extend(["-b", str(bg_file)]) + if name: + cmd.extend(["-n", name]) + if known: + cmd.append("--known") + if denovo: + cmd.append("--denovo") + if noreport: + cmd.append("--noreport") + if nogc: + cmd.append("--nogc") + if tools: + cmd.extend(["-t", tools]) + if threads != 8: + cmd.extend(["-N", str(threads)]) + if size != 200: + cmd.extend(["-s", str(size)]) + if fraction != 0.1: + cmd.extend(["-f", str(fraction)]) + if max_time != 120.0: + cmd.extend(["--max-time", str(max_time)]) + if cluster: + cmd.append("--cluster") + if template: + cmd.extend(["--template", str(template)]) + if queue: + cmd.extend(["--queue", queue]) + if job_name: + cmd.extend(["--job_name", job_name]) + if walltime: + cmd.extend(["--walltime", walltime]) + if mem: + cmd.extend(["--mem", mem]) + if ppn: + cmd.extend(["--ppn", str(ppn)]) + + # Execution + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + output_path = Path(outputdir) + output_files = {"output_directory": str(output_path)} + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "GimmeMotifs motifs command failed", + "return_code": e.returncode, + } + + +@mcp.tool() +def gimme_maelstrom( + expression_file: Path, + peak_files: Path, + outputdir: str, + motiffile: Optional[Path] = None, + genome: Optional[str] = None, + datadir: Optional[Path] = None, + cluster: Optional[str] = None, + known: Optional[Path] = None, + zscore: bool = False, + zscore_threshold: float = 2.0, + filter: Optional[str] = None, + plot: Optional[str] = None, + threads: int = 8, + size: int = 200, + method: str = "bayesianridge", +) -> Dict: + """ + Identifies differential motifs from multiple datasets using expression data. + + Args: + expression_file: File with expression data. + peak_files: Directory with peak files or file with peak file names. + outputdir: Output directory name. + motiffile: Motif file in PFM format. + genome: Genome name or FASTA file. + datadir: Directory to store intermediate data. + cluster: Cluster results based on expression. + known: File with known motif-TF associations. + zscore: Use z-score for motif activity. + zscore_threshold: Z-score threshold for differential motifs. + filter: Filter on number of samples and expression value (e.g., '2,1'). + plot: Comma-separated list of plots to generate. + threads: Number of threads. + size: Size of sequences to scan. + method: Method for activity prediction ('bayesianridge', 'lasso', 'randomforest'). + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + if not expression_file.is_file(): + raise FileNotFoundError(f"Expression file not found: {expression_file}") + if not peak_files.exists(): + raise FileNotFoundError(f"Peak files path not found: {peak_files}") + if motiffile and not motiffile.is_file(): + raise FileNotFoundError(f"Motif file not found: {motiffile}") + if known and not known.is_file(): + raise FileNotFoundError(f"Known associations file not found: {known}") + if threads <= 0: + raise ValueError("Number of threads must be positive.") + if size <= 0: + raise ValueError("Sequence size must be positive.") + valid_methods = ["bayesianridge", "lasso", "randomforest"] + if method not in valid_methods: + raise ValueError(f"Method must be one of {valid_methods}") + if filter: + parts = filter.split(',') + if len(parts) != 2 or not all(p.isdigit() for p in parts): + raise ValueError("Filter must be in the format 'samples,value', e.g., '2,1'") + + # Command construction + cmd = ["gimme", "maelstrom", str(expression_file), str(peak_files), outputdir] + + if motiffile: + cmd.extend(["-m", str(motiffile)]) + if genome: + cmd.extend(["-g", genome]) + if datadir: + cmd.extend(["-d", str(datadir)]) + if cluster: + cmd.extend(["-c", cluster]) + if known: + cmd.extend(["-k", str(known)]) + if zscore: + cmd.append("--zscore") + if zscore_threshold != 2.0: + cmd.extend(["--zscore-threshold", str(zscore_threshold)]) + if filter: + cmd.extend(["-f", filter]) + if plot: + cmd.extend(["-p", plot]) + if threads != 8: + cmd.extend(["-N", str(threads)]) + if size != 200: + cmd.extend(["-s", str(size)]) + if method != "bayesianridge": + cmd.extend(["--method", method]) + + # Execution + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + output_path = Path(outputdir) + output_files = {"output_directory": str(output_path)} + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "GimmeMotifs maelstrom command failed", + "return_code": e.returncode, + } + + +@mcp.tool() +def gimme_scan( + inputfile: Path, + motiffile: Optional[Path] = None, + genome: Optional[str] = None, + outputdir: Optional[Path] = None, + fpr: float = 0.01, + table: bool = False, + bed: bool = False, + scan_size: int = 200, + nreport: int = 1, + cutoff: float = 0.001, + nobackground: bool = False, + threads: int = 8, + zscore: bool = False, + score: bool = False, + pvalue: bool = False, + log_odds: bool = False, + gc: bool = False, + input_format: Optional[str] = None, +) -> Dict: + """ + Scans sequences for motifs and reports matches. + + Args: + inputfile: Input file (FASTA, BED, etc.). + motiffile: Motif file in PFM format. + genome: Genome name or FASTA file. + outputdir: Output directory. If not specified, prints to stdout. + fpr: FPR for scanning. + table: Output in table format. + bed: Output in BED format. + scan_size: Size of sequences to scan. + nreport: Number of matches to report per sequence. + cutoff: P-value cutoff for motif scanning. + nobackground: Do not use background for p-value calculation. + threads: Number of threads. + zscore: Report z-score of match. + score: Report raw score of match. + pvalue: Report p-value of match. + log_odds: Report log-odds score of match. + gc: Use GC% bins for background. + input_format: Specify input format ('fasta', 'bed', 'regions', 'peak'). + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + if not inputfile.is_file(): + raise FileNotFoundError(f"Input file not found: {inputfile}") + if motiffile and not motiffile.is_file(): + raise FileNotFoundError(f"Motif file not found: {motiffile}") + if not (0 < fpr <= 1.0): + raise ValueError("FPR must be between 0 and 1.") + if scan_size <= 0: + raise ValueError("Scan size must be positive.") + if nreport <= 0: + raise ValueError("nreport must be positive.") + if not (0 < cutoff <= 1.0): + raise ValueError("Cutoff must be between 0 and 1.") + if threads <= 0: + raise ValueError("Number of threads must be positive.") + if input_format: + valid_formats = ["fasta", "bed", "regions", "peak"] + if input_format not in valid_formats: + raise ValueError(f"Input format must be one of {valid_formats}") + + # Command construction + cmd = ["gimme", "scan", str(inputfile)] + + if motiffile: + cmd.extend(["-m", str(motiffile)]) + if genome: + cmd.extend(["-g", genome]) + if outputdir: + cmd.extend(["-o", str(outputdir)]) + if fpr != 0.01: + cmd.extend(["-f", str(fpr)]) + if table: + cmd.append("-t") + if bed: + cmd.append("-b") + if scan_size != 200: + cmd.extend(["-s", str(scan_size)]) + if nreport != 1: + cmd.extend(["-n", str(nreport)]) + if cutoff != 0.001: + cmd.extend(["-c", str(cutoff)]) + if nobackground: + cmd.append("--nobackground") + if threads != 8: + cmd.extend(["-N", str(threads)]) + if zscore: + cmd.append("--zscore") + if score: + cmd.append("--score") + if pvalue: + cmd.append("--pvalue") + if log_odds: + cmd.append("--log_odds") + if gc: + cmd.append("--gc") + if input_format: + cmd.extend(["--input_format", input_format]) + + # Execution + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + output_files = {} + if outputdir: + output_files["output_directory"] = str(outputdir) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "GimmeMotifs scan command failed", + "return_code": e.returncode, + } + + +@mcp.tool() +def gimme_background( + inputfile: Path, + outputfile: Path, + format: str = "gc", + kmer: int = 1, + number: int = 10000, + length: int = 200, + genome: Optional[str] = None, +) -> Dict: + """ + Generates a background file from a FASTA file or a genome. + + Args: + inputfile: Input file (FASTA). + outputfile: Output file. + format: Background format ('fasta', 'gc', 'markov'). + kmer: K-mer size for Markov model. + number: Number of sequences to generate. + length: Length of sequences to generate. + genome: Genome name or FASTA file. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + if not inputfile.is_file(): + raise FileNotFoundError(f"Input file not found: {inputfile}") + valid_formats = ["fasta", "gc", "markov"] + if format not in valid_formats: + raise ValueError(f"Format must be one of {valid_formats}") + if kmer <= 0: + raise ValueError("K-mer size must be positive.") + if number <= 0: + raise ValueError("Number of sequences must be positive.") + if length <= 0: + raise ValueError("Length of sequences must be positive.") + + # Command construction + cmd = ["gimme", "background", "-i", str(inputfile), "-o", str(outputfile)] + + if format != "gc": + cmd.extend(["-f", format]) + if kmer != 1: + cmd.extend(["-k", str(kmer)]) + if number != 10000: + cmd.extend(["-n", str(number)]) + if length != 200: + cmd.extend(["-l", str(length)]) + if genome: + cmd.extend(["-g", genome]) + + # Execution + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + output_files = {"background_file": str(outputfile)} + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "GimmeMotifs background command failed", + "return_code": e.returncode, + } + + +@mcp.tool() +def gimme_logo( + inputfile: Path, + outputfile: Optional[Path] = None, + ids: Optional[str] = None, + scale_width: bool = False, + format: str = "png", + title: bool = False, +) -> Dict: + """ + Creates a sequence logo from a motif PFM file. + + Args: + inputfile: Input file (PFM format). + outputfile: Output file name. + ids: Comma-separated list of motif IDs to plot. + scale_width: Scale width by information content. + format: Output format ('png', 'eps', 'pdf', 'svg'). + title: Add title to logo. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + if not inputfile.is_file(): + raise FileNotFoundError(f"Input file not found: {inputfile}") + valid_formats = ["png", "eps", "pdf", "svg"] + if format not in valid_formats: + raise ValueError(f"Format must be one of {valid_formats}") + + # Command construction + cmd = ["gimme", "logo", str(inputfile)] + + if outputfile: + cmd.extend(["-o", str(outputfile)]) + if ids: + cmd.extend(["-i", ids]) + if scale_width: + cmd.append("--scale_width") + if format != "png": + cmd.extend(["--format", format]) + if title: + cmd.append("--title") + + # Execution + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + output_files = {} + if outputfile: + output_files["logo_file"] = str(outputfile) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "GimmeMotifs logo command failed", + "return_code": e.returncode, + } + + +@mcp.tool() +def gimme_match( + inputfile: Path, + database: Optional[str] = None, + threshold: float = 0.9, + best: bool = False, + nreport: int = 5, +) -> Dict: + """ + Finds the best matching motifs from a database for a given set of motifs. + + Args: + inputfile: Input file (PFM format). + database: Motif database to use. + threshold: Similarity score threshold. + best: Report only the best match. + nreport: Number of matches to report. + + Returns: + A dictionary containing the command executed, stdout, and stderr. + """ + # Input validation + if not inputfile.is_file(): + raise FileNotFoundError(f"Input file not found: {inputfile}") + if not (0 <= threshold <= 1.0): + raise ValueError("Threshold must be between 0 and 1.") + if nreport <= 0: + raise ValueError("nreport must be positive.") + + # Command construction + cmd = ["gimme", "match", str(inputfile)] + + if database: + cmd.extend(["-d", database]) + if threshold != 0.9: + cmd.extend(["-t", str(threshold)]) + if best: + cmd.append("-b") + if nreport != 5: + cmd.extend(["-n", str(nreport)]) + + # Execution + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {}, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "GimmeMotifs match command failed", + "return_code": e.returncode, + } + + +@mcp.tool() +def gimme_cluster( + inputfile: Path, + outputdir: str, + threshold: float = 0.95, + use_strand: bool = False, + separate: bool = False, +) -> Dict: + """ + Clusters motifs based on similarity. + + Args: + inputfile: Input file (PFM format). + outputdir: Output directory name. + threshold: Similarity score threshold for clustering. + use_strand: Use strand information for clustering. + separate: Create separate motif files for each cluster. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + if not inputfile.is_file(): + raise FileNotFoundError(f"Input file not found: {inputfile}") + if not (0 <= threshold <= 1.0): + raise ValueError("Threshold must be between 0 and 1.") + + # Command construction + cmd = ["gimme", "cluster", str(inputfile), outputdir] + + if threshold != 0.95: + cmd.extend(["-t", str(threshold)]) + if use_strand: + cmd.append("-u") + if separate: + cmd.append("-s") + + # Execution + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + output_path = Path(outputdir) + output_files = {"output_directory": str(output_path)} + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "GimmeMotifs cluster command failed", + "return_code": e.returncode, + } + + +@mcp.tool() +def gimme_threshold( + inputfile: Path, + fpr: float = 0.01, + genome: Optional[str] = None, + background: Optional[Path] = None, + ids: Optional[str] = None, + outputfile: Optional[Path] = None, +) -> Dict: + """ + Determines the optimal score threshold for a motif based on a specified FPR. + + Args: + inputfile: Input file (PFM format). + fpr: False Positive Rate. + genome: Genome name or FASTA file. + background: Background file (FASTA). + ids: Comma-separated list of motif IDs. + outputfile: Output file name. If not specified, prints to stdout. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + if not inputfile.is_file(): + raise FileNotFoundError(f"Input file not found: {inputfile}") + if not (0 < fpr <= 1.0): + raise ValueError("FPR must be between 0 and 1.") + if background and not background.is_file(): + raise FileNotFoundError(f"Background file not found: {background}") + + # Command construction + cmd = ["gimme", "threshold", str(inputfile)] + + if fpr != 0.01: + cmd.extend(["-f", str(fpr)]) + if genome: + cmd.extend(["-g", genome]) + if background: + cmd.extend(["-b", str(background)]) + if ids: + cmd.extend(["-i", ids]) + if outputfile: + cmd.extend(["-o", str(outputfile)]) + + # Execution + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + output_files = {} + if outputfile: + output_files["threshold_file"] = str(outputfile) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "GimmeMotifs threshold command failed", + "return_code": e.returncode, + } + + +@mcp.tool() +def gimme_location( + inputfile: Path, + motiffile: Path, + genome: Optional[str] = None, + outputfile: Optional[Path] = None, + width: int = 200, + bins: int = 10, + separate: bool = False, + format: str = "png", + threshold: float = 0.001, +) -> Dict: + """ + Plots the distribution of motifs relative to the center of sequences. + + Args: + inputfile: Input file (FASTA or BED). + motiffile: Motif file in PFM format. + genome: Genome name or FASTA file. + outputfile: Output file name (image format). + width: Width of the window to scan. + bins: Number of bins for the histogram. + separate: Plot each motif separately. + format: Output format ('png', 'eps', 'pdf', 'svg'). + threshold: P-value threshold for scanning. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + if not inputfile.is_file(): + raise FileNotFoundError(f"Input file not found: {inputfile}") + if not motiffile.is_file(): + raise FileNotFoundError(f"Motif file not found: {motiffile}") + if width <= 0: + raise ValueError("Width must be positive.") + if bins <= 0: + raise ValueError("Number of bins must be positive.") + valid_formats = ["png", "eps", "pdf", "svg"] + if format not in valid_formats: + raise ValueError(f"Format must be one of {valid_formats}") + if not (0 < threshold <= 1.0): + raise ValueError("Threshold must be between 0 and 1.") + + # Command construction + cmd = ["gimme", "location", str(inputfile), "-m", str(motiffile)] + + if genome: + cmd.extend(["-g", genome]) + if outputfile: + cmd.extend(["-o", str(outputfile)]) + if width != 200: + cmd.extend(["-w", str(width)]) + if bins != 10: + cmd.extend(["-b", str(bins)]) + if separate: + cmd.append("-s") + if format != "png": + cmd.extend(["-f", format]) + if threshold != 0.001: + cmd.extend(["-t", str(threshold)]) + + # Execution + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + output_files = {} + if outputfile: + output_files["location_plot"] = str(outputfile) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "GimmeMotifs location command failed", + "return_code": e.returncode, + } + + +@mcp.tool() +def gimme_diff( + fg_file: Path, + bg_file: Path, + motiffile: Path, + genome: Optional[str] = None, + outputdir: Optional[Path] = None, + enrichment: bool = False, + denovo: bool = False, + scan: bool = False, + plot: bool = False, + threads: int = 8, +) -> Dict: + """ + Finds differential motifs between a foreground and a background set of sequences. + + Args: + fg_file: Foreground file (FASTA or BED). + bg_file: Background file (FASTA or BED). + motiffile: Motif file in PFM format. + genome: Genome name or FASTA file. + outputdir: Output directory. + enrichment: Calculate enrichment statistics. + denovo: Predict de novo motifs. + scan: Scan for known motifs. + plot: Generate plots. + threads: Number of threads. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + if not fg_file.is_file(): + raise FileNotFoundError(f"Foreground file not found: {fg_file}") + if not bg_file.is_file(): + raise FileNotFoundError(f"Background file not found: {bg_file}") + if not motiffile.is_file(): + raise FileNotFoundError(f"Motif file not found: {motiffile}") + if threads <= 0: + raise ValueError("Number of threads must be positive.") + + # Command construction + cmd = ["gimme", "diff", str(fg_file), str(bg_file), "-m", str(motiffile)] + + if genome: + cmd.extend(["-g", genome]) + if outputdir: + cmd.extend(["-o", str(outputdir)]) + if enrichment: + cmd.append("-e") + if denovo: + cmd.append("-d") + if scan: + cmd.append("-s") + if plot: + cmd.append("-p") + if threads != 8: + cmd.extend(["-N", str(threads)]) + + # Execution + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + output_files = {} + if outputdir: + output_files["output_directory"] = str(outputdir) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "GimmeMotifs diff command failed", + "return_code": e.returncode, + } + + +@mcp.tool() +def gimme_motif2factors( + database: str, + outputfile: Optional[Path] = None, + format: str = "txt", + direct: bool = False, + indirect: bool = False, +) -> Dict: + """ + Links motifs to transcription factors using a specified database. + + Args: + database: Motif database name. + outputfile: Output file name. If not specified, prints to stdout. + format: Output format ('txt', 'md', 'html'). + direct: Only include direct associations. + indirect: Only include indirect associations. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + valid_formats = ["txt", "md", "html"] + if format not in valid_formats: + raise ValueError(f"Format must be one of {valid_formats}") + if direct and indirect: + raise ValueError("Cannot specify both --direct and --indirect.") + + # Command construction + cmd = ["gimme", "motif2factors", database] + + if outputfile: + cmd.extend(["-o", str(outputfile)]) + if format != "txt": + cmd.extend(["-f", format]) + if direct: + cmd.append("-d") + if indirect: + cmd.append("-i") + + # Execution + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True, + ) + output_files = {} + if outputfile: + output_files["factor_file"] = str(outputfile) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "GimmeMotifs motif2factors command failed", + "return_code": e.returncode, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gimmemotifs/app/gimmemotifs_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gimmemotifs/app/gimmemotifs_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ec378702ceb332a95a0431fc1da9910d9668b71f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gimmemotifs/app/gimmemotifs_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gimmemotifs/app/gimmemotifs_server.py') +SERVER_NAME = 'biosci_gimmemotifs' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gimmemotifs/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gimmemotifs/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gimmemotifs/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gimmemotifs/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gimmemotifs/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..464626c82013c92c90ad85cff785bc2d583e341d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gimmemotifs/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-gimmemotifs: + build: . + image: mcp-gimmemotifs:latest + container_name: mcp-gimmemotifs + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=gimmemotifs + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gimmemotifs/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gimmemotifs/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a1de281707add5dfebd95e69694a1285eecd321c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gimmemotifs/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - gimmemotifs + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gimmemotifs/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gimmemotifs/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gimmemotifs/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_glimmerhmm/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_glimmerhmm/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..409bc1d1f7ceb71301e2b87db0c89c2598a3610d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_glimmerhmm/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install glimmerhmm via conda (e.g., from bioconda) +RUN conda install -c bioconda glimmerhmm -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/glimmerhmm_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/glimmerhmm_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/glimmerhmm_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_glimmerhmm/app/glimmerhmm_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_glimmerhmm/app/glimmerhmm_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7370431f0aba854e1d5be535ad234662f9c2a28b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_glimmerhmm/app/glimmerhmm_server.py @@ -0,0 +1,170 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# MCP decorator is assumed to be available in the execution environment. +# No import is necessary for the final code. +# from mcp import tool as mcp_tool + +@mcp.tool() +def glimmerhmm( + sequence_file: Path, + model_dir: Path, + output_file: Optional[Path] = None, + max_predictions: Optional[int] = None, + both_strands: bool = False, + verbose: bool = False, + intergenic_prob: float = 0.9, + detail_cols: int = 50, + first_pass_only: bool = False, + intron_submodel: Optional[Path] = None, + utr_submodel: Optional[Path] = None, + start_codon_submodel: Optional[Path] = None, + stop_codon_submodel: Optional[Path] = None, + exon_submodel: Optional[Path] = None, + use_rbs_scores: bool = False, + rbs_pwm: Optional[Path] = None, + branch_point_pwm: Optional[Path] = None, + acceptor_splice_pwm: Optional[Path] = None, + donor_splice_pwm: Optional[Path] = None, + start_trna_pwm: Optional[Path] = None, + stop_trna_pwm: Optional[Path] = None, + use_length_dist: bool = False, + initial_exon_len_dist: Optional[Path] = None, + internal_exon_len_dist: Optional[Path] = None, + final_exon_len_dist: Optional[Path] = None, + single_exon_len_dist: Optional[Path] = None, +): + """ + Predicts genes in eukaryotic DNA sequences using a Generalized Hidden Markov Model (GHMM). + + GlimmerHMM is an ab initio gene finder. It takes a FASTA-formatted sequence file + and a trained model directory to produce gene predictions. + + Args: + sequence_file: The file of sequences to be processed, in FASTA format. + model_dir: The directory containing the model files for a particular organism. + output_file: Print output to this file instead of stdout. The output is in 6-column GFF-like format. + max_predictions: Output at most N predictions. + both_strands: Predict genes on both strands. Default is forward strand only. + verbose: Print progress information to stderr. + intergenic_prob: Probability of being in an intergenic region. Must be between 0.0 and 1.0. + detail_cols: The number of columns to use for printing the sequence in the .detail file. + first_pass_only: Perform only the first-pass Viterbi algorithm, not the second pass. + intron_submodel: File for the intron submodel. + utr_submodel: File for the UTR submodel. + start_codon_submodel: File for the start-codon submodel. + stop_codon_submodel: File for the stop-codon submodel. + exon_submodel: File for the exon submodel. + use_rbs_scores: Use ribosome binding site scores. + rbs_pwm: File containing the ribosome binding site PWM. + branch_point_pwm: File containing the branch point PWM. + acceptor_splice_pwm: File containing the acceptor splice site PWM. + donor_splice_pwm: File containing the donor splice site PWM. + start_trna_pwm: File containing the start tRNA PWM. + stop_trna_pwm: File containing the stop tRNA PWM. + use_length_dist: Use length distributions. + initial_exon_len_dist: File for the initial exon length distribution. + internal_exon_len_dist: File for the internal exon length distribution. + final_exon_len_dist: File for the final exon length distribution. + single_exon_len_dist: File for the single exon length distribution. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not sequence_file.is_file(): + raise FileNotFoundError(f"Input sequence file not found: {sequence_file}") + if not model_dir.is_dir(): + raise NotADirectoryError(f"Model directory not found or is not a directory: {model_dir}") + + optional_files = { + "intron_submodel": intron_submodel, "utr_submodel": utr_submodel, + "start_codon_submodel": start_codon_submodel, "stop_codon_submodel": stop_codon_submodel, + "exon_submodel": exon_submodel, "rbs_pwm": rbs_pwm, "branch_point_pwm": branch_point_pwm, + "acceptor_splice_pwm": acceptor_splice_pwm, "donor_splice_pwm": donor_splice_pwm, + "start_trna_pwm": start_trna_pwm, "stop_trna_pwm": stop_trna_pwm, + "initial_exon_len_dist": initial_exon_len_dist, "internal_exon_len_dist": internal_exon_len_dist, + "final_exon_len_dist": final_exon_len_dist, "single_exon_len_dist": single_exon_len_dist + } + for name, path in optional_files.items(): + if path and not path.is_file(): + raise FileNotFoundError(f"Optional file for '{name}' not found: {path}") + + if not (0.0 <= intergenic_prob <= 1.0): + raise ValueError("intergenic_prob must be between 0.0 and 1.0.") + if detail_cols <= 0: + raise ValueError("detail_cols must be a positive integer.") + if max_predictions is not None and max_predictions <= 0: + raise ValueError("max_predictions must be a positive integer.") + + # --- Command Construction --- + cmd = ["glimmerhmm", str(sequence_file), str(model_dir)] + + if output_file: + cmd.extend(["-o", str(output_file)]) + if max_predictions is not None: + cmd.extend(["-n", str(max_predictions)]) + if both_strands: + cmd.append("-g") + if verbose: + cmd.append("-v") + if intergenic_prob != 0.9: + cmd.extend(["-p", str(intergenic_prob)]) + if detail_cols != 50: + cmd.extend(["-c", str(detail_cols)]) + if first_pass_only: + cmd.append("-f") + if use_rbs_scores: + cmd.append("-r") + if use_length_dist: + cmd.append("-l") + + # Add optional file paths to command + file_flags = { + "-i": intron_submodel, "-u": utr_submodel, "-s": start_codon_submodel, + "-t": stop_codon_submodel, "-e": exon_submodel, "-z": rbs_pwm, + "-b": branch_point_pwm, "-a": acceptor_splice_pwm, "-m": donor_splice_pwm, + "-w": start_trna_pwm, "-y": stop_trna_pwm, "-q": initial_exon_len_dist, + "-j": internal_exon_len_dist, "-k": final_exon_len_dist, "-x": single_exon_len_dist + } + for flag, path in file_flags.items(): + if path: + cmd.extend([flag, str(path)]) + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except subprocess.CalledProcessError as e: + # The tool failed, return structured error information + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + "output_files": [] + } + + # --- Collect Output Files --- + output_files_list = [] + if output_file: + if output_file.exists() and output_file.stat().st_size > 0: + output_files_list.append(str(output_file)) + # GlimmerHMM may create a '.detail' file alongside the main output + detail_file = output_file.with_suffix(".detail") + if detail_file.exists(): + output_files_list.append(str(detail_file)) + + # --- Return Structured Result --- + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files_list + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_glimmerhmm/app/glimmerhmm_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_glimmerhmm/app/glimmerhmm_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2f7a68b9700f8f41c2bf2831029d7d5c4083e05c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_glimmerhmm/app/glimmerhmm_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_glimmerhmm/app/glimmerhmm_server.py') +SERVER_NAME = 'biosci_glimmerhmm' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_glimmerhmm/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_glimmerhmm/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_glimmerhmm/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_glimmerhmm/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_glimmerhmm/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..a0374882e86925f6cda389e1041719dd629bff09 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_glimmerhmm/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-glimmerhmm: + build: . + image: mcp-glimmerhmm:latest + container_name: mcp-glimmerhmm + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=glimmerhmm + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_glimmerhmm/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_glimmerhmm/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6b4680a89b3e56dfde526393cd328160eeb0b10f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_glimmerhmm/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - glimmerhmm + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_glimmerhmm/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_glimmerhmm/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_glimmerhmm/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gmap/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gmap/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a270776cfc98857abc53afe0c5f9975e28426f22 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gmap/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install gmap via conda (e.g., from bioconda) +RUN conda install -c bioconda gmap -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/gmap_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/gmap_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/gmap_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gmap/app/gmap_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gmap/app/gmap_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3be95996dfd46ec7ed10955b6147dd449737d45d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gmap/app/gmap_server.py @@ -0,0 +1,309 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Union + +@mcp.tool() +def gmap_build( + db_name: str, + fasta_files: List[str], + dest_dir: Optional[str] = None, + kmer: int = 15, + sampling: int = 3, +): + """ + Builds a genome database for GMAP and GSNAP. + + Args: + db_name: Name of the genome database to create. + fasta_files: List of paths to FASTA files containing the genome sequences. + dest_dir: Destination directory for the genome database. If not provided, uses default. + kmer: K-mer size for the genomic index (default 15). + sampling: Sampling interval for the genomic index (default 3). + """ + # Input validation + if not fasta_files: + return {"error": "At least one FASTA file must be provided."} + + for f in fasta_files: + if not Path(f).exists(): + return {"error": f"FASTA file not found: {f}"} + + cmd = ["gmap_build", "-d", db_name] + + if dest_dir: + dest_path = Path(dest_dir) + dest_path.mkdir(parents=True, exist_ok=True) + cmd.extend(["-D", str(dest_path)]) + + cmd.extend(["-k", str(kmer)]) + cmd.extend(["-s", str(sampling)]) + cmd.extend(fasta_files) + + try: + process = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def gmap( + db_name: str, + query_file: str, + genome_dir: Optional[str] = None, + nthreads: int = 1, + output_format: str = "samse", + align_fraction: float = 1.0, + npaths: int = 5, + min_intronlength: int = 20, + max_intronlength_middle: int = 500000, + max_intronlength_ends: int = 10000, +): + """ + Genomic mapping and alignment program for mRNA and EST sequences. + + Args: + db_name: Genome database name. + query_file: Path to the mRNA/EST sequence file (FASTA/FASTQ). + genome_dir: Directory where the genome database is located. + nthreads: Number of worker threads (default 1). + output_format: Output format (samse, sampe, gff3_gene, gff3_match_cdna, gff3_match_est, etc.). + align_fraction: Align only a fraction of the given reads, selected randomly (0.0 to 1.0). + npaths: Maximum number of paths to show (default 5). + min_intronlength: Minimum intron length (default 20). + max_intronlength_middle: Max intron length for internal introns (default 500000). + max_intronlength_ends: Max intron length for end introns (default 10000). + """ + if not Path(query_file).exists(): + return {"error": f"Query file not found: {query_file}"} + + if not (0.0 <= align_fraction <= 1.0): + return {"error": "align_fraction must be between 0.0 and 1.0"} + + cmd = ["gmap", "-d", db_name, "-t", str(nthreads), "-f", output_format] + + if genome_dir: + cmd.extend(["-D", genome_dir]) + + cmd.extend(["--align-fraction", str(align_fraction)]) + cmd.extend(["-n", str(npaths)]) + cmd.extend(["--min-intronlength", str(min_intronlength)]) + cmd.extend(["--max-intronlength-middle", str(max_intronlength_middle)]) + cmd.extend(["--max-intronlength-ends", str(max_intronlength_ends)]) + cmd.append(query_file) + + try: + process = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def gsnap( + db_name: str, + query_file1: str, + query_file2: Optional[str] = None, + genome_dir: Optional[str] = None, + nthreads: int = 1, + output_format: str = "sam", + two_pass: bool = False, + max_insertions: int = 3, + max_deletions: int = 3, + min_coverage: float = 0.5, + align_fraction: float = 1.0, + batch: int = 2, +): + """ + Genomic Short-read Nucleotide Alignment Program (GSNAP). + + Args: + db_name: Genome database name. + query_file1: Path to the first FASTQ/FASTA file (or single-end file). + query_file2: Path to the second FASTQ/FASTA file for paired-end reads. + genome_dir: Directory where the genome database is located. + nthreads: Number of worker threads (default 1). + output_format: Output format (sam, etc.). + two_pass: Use two-pass mode to learn splice sites and indels (default False). + max_insertions: Maximum number of insertions allowed (default 3). + max_deletions: Maximum number of deletions allowed (default 3). + min_coverage: Minimum coverage required for an alignment (default 0.5). + align_fraction: Align only a fraction of the given reads (0.0 to 1.0). + batch: Batch mode (0=offsets, 1=offsets+positions, 2=offsets+positions+genome, default 2). + """ + if not Path(query_file1).exists(): + return {"error": f"Query file 1 not found: {query_file1}"} + + cmd = ["gsnap", "-d", db_name, "-t", str(nthreads), "-A", output_format] + + if genome_dir: + cmd.extend(["-D", genome_dir]) + + if two_pass: + cmd.append("--two-pass") + + cmd.extend(["--max-insertions", str(max_insertions)]) + cmd.extend(["--max-deletions", str(max_deletions)]) + cmd.extend(["--min-coverage", str(min_coverage)]) + cmd.extend(["--align-fraction", str(align_fraction)]) + cmd.extend(["-B", str(batch)]) + + cmd.append(query_file1) + if query_file2: + if not Path(query_file2).exists(): + return {"error": f"Query file 2 not found: {query_file2}"} + cmd.append(query_file2) + + try: + process = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def gtf_exons(gtf_file: str): + """ + Extracts exons from a GTF file for use with GMAP/GSNAP. + + Args: + gtf_file: Path to the input GTF file. + """ + if not Path(gtf_file).exists(): + return {"error": f"GTF file not found: {gtf_file}"} + + cmd = ["gtf_exons", gtf_file] + + try: + process = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def gff3_exons(gff3_file: str): + """ + Extracts exons from a GFF3 file for use with GMAP/GSNAP. + + Args: + gff3_file: Path to the input GFF3 file. + """ + if not Path(gff3_file).exists(): + return {"error": f"GFF3 file not found: {gff3_file}"} + + cmd = ["gff3_exons", gff3_file] + + try: + process = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def gff3_genes(gff3_file: str): + """ + Extracts genes from a GFF3 file for use with GMAP/GSNAP. + Works on NCBI and Ensembl GFF3 files. + + Args: + gff3_file: Path to the input GFF3 file. + """ + if not Path(gff3_file).exists(): + return {"error": f"GFF3 file not found: {gff3_file}"} + + cmd = ["gff3_genes", gff3_file] + + try: + process = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def iit_store(input_file: str, output_file: str): + """ + Creates an Interval Index Tree (IIT) file from a text file. + Used for handling SNPs and splices in GMAP/GSNAP. + + Args: + input_file: Path to the input text file (e.g., splices or SNPs). + output_file: Path to the output .iit file. + """ + if not Path(input_file).exists(): + return {"error": f"Input file not found: {input_file}"} + + cmd = ["iit_store", "-o", output_file, input_file] + + try: + process = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [output_file], + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gmap/app/gmap_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gmap/app/gmap_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..71a106a1ccc76e1d3f24d9b7e01d268fac46213f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gmap/app/gmap_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gmap/app/gmap_server.py') +SERVER_NAME = 'biosci_gmap' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gmap/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gmap/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gmap/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gmap/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gmap/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..cd781380c776408bd37ea85418ca5c691f5f2fd8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gmap/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-gmap: + build: . + image: mcp-gmap:latest + container_name: mcp-gmap + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=gmap + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gmap/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gmap/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e3b797d385792b1faf5aa43915e9e7a5352a681f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gmap/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - gmap + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gmap/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gmap/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gmap/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gneiss/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gneiss/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..645610c98d6e90ef28cfd2502d1cbffb49f64d27 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gneiss/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install gneiss via conda (e.g., from bioconda) +RUN conda install -c bioconda gneiss -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/gneiss_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/gneiss_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/gneiss_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gneiss/app/gneiss_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gneiss/app/gneiss_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fa32a49f4111d2db80e9d58dc7d8c2bbf94d5ae8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gneiss/app/gneiss_server.py @@ -0,0 +1,327 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, List + +# It is assumed that 'mcp' is a pre-defined decorator. +# For standalone testing, you could use a mock decorator: +# +# class mcp: +# @staticmethod +# def tool(): +# def decorator(func): +# return func +# return decorator + +logging.basicConfig(level=logging.INFO) + +@mcp.tool() +def correlation_clustering( + in_biom: Path, + output_tree: Path, + correlation_method: str = 'spearman', + clustering_method: str = 'ward' +) -> dict: + """ + Performs hierarchical clustering on features using their correlation. + + This is useful for creating a hierarchy of features based on their co-occurrence + patterns across samples. + """ + if not in_biom.exists(): + raise FileNotFoundError(f"Input biom table not found: {in_biom}") + + # Ensure output directory exists + output_tree.parent.mkdir(parents=True, exist_ok=True) + + cmd = [ + "gneiss", "correlation-clustering", + "--in-biom", str(in_biom), + "--output-tree", str(output_tree), + "--correlation-method", correlation_method, + "--clustering-method", clustering_method + ] + + command_str = " ".join(cmd) + logging.info(f"Executing command: {command_str}") + + 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": [str(output_tree)] + } + except subprocess.CalledProcessError as e: + logging.error(f"Gneiss correlation-clustering failed: {e.stderr}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + +@mcp.tool() +def dendrogram_heatmap( + in_biom: Path, + in_tree: Path, + in_meta: Path, + category: str, + output_viz: Path, + vmin: Optional[float] = None, + vmax: Optional[float] = None, + cmap: str = 'YlGnBu' +) -> dict: + """ + Builds a heatmap visualization of a biom table, ordered by a dendrogram. + + This tool is useful for visualizing the relationship between feature balances + and sample metadata categories. + """ + for input_file in [in_biom, in_tree, in_meta]: + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + if not category: + raise ValueError("Metadata category must be a non-empty string.") + + # Ensure output directory exists + output_viz.parent.mkdir(parents=True, exist_ok=True) + + cmd = [ + "gneiss", "dendrogram-heatmap", + "--in-biom", str(in_biom), + "--in-tree", str(in_tree), + "--in-meta", str(in_meta), + "--category", category, + "--output-viz", str(output_viz), + "--cmap", cmap + ] + + if vmin is not None: + cmd.extend(["--vmin", str(vmin)]) + if vmax is not None: + cmd.extend(["--vmax", str(vmax)]) + + command_str = " ".join(cmd) + logging.info(f"Executing command: {command_str}") + + 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": [str(output_viz)] + } + except subprocess.CalledProcessError as e: + logging.error(f"Gneiss dendrogram-heatmap failed: {e.stderr}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + +@mcp.tool() +def ilr_hierarchical( + in_biom: Path, + in_tree: Path, + output_biom: Path +) -> dict: + """ + Performs isometric log-ratio (ILR) transformation on a table using a hierarchical tree. + + This transforms compositional data into a real-valued space of balances, + which is suitable for standard statistical analyses. + """ + for input_file in [in_biom, in_tree]: + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + # Ensure output directory exists + output_biom.parent.mkdir(parents=True, exist_ok=True) + + cmd = [ + "gneiss", "ilr-hierarchical", + "--in-biom", str(in_biom), + "--in-tree", str(in_tree), + "--output-biom", str(output_biom) + ] + + command_str = " ".join(cmd) + logging.info(f"Executing command: {command_str}") + + 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": [str(output_biom)] + } + except subprocess.CalledProcessError as e: + logging.error(f"Gneiss ilr-hierarchical failed: {e.stderr}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + +@mcp.tool() +def ilr_phylogenetic( + in_biom: Path, + in_tree: Path, + output_biom: Path +) -> dict: + """ + Performs isometric log-ratio (ILR) transformation on a table using a phylogenetic tree. + + This is similar to ilr-hierarchical but specifically uses a phylogenetic tree + to define the balances, incorporating evolutionary relationships. + """ + for input_file in [in_biom, in_tree]: + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + # Ensure output directory exists + output_biom.parent.mkdir(parents=True, exist_ok=True) + + cmd = [ + "gneiss", "ilr-phylogenetic", + "--in-biom", str(in_biom), + "--in-tree", str(in_tree), + "--output-biom", str(output_biom) + ] + + command_str = " ".join(cmd) + logging.info(f"Executing command: {command_str}") + + 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": [str(output_biom)] + } + except subprocess.CalledProcessError as e: + logging.error(f"Gneiss ilr-phylogenetic failed: {e.stderr}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + +@mcp.tool() +def lme_regression( + in_biom: Path, + in_meta: Path, + formula: str, + groups: str, + output_dir: Path +) -> dict: + """ + Performs Linear Mixed Effects (LME) regression on balances. + + This models the relationship between balances and metadata variables while + accounting for random effects, such as repeated measures from subjects. + """ + for input_file in [in_biom, in_meta]: + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + if not formula: + raise ValueError("Formula must be a non-empty string.") + if not groups: + raise ValueError("Groups must be a non-empty string.") + + # Ensure output directory exists + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "gneiss", "lme-regression", + "--in-biom", str(in_biom), + "--in-meta", str(in_meta), + "--formula", formula, + "--groups", groups, + "--output-dir", str(output_dir) + ] + + command_str = " ".join(cmd) + logging.info(f"Executing command: {command_str}") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + # Gneiss regression outputs multiple files, so we return the directory + output_files = [str(p) for p in output_dir.glob('*')] + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + logging.error(f"Gneiss lme-regression failed: {e.stderr}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + +@mcp.tool() +def ols_regression( + in_biom: Path, + in_meta: Path, + formula: str, + output_dir: Path +) -> dict: + """ + Performs Ordinary Least Squares (OLS) regression on balances. + + This models the linear relationship between balances (response variables) + and metadata variables (predictors). + """ + for input_file in [in_biom, in_meta]: + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + if not formula: + raise ValueError("Formula must be a non-empty string.") + + # Ensure output directory exists + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "gneiss", "ols-regression", + "--in-biom", str(in_biom), + "--in-meta", str(in_meta), + "--formula", formula, + "--output-dir", str(output_dir) + ] + + command_str = " ".join(cmd) + logging.info(f"Executing command: {command_str}") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + # Gneiss regression outputs multiple files, so we return the directory + output_files = [str(p) for p in output_dir.glob('*')] + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + logging.error(f"Gneiss ols-regression failed: {e.stderr}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gneiss/app/gneiss_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gneiss/app/gneiss_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..aa11ed03108cd55d07cd87cffca64525d35f4fce --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gneiss/app/gneiss_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gneiss/app/gneiss_server.py') +SERVER_NAME = 'biosci_gneiss' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gneiss/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gneiss/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gneiss/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gneiss/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gneiss/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..8188b23a6e770bcf257b16fd7c0ac7d7841a2500 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gneiss/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-gneiss: + build: . + image: mcp-gneiss:latest + container_name: mcp-gneiss + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=gneiss + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gneiss/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gneiss/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..61580b9529e067472a95fde20dfcd5e18fbe7fff --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gneiss/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - gneiss + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gneiss/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gneiss/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gneiss/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gnuplot/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gnuplot/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8578476e4f9e589340baf494af0a46f01c3e52c8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gnuplot/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install gnuplot via conda (e.g., from bioconda) +RUN conda install -c bioconda gnuplot -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/gnuplot_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/gnuplot_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/gnuplot_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gnuplot/app/gnuplot_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gnuplot/app/gnuplot_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1f2c6ed1add5da2845296c129a4fc751bc6a6206 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gnuplot/app/gnuplot_server.py @@ -0,0 +1,132 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Dict, Any + +# @mcp.tool is a decorator placeholder. +# In a real MCP environment, this would be provided by the MCP framework. +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def run_gnuplot( + script: str, + persist: bool = False, + default_settings: bool = False, + expected_output: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Executes a gnuplot script and captures the output. + + Gnuplot is a portable command-line driven graphing utility. This tool + allows you to run a gnuplot script and capture any generated files. + + Args: + script (str): The gnuplot script content to execute. This script should + contain commands like 'set terminal' and 'set output' to + generate a file. + persist (bool): Corresponds to the -p/--persist flag. In some terminal + environments, this may keep plot windows open after gnuplot exits. + Defaults to False. + default_settings (bool): Corresponds to the -d/--default flag. Instructs gnuplot + to use its default settings. Defaults to False. + expected_output (Optional[Path]): The path to the file that the gnuplot script is + expected to create. This function will check for its + existence after the script runs and include it in the + output if found. Note: You must include a corresponding + 'set output \"\"' command in your script content. + Defaults to None. + + Returns: + Dict[str, Any]: A dictionary containing the execution details, including the + command executed, stdout, stderr, return code, and a list of + output file paths. + """ + # 1. Input Validation + if not script or not script.strip(): + raise ValueError("The 'script' content cannot be empty.") + + if expected_output: + # Ensure the parent directory for the output file exists to prevent errors + try: + expected_output.parent.mkdir(parents=True, exist_ok=True) + except Exception as e: + raise IOError(f"Failed to create parent directory for expected_output: {e}") from e + + # 2. File Handling: gnuplot runs on files, so write the script string to a temp file. + # Using a try-finally block to ensure the temp file is always cleaned up. + script_path = None + try: + with tempfile.NamedTemporaryFile( + mode="w", delete=False, suffix=".gp", encoding="utf-8" + ) as tmp_script_file: + script_path = Path(tmp_script_file.name) + tmp_script_file.write(script) + # The file is automatically flushed and closed upon exiting the 'with' block. + + # 3. Command Construction + cmd = ["gnuplot"] + if persist: + cmd.append("--persist") + if default_settings: + cmd.append("--default") + + cmd.append(str(script_path)) + command_executed = " ".join(cmd) + + # 4. Subprocess Execution and Error Handling + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + stdout = result.stdout + stderr = result.stderr + return_code = result.returncode + + except FileNotFoundError: + # This error occurs if 'gnuplot' is not in the system's PATH + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'gnuplot' command not found. Please ensure gnuplot is installed and in your system's PATH.", + "output_files": [], + "return_code": 127 + } + except subprocess.CalledProcessError as e: + # This error occurs if gnuplot returns a non-zero exit code + return { + "command_executed": command_executed, + "stdout": e.stdout or "", + "stderr": e.stderr or "Gnuplot exited with a non-zero status code.", + "output_files": [], + "return_code": e.returncode + } + + # 5. Structured Result Return + output_files = [] + if expected_output: + if expected_output.is_file(): + output_files.append(str(expected_output.resolve())) + else: + # If the expected file was not created, it's not an error for the tool itself, + # but it's useful information to include in stderr. + warning_msg = f"\nWarning: Expected output file was not created: {expected_output}" + stderr = (stderr + warning_msg) if stderr else warning_msg + + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + "return_code": return_code + } + + finally: + # Clean up the temporary script file if it was created + if script_path and script_path.exists(): + script_path.unlink() \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gnuplot/app/gnuplot_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gnuplot/app/gnuplot_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3815c6e99e825d38d8cbca8c96f6e9f23e1c38f5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gnuplot/app/gnuplot_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gnuplot/app/gnuplot_server.py') +SERVER_NAME = 'biosci_gnuplot' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gnuplot/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gnuplot/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gnuplot/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gnuplot/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gnuplot/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..a95a39bf47a4a3dbc26df62767433c7138407c8a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gnuplot/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-gnuplot: + build: . + image: mcp-gnuplot:latest + container_name: mcp-gnuplot + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=gnuplot + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gnuplot/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gnuplot/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ec008703129b3ef6ff99bbe3cc9c90d81d681641 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gnuplot/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - gnuplot + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gnuplot/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gnuplot/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gnuplot/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gofasta/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gofasta/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..94e837527971c90eedb42f31ee8e2a2d61ca26f2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gofasta/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install gofasta via conda (e.g., from bioconda) +RUN conda install -c bioconda gofasta -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/gofasta_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/gofasta_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/gofasta_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gofasta/app/gofasta_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gofasta/app/gofasta_server.py new file mode 100644 index 0000000000000000000000000000000000000000..99adc0cb4201457c8ceaba699182e565d17b5e51 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gofasta/app/gofasta_server.py @@ -0,0 +1,497 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Literal + +# Helper function for running commands +def _run_command(cmd: List[str], output_file: Optional[Path] = None) -> dict: + """ + Executes a shell command and captures its output. + If output_file is provided, redirects stdout to the file. + """ + stdout_capture = subprocess.PIPE + stderr_capture = subprocess.PIPE + output_files_produced = [] + + try: + if output_file: + output_files_produced.append(str(output_file)) + # Ensure parent directory exists for the output file + output_file.parent.mkdir(parents=True, exist_ok=True) + with open(output_file, "w") as f: + process = subprocess.run(cmd, stdout=f, stderr=stderr_capture, check=True, text=True) + stdout_content = "" # stdout was redirected to file + else: + process = subprocess.run(cmd, stdout=stdout_capture, stderr=stderr_capture, check=True, text=True) + stdout_content = process.stdout + + return { + "command_executed": " ".join(cmd), + "stdout": stdout_content, + "stderr": process.stderr, + "output_files": output_files_produced, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": e.cmd, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": str(e), + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": "gofasta command not found. Please ensure it is installed and in your PATH.", + "output_files": [], + "error": "gofasta command not found.", + } + + +@mcp.tool() +def gofasta_closest( + query: Path, + target: Path, + measure: Literal["raw", "snp", "tn93"] = "raw", + threads: Optional[int] = None, + number: Optional[int] = None, + max_dist: Optional[float] = None, + outfile: Optional[Path] = None, + table: bool = False, +) -> dict: + """ + Find the closest sequence(s) to a query by genetic distance. + + Args: + query: Alignment of sequences to find neighbours for, in fasta format. + target: Alignment of sequences to search for neighbours in, in fasta format. + measure: Which distance measure to use (raw, snp or tn93). + threads: Number of CPUs to use. If None, gofasta will use all available. + number: (Optional) The closest n sequences to each query will be returned. + max_dist: (Optional) Return all sequences less than or equal to this distance away. + Type is float for flexibility, as raw is per site, tn93 is evolutionary distance, + and snp is an integer count. + outfile: The output file to write. If None, output is written to stdout. + table: Write a long-form table of the output. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + if not query.is_file(): + raise FileNotFoundError(f"Query file not found: {query}") + if not target.is_file(): + raise FileNotFoundError(f"Target file not found: {target}") + if threads is not None and threads <= 0: + raise ValueError("Threads must be a positive integer.") + if number is not None and number <= 0: + raise ValueError("Number of closest sequences must be a positive integer.") + if max_dist is not None and max_dist < 0: + raise ValueError("Maximum distance must be a non-negative float.") + + cmd = ["gofasta", "closest"] + cmd.extend(["--query", str(query)]) + cmd.extend(["--target", str(target)]) + cmd.extend(["--measure", measure]) + + if threads is not None: + cmd.extend(["--threads", str(threads)]) + if number is not None: + cmd.extend(["--number", str(number)]) + if max_dist is not None: + cmd.extend(["--max-dist", str(max_dist)]) + if table: + cmd.append("--table") + + return _run_command(cmd, outfile) + + +@mcp.tool() +def gofasta_sam_to_multi_align( + reference: Path, + sam_file: Optional[Path] = None, + start: Optional[int] = None, + end: Optional[int] = None, + pad: bool = False, + outfile: Optional[Path] = None, + threads: Optional[int] = None, +) -> dict: + """ + Converts SAM format alignments to a multiple sequence alignment in FASTA format. + + Args: + reference: Reference sequence in FASTA format. This is treated as a positional argument. + sam_file: Input SAM file. If None, reads from stdin. + start: 1-based inclusive start coordinate for clipping the alignment. + end: 1-based inclusive end coordinate for clipping the alignment. + pad: Replace trimmed regions with Ns to retain the reference length in the output. + outfile: Output FASTA file to write. If None, output is written to stdout. + threads: Number of CPUs to use. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + if sam_file is not None and not sam_file.is_file(): + raise FileNotFoundError(f"SAM input file not found: {sam_file}") + if not reference.is_file(): + raise FileNotFoundError(f"Reference file not found: {reference}") + if start is not None and start <= 0: + raise ValueError("Start coordinate must be a positive integer.") + if end is not None and end <= 0: + raise ValueError("End coordinate must be a positive integer.") + if start is not None and end is not None and start > end: + raise ValueError("Start coordinate cannot be greater than end coordinate.") + if threads is not None and threads <= 0: + raise ValueError("Threads must be a positive integer.") + + cmd = ["gofasta", "sam", "toMultiAlign"] + if sam_file is not None: + cmd.extend(["--sam", str(sam_file)]) + if start is not None: + cmd.extend(["--start", str(start)]) + if end is not None: + cmd.extend(["--end", str(end)]) + if pad: + cmd.append("--pad") + if threads is not None: + cmd.extend(["-t", str(threads)]) + + cmd.append(str(reference)) # Positional argument + + return _run_command(cmd, outfile) + + +@mcp.tool() +def gofasta_sam_to_pair_align( + reference: Path, + output_dir: Path, + sam_file: Optional[Path] = None, + start: Optional[int] = None, + end: Optional[int] = None, + threads: Optional[int] = None, +) -> dict: + """ + Converts SAM format alignments into pairwise FASTA alignments, writing one file per consensus genome. + + Args: + reference: Reference sequence in FASTA format. + output_dir: Output directory to write individual FASTA files. Will be created if it does not exist. + sam_file: Input SAM file. If None, reads from stdin. + start: 1-based inclusive start coordinate for clipping the alignment. + end: 1-based inclusive end coordinate for clipping the alignment. + threads: Number of CPUs to use. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + if sam_file is not None and not sam_file.is_file(): + raise FileNotFoundError(f"SAM input file not found: {sam_file}") + if not reference.is_file(): + raise FileNotFoundError(f"Reference file not found: {reference}") + if start is not None and start <= 0: + raise ValueError("Start coordinate must be a positive integer.") + if end is not None and end <= 0: + raise ValueError("End coordinate must be a positive integer.") + if start is not None and end is not None and start > end: + raise ValueError("Start coordinate cannot be greater than end coordinate.") + if threads is not None and threads <= 0: + raise ValueError("Threads must be a positive integer.") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = ["gofasta", "sam", "toPairAlign"] + if sam_file is not None: + cmd.extend(["--sam", str(sam_file)]) + cmd.extend(["--reference", str(reference)]) + cmd.extend(["--outfile", str(output_dir)]) # Note: --outfile here is a directory + if start is not None: + cmd.extend(["--start", str(start)]) + if end is not None: + cmd.extend(["--end", str(end)]) + if threads is not None: + cmd.extend(["-t", str(threads)]) + + # For toPairAlign, output_dir is the target, not a single file. + # We can't predict the exact filenames, so we'll just report the directory. + result = _run_command(cmd) + if not result.get("error"): # Only add output_dir if command was successful + result["output_files"].append(str(output_dir)) + return result + + +@mcp.tool() +def gofasta_snps( + reference: Path, + query: Optional[Path] = None, + outfile: Optional[Path] = None, + hard_gaps: bool = False, + aggregate: bool = False, + threshold: Optional[float] = None, +) -> dict: + """ + Extracts nucleotide changes relative to a reference sequence from a multiple sequence alignment. + + Args: + reference: Reference sequence, in fasta format. + query: Alignment of sequences to find SNPs in, in fasta format. If None, reads from stdin. + outfile: Output file to write. If None, output is written to stdout. + hard_gaps: Don't treat alignment gaps as missing data (treat as Ns by default). + aggregate: Report the proportions of each change instead of per-sequence SNPs. + threshold: If --aggregate, only report SNPs with a frequency greater than or equal to this value. + Must be between 0.0 and 1.0. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + if not reference.is_file(): + raise FileNotFoundError(f"Reference file not found: {reference}") + if query is not None and not query.is_file(): + raise FileNotFoundError(f"Query file not found: {query}") + if threshold is not None: + if not aggregate: + raise ValueError("Threshold can only be specified when --aggregate is true.") + if not (0.0 <= threshold <= 1.0): + raise ValueError("Threshold must be between 0.0 and 1.0.") + + cmd = ["gofasta", "snps"] + cmd.extend(["--reference", str(reference)]) + if query is not None: + cmd.extend(["--query", str(query)]) + if hard_gaps: + cmd.append("--hard-gaps") + if aggregate: + cmd.append("--aggregate") + if threshold is not None: + cmd.extend(["--threshold", str(threshold)]) + + return _run_command(cmd, outfile) + + +@mcp.tool() +def gofasta_updown_list( + reference: Path, + query: Optional[Path] = None, + outfile: Optional[Path] = None, +) -> dict: + """ + Generate input CSV files for gofasta updown topranking. + + Args: + reference: Reference sequence, in fasta format. + query: Alignment of sequences to parse, in fasta format. If None, reads from stdin. + outfile: Output CSV-format file to write. If None, output is written to stdout. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + if not reference.is_file(): + raise FileNotFoundError(f"Reference file not found: {reference}") + if query is not None and not query.is_file(): + raise FileNotFoundError(f"Query file not found: {query}") + + cmd = ["gofasta", "updown", "list"] + cmd.extend(["--reference", str(reference)]) + if query is not None: + cmd.extend(["--query", str(query)]) + + return _run_command(cmd, outfile) + + +@mcp.tool() +def gofasta_updown_topranking( + reference: Path, + query: Path, + target: Path, + outfile: Optional[Path] = None, + table: bool = False, + ignore: Optional[Path] = None, + dist_all: Optional[int] = None, + dist_up: Optional[int] = None, + dist_down: Optional[int] = None, + dist_side: Optional[int] = None, + size_total: Optional[int] = None, + size_up: Optional[int] = None, + size_down: Optional[int] = None, + size_side: Optional[int] = None, + size_same: Optional[int] = None, + threshold_pair: float = 0.1, + threshold_target: int = 10000, + dist_push: Optional[int] = None, + no_fill: bool = False, +) -> dict: + """ + Finds the closest neighbours by (directional) SNP distance. + + Args: + reference: Reference sequence, in fasta format, which is treated as the root of the imaginary tree. + query: File with sequences to find neighbours for. Either CSV output of gofasta updown list, or FASTA alignment. + target: File of sequences to look for neighbours in. Either CSV output of gofasta updown list, or FASTA alignment. + outfile: CSV-format file of closest neighbours to write. If None, output is written to stdout. + table: Write a long-form table of the output. + ignore: Optional plain text file of IDs to ignore in the target file when searching for neighbours. + dist_all: Maximum allowed SNP-distance between target and query sequence in any direction. Overrides other dist settings. + dist_up: Maximum allowed SNP-distance from query for sequences in the parent bin. + dist_down: Maximum allowed SNP-distance from query for sequences in the child bin. + dist_side: Maximum allowed SNP-distance from query for sequences in the sibling bin. + size_total: Max number of neighbours to find (attempts to split equally between same/up/down/side). A hard limit. + size_up: Max number of closest parent sequences to find, if size_total not specified. A soft limit unless --no-fill. + size_down: Max number of closest child sequences to find, if size_total not specified. A soft limit unless --no-fill. + size_side: Max number of closest sibling sequences to find, if size_total not specified. A soft limit unless --no-fill. + size_same: Max number of identical sequences to find, if size_total not specified. A soft limit unless --no-fill. + threshold_pair: Up to this proportion of consequential sites is allowed to be ambiguous in either sequence for each pairwise comparison. + threshold_target: Target can have at most this number of ambiguities to be considered. + dist_push: Push the --dist boundaries outwards so that bins have at least these many closest SNP-distances for which there are neighbours, where possible. + no_fill: Don't make up for a shortfall in any of --size-up, -down, -side or -same by increasing the count for other bins. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + if not reference.is_file(): + raise FileNotFoundError(f"Reference file not found: {reference}") + if not query.is_file(): + raise FileNotFoundError(f"Query file not found: {query}") + if not target.is_file(): + raise FileNotFoundError(f"Target file not found: {target}") + if ignore is not None and not ignore.is_file(): + raise FileNotFoundError(f"Ignore file not found: {ignore}") + + # Validate integer parameters are non-negative if set + for param_name, param_value in [ + ("dist_all", dist_all), ("dist_up", dist_up), ("dist_down", dist_down), + ("dist_side", dist_side), ("size_total", size_total), ("size_up", size_up), + ("size_down", size_down), ("size_side", size_side), ("size_same", size_same), + ("dist_push", dist_push) + ]: + if param_value is not None and param_value < 0: + raise ValueError(f"{param_name} must be a non-negative integer.") + + if not (0.0 <= threshold_pair <= 1.0): + raise ValueError("Threshold pair must be between 0.0 and 1.0.") + if threshold_target < 0: + raise ValueError("Threshold target must be a non-negative integer.") + + cmd = ["gofasta", "updown", "topranking"] + cmd.extend(["--reference", str(reference)]) + cmd.extend(["--query", str(query)]) + cmd.extend(["--target", str(target)]) + + if table: + cmd.append("--table") + if ignore is not None: + cmd.extend(["--ignore", str(ignore)]) + if dist_all is not None: + cmd.extend(["--dist-all", str(dist_all)]) + if dist_up is not None: + cmd.extend(["--dist-up", str(dist_up)]) + if dist_down is not None: + cmd.extend(["--dist-down", str(dist_down)]) + if dist_side is not None: + cmd.extend(["--dist-side", str(dist_side)]) + if size_total is not None: + cmd.extend(["--size-total", str(size_total)]) + if size_up is not None: + cmd.extend(["--size-up", str(size_up)]) + if size_down is not None: + cmd.extend(["--size-down", str(size_down)]) + if size_side is not None: + cmd.extend(["--size-side", str(size_side)]) + if size_same is not None: + cmd.extend(["--size-same", str(size_same)]) + + cmd.extend(["--threshold-pair", str(threshold_pair)]) + cmd.extend(["--threshold-target", str(threshold_target)]) + + if dist_push is not None: + cmd.extend(["--dist-push", str(dist_push)]) + if no_fill: + cmd.append("--no-fill") + + return _run_command(cmd, outfile) + + +@mcp.tool() +def gofasta_variants( + annotation: Path, + query: Optional[Path] = None, + outfile: Optional[Path] = None, + aggregate: bool = False, + reference: Optional[Path] = None, +) -> dict: + """ + Annotates amino acid, indel, and nucleotide changes relative to an annotated reference sequence + from a multiple sequence alignment in FASTA format. + + Args: + annotation: Annotation file (Genbank flat file or GFF3 format). + query: Alignment of sequences to annotate, in FASTA format. If None, reads from stdin. + outfile: Output file to write. If None, output is written to stdout. + aggregate: Report the overall frequencies of mutations. + reference: Reference sequence in FASTA format. Optional if a sequence in the same space + as the annotation is present in the alignment (first sequence if stdin). + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + if not annotation.is_file(): + raise FileNotFoundError(f"Annotation file not found: {annotation}") + if query is not None and not query.is_file(): + raise FileNotFoundError(f"Query file not found: {query}") + if reference is not None and not reference.is_file(): + raise FileNotFoundError(f"Reference file not found: {reference}") + + cmd = ["gofasta", "variants"] + cmd.extend(["--annotation", str(annotation)]) + if query is not None: + cmd.extend(["--query", str(query)]) + if aggregate: + cmd.append("--aggregate") + if reference is not None: + cmd.extend(["--reference", str(reference)]) + + return _run_command(cmd, outfile) + + +@mcp.tool() +def gofasta_sam_variants( + annotation: Path, + sam_file: Optional[Path] = None, + outfile: Optional[Path] = None, + aggregate: bool = False, + reference: Optional[Path] = None, + threads: Optional[int] = None, +) -> dict: + """ + Annotates amino acid, indel, and nucleotide changes relative to an annotated reference sequence + from alignments in SAM format. + + Args: + annotation: Annotation file (Genbank flat file or GFF3 format). + sam_file: Input SAM file. If None, reads from stdin. + outfile: Output file to write. If None, output is written to stdout. + aggregate: Report the overall frequencies of mutations. + reference: Reference sequence in FASTA format. Optional unless it is not present in your annotation. + threads: Number of CPUs to use. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + if not annotation.is_file(): + raise FileNotFoundError(f"Annotation file not found: {annotation}") + if sam_file is not None and not sam_file.is_file(): + raise FileNotFoundError(f"SAM input file not found: {sam_file}") + if reference is not None and not reference.is_file(): + raise FileNotFoundError(f"Reference file not found: {reference}") + if threads is not None and threads <= 0: + raise ValueError("Threads must be a positive integer.") + + cmd = ["gofasta", "sam", "variants"] + cmd.extend(["--annotation", str(annotation)]) + if sam_file is not None: + cmd.extend(["--sam", str(sam_file)]) + if aggregate: + cmd.append("--aggregate") + if reference is not None: + cmd.extend(["--reference", str(reference)]) + if threads is not None: + cmd.extend(["-t", str(threads)]) + + return _run_command(cmd, outfile) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gofasta/app/gofasta_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gofasta/app/gofasta_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b2aff47ca0e99d807ce449d006ece15176b1af28 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gofasta/app/gofasta_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gofasta/app/gofasta_server.py') +SERVER_NAME = 'biosci_gofasta' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gofasta/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gofasta/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gofasta/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gofasta/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gofasta/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..010031b0f4108eceb1e3192bcdadf764c68f0101 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gofasta/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-gofasta: + build: . + image: mcp-gofasta:latest + container_name: mcp-gofasta + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=gofasta + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gofasta/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gofasta/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5ceee962e602571af66aed9b8e5fb40a8adf3b1b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gofasta/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - gofasta + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gofasta/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gofasta/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gofasta/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_goleft/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_goleft/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..654ab93c8fe816b5153cf4d183021d0447c40e95 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_goleft/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install goleft via conda (e.g., from bioconda) +RUN conda install -c bioconda goleft -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/goleft_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/goleft_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/goleft_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_goleft/app/goleft_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_goleft/app/goleft_server.py new file mode 100644 index 0000000000000000000000000000000000000000..e4a64b8fe79983ac513f7e73fd368007612b1666 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_goleft/app/goleft_server.py @@ -0,0 +1,435 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# NOTE: The @mcp.tool decorator is a placeholder. +# In a real MCP environment, it would be provided by the MCP framework. +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def goleft_covstats( + bams: List[Path], + denominator: str = "target-size", + n_reads: int = 25000000, + procs: int = 4, + reference: Optional[Path] = None, + target_bed: Optional[Path] = None, +): + """ + Estimate coverage and insert-size statistics on BAM/CRAM files by sampling. + + Args: + bams: List of input BAM/CRAM files. + denominator: Calculate coverage as reads / denominator. Must be 'target-size' or 'genome-size'. + n_reads: Number of reads to sample from each BAM. + procs: Number of processors to use. + reference: Optional reference FASTA for CRAM files. + target_bed: Optional BED file of target regions. + """ + # Input validation + if not bams: + raise ValueError("At least one BAM/CRAM file must be provided.") + for bam in bams: + if not bam.is_file(): + raise FileNotFoundError(f"Input file not found: {bam}") + if denominator not in ["target-size", "genome-size"]: + raise ValueError("Denominator must be one of 'target-size' or 'genome-size'.") + if n_reads <= 0: + raise ValueError("n_reads must be a positive integer.") + if procs <= 0: + raise ValueError("procs must be a positive integer.") + if reference and not reference.is_file(): + raise FileNotFoundError(f"Reference file not found: {reference}") + if target_bed and not target_bed.is_file(): + raise FileNotFoundError(f"Target BED file not found: {target_bed}") + + cmd = [ + "goleft", "covstats", + "--denominator", denominator, + "--nreads", str(n_reads), + "--procs", str(procs), + ] + + if reference: + cmd.extend(["--reference", str(reference)]) + if target_bed: + cmd.extend(["--targetbed", str(target_bed)]) + + cmd.extend([str(p) for p in bams]) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"goleft covstats failed with exit code {e.returncode}", + "output_files": [], + } + +@mcp.tool +def goleft_depth( + bams: List[Path], + fai: Path, + output_dir: Path, + bed: Optional[Path] = None, + gaps: int = 2000, + procs: int = 4, + map_quality: int = 10, + base_quality: int = 10, + reference: Optional[Path] = None, + window_size: int = 5000, + min_cov: int = 1, + s_flags: int = 1796, + f_flags: int = 0, +): + """ + Parallelize calls to samtools depth in user-defined windows. + + Args: + bams: List of input BAM/CRAM files. + fai: FAI file of the reference genome. + output_dir: Directory to write depth files. + bed: Optional BED file of regions to process. + gaps: Number of bases to pad between windows for discordant pairs. + procs: Number of processors to use. + map_quality: Only count reads with mapping quality of at least this value. + base_quality: Only count bases with base quality of at least this value. + reference: Optional reference FASTA for CRAM files. + window_size: Window size for coverage depth reporting. + min_cov: Only report windows with coverage at least this value. + s_flags: Samtools flags to skip reads (e.g., 1796 for QCFAIL, DUP, SECONDARY, SUPPLEMENTARY). + f_flags: Samtools flags to filter reads (e.g., 2 to count only proper pairs). + """ + # Input validation + if not bams: + raise ValueError("At least one BAM/CRAM file must be provided.") + for bam in bams: + if not bam.is_file(): + raise FileNotFoundError(f"Input file not found: {bam}") + if not fai.is_file(): + raise FileNotFoundError(f"FAI file not found: {fai}") + if bed and not bed.is_file(): + raise FileNotFoundError(f"BED file not found: {bed}") + if reference and not reference.is_file(): + raise FileNotFoundError(f"Reference file not found: {reference}") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "goleft", "depth", + "--fai", str(fai), + "--dir", str(output_dir), + "--gaps", str(gaps), + "--procs", str(procs), + "-q", str(map_quality), + "-Q", str(base_quality), + "--windowsize", str(window_size), + "--mincov", str(min_cov), + "--sflags", str(s_flags), + "--fflags", str(f_flags), + ] + + if bed: + cmd.extend(["--bed", str(bed)]) + if reference: + cmd.extend(["--reference", str(reference)]) + + cmd.extend([str(p) for p in bams]) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + output_files = [output_dir / f"{bam.stem}.depth.bed.gz" for bam in bams] + final_output_files = [str(f) for f in output_files if f.exists()] + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": final_output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"goleft depth failed with exit code {e.returncode}", + "output_files": [], + } + +@mcp.tool +def goleft_depthwed( + depth_files: List[Path], + bed: Path, + prefix: str, + output_dir: Optional[Path] = None, +): + """ + Matricize output from 'goleft depth' to n-sites * n-samples. + + Args: + depth_files: List of depth files generated by 'goleft depth'. + bed: BED file of regions used to create the depth files. + prefix: Prefix for output files (e.g., 'my_cohort'). + output_dir: Directory to write output files. Defaults to a temporary directory. + """ + # Input validation + if not depth_files: + raise ValueError("At least one depth file must be provided.") + for df in depth_files: + if not df.is_file(): + raise FileNotFoundError(f"Input depth file not found: {df}") + if not bed.is_file(): + raise FileNotFoundError(f"BED file not found: {bed}") + if not prefix.strip(): + raise ValueError("Prefix cannot be empty.") + + with tempfile.TemporaryDirectory() as temp_dir: + work_dir = output_dir or Path(temp_dir) + work_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "goleft", "depthwed", + "--bed", str(bed), + "--prefix", prefix, + ] + cmd.extend([str(p) for p in depth_files]) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + cwd=work_dir, + ) + + expected_files = [ + work_dir / f"{prefix}.depth.tsv", + work_dir / f"{prefix}.sites.bed.gz", + work_dir / f"{prefix}.samples.tsv" + ] + output_files = [str(f) for f in expected_files if f.exists()] + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"goleft depthwed failed with exit code {e.returncode}", + "output_files": [], + } + +@mcp.tool +def goleft_indexcov( + bams: List[Path], + fai: Path, + output_dir: Path, + procs: int = 4, + sex_file: Optional[Path] = None, + window_size: str = "16K", +): + """ + Quick coverage estimate using only the BAM/CRAM index. + + Args: + bams: List of input BAM/CRAM files (and their .bai/.crai indexes). + fai: FAI file of the reference genome. + output_dir: Directory to write output files (HTML report, etc.). + procs: Number of processors to use. + sex_file: Optional file containing sample\tsex mapping. + window_size: Window size for coverage depth reporting (e.g., '16K', '1M'). + """ + # Input validation + if not bams: + raise ValueError("At least one BAM/CRAM file must be provided.") + for bam in bams: + if not bam.is_file(): + raise FileNotFoundError(f"Input file not found: {bam}") + index_bai = bam.with_suffix(bam.suffix + ".bai") + index_crai = bam.with_suffix(".crai") + if not (index_bai.exists() or index_crai.exists()): + raise FileNotFoundError(f"Index file (.bai or .crai) not found for {bam}") + if not fai.is_file(): + raise FileNotFoundError(f"FAI file not found: {fai}") + if sex_file and not sex_file.is_file(): + raise FileNotFoundError(f"Sex file not found: {sex_file}") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "goleft", "indexcov", + "--fai", str(fai), + "--dir", str(output_dir), + "--procs", str(procs), + "--windowsize", window_size, + ] + + if sex_file: + cmd.extend(["--sex", str(sex_file)]) + + cmd.extend([str(p) for p in bams]) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + html_report = output_dir / "indexcov.html" + output_files = [str(p) for p in output_dir.glob('**/*') if p.is_file()] + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + "main_report": str(html_report) if html_report.exists() else None + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"goleft indexcov failed with exit code {e.returncode}", + "output_files": [], + } + +@mcp.tool +def goleft_indexsplit( + bams: List[Path], + fai: Path, + n_chunks: int = 100, + output_file: Optional[Path] = None, + procs: int = 4, +): + """ + Generate regions of even data across a cohort for parallelization. + + Args: + bams: List of input BAM/CRAM files. + fai: FAI file of the reference genome. + n_chunks: Number of chunks to create. + output_file: File to write regions to. If None, writes to stdout. + procs: Number of processors to use. + """ + # Input validation + if not bams: + raise ValueError("At least one BAM/CRAM file must be provided.") + for bam in bams: + if not bam.is_file(): + raise FileNotFoundError(f"Input file not found: {bam}") + if not fai.is_file(): + raise FileNotFoundError(f"FAI file not found: {fai}") + if n_chunks <= 0: + raise ValueError("n_chunks must be a positive integer.") + if procs <= 0: + raise ValueError("procs must be a positive integer.") + + cmd = [ + "goleft", "indexsplit", + "--fai", str(fai), + "-N", str(n_chunks), + "--procs", str(procs), + ] + + output_files_list = [] + if output_file: + cmd.extend(["--out", str(output_file)]) + output_files_list.append(str(output_file)) + + cmd.extend([str(p) for p in bams]) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files_list, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"goleft indexsplit failed with exit code {e.returncode}", + "output_files": [], + } + +@mcp.tool +def goleft_samplename( + bams: List[Path], +): + """ + Report samplename(s) from a BAM/CRAM file's SM tag in the header. + + Args: + bams: List of input BAM/CRAM files. + """ + # Input validation + if not bams: + raise ValueError("At least one BAM/CRAM file must be provided.") + for bam in bams: + if not bam.is_file(): + raise FileNotFoundError(f"Input file not found: {bam}") + + cmd = ["goleft", "samplename"] + cmd.extend([str(p) for p in bams]) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"goleft samplename failed with exit code {e.returncode}", + "output_files": [], + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_goleft/app/goleft_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_goleft/app/goleft_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9071cfda9bb661743f03635a5b67c6ccaaaa1e27 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_goleft/app/goleft_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_goleft/app/goleft_server.py') +SERVER_NAME = 'biosci_goleft' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_goleft/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_goleft/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_goleft/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_goleft/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_goleft/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..be5348e342deeffe41b34a8051fd7f83e9ac76d3 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_goleft/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-goleft: + build: . + image: mcp-goleft:latest + container_name: mcp-goleft + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=goleft + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_goleft/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_goleft/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..fc842e11ccefeccf5dc031cbffa31a8e6486189e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_goleft/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - goleft + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_goleft/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_goleft/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_goleft/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gridss/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gridss/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gridss/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gromacs/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gromacs/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6dddfd57f06bcbce0153d4eafc7cf08b91ad7817 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gromacs/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install gromacs via conda (e.g., from bioconda) +RUN conda install -c bioconda gromacs -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/gromacs_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/gromacs_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/gromacs_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gromacs/app/gromacs_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gromacs/app/gromacs_server.py new file mode 100644 index 0000000000000000000000000000000000000000..24a40dd36a26827a962490e74a93346f1caa13e1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gromacs/app/gromacs_server.py @@ -0,0 +1,503 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +@mcp.tool() +def gmx_pdb2gmx( + f: str, + o: str = "processed.gro", + p: str = "topol.top", + i: str = "posre.itp", + ff: str = "oplsaa", + water: str = "spce", + ignh: bool = False, + missing: bool = False, +): + """ + Converts PDB files to GROMACS coordinate and topology files. + + Args: + f: Input structure file (.pdb, .gro, etc.) + o: Output structure file + p: Output topology file + i: Output position restraint file + ff: Force field to use (e.g., 'oplsaa', 'amber99sb-ildn') + water: Water model (e.g., 'spce', 'tip3p') + ignh: Ignore hydrogen atoms in the PDB file + missing: Allow missing atoms + """ + input_path = Path(f) + if not input_path.exists(): + return {"error": f"Input file {f} not found"} + + cmd = [ + "gmx", "pdb2gmx", + "-f", str(input_path), + "-o", o, + "-p", p, + "-i", i, + "-ff", ff, + "-water", water + ] + + if ignh: + cmd.append("-ignh") + if missing: + cmd.append("-missing") + + 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": [o, p, i] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def gmx_editconf( + f: str, + o: str = "box.gro", + c: bool = True, + d: float = 1.0, + bt: str = "cubic", + box: Optional[str] = None, + princ: bool = False, +): + """ + Edits the simulation box and centers the system. + + Args: + f: Input structure file + o: Output structure file + c: Center molecule in box + d: Distance between the solute and the box edge (nm) + bt: Box type: 'cubic', 'triclinic', 'magical', 'octahedron', 'dodecahedron' + box: Box vector lengths (x, y, z) as a string + princ: Orient molecule along principal axes + """ + input_path = Path(f) + if not input_path.exists(): + return {"error": f"Input file {f} not found"} + + cmd = ["gmx", "editconf", "-f", str(input_path), "-o", o, "-bt", bt] + + if c: + cmd.append("-c") + if d > 0: + cmd.extend(["-d", str(d)]) + if box: + cmd.extend(["-box", box]) + if princ: + cmd.append("-princ") + + 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": [o] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def gmx_solvate( + cp: str, + cs: str = "spc216.gro", + p: str = "topol.top", + o: str = "solvated.gro", + maxsol: int = 0, +): + """ + Solvates a system by adding water molecules. + + Args: + cp: Input structure file (solute) + cs: Solvent structure file + p: Topology file (will be updated) + o: Output structure file + maxsol: Maximum number of solvent molecules to add (0 for all) + """ + cp_path = Path(cp) + p_path = Path(p) + if not cp_path.exists(): + return {"error": f"Solute file {cp} not found"} + if not p_path.exists(): + return {"error": f"Topology file {p} not found"} + + cmd = [ + "gmx", "solvate", + "-cp", str(cp_path), + "-cs", cs, + "-p", str(p_path), + "-o", o + ] + + if maxsol > 0: + cmd.extend(["-maxsol", str(maxsol)]) + + 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": [o, p] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def gmx_grompp( + f: str, + c: str, + p: str, + o: str = "topol.tpr", + r: Optional[str] = None, + n: Optional[str] = None, + maxwarn: int = 0, +): + """ + The GROMACS preprocessor: generates a run input file (.tpr). + + Args: + f: Input MD parameter file (.mdp) + c: Input structure file (.gro) + p: Input topology file (.top) + o: Output run input file (.tpr) + r: Structure file for restraints + n: Index file (.ndx) + maxwarn: Number of allowed warnings + """ + f_path = Path(f) + c_path = Path(c) + p_path = Path(p) + + for path in [f_path, c_path, p_path]: + if not path.exists(): + return {"error": f"Required file {path} not found"} + + cmd = [ + "gmx", "grompp", + "-f", str(f_path), + "-c", str(c_path), + "-p", str(p_path), + "-o", o, + "-maxwarn", str(maxwarn) + ] + + if r: + cmd.extend(["-r", r]) + if n: + cmd.extend(["-n", n]) + + 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": [o] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def gmx_genion( + s: str, + p: str, + o: str = "solvated_ions.gro", + pname: str = "NA", + nname: str = "CL", + neutral: bool = True, + conc: float = 0.0, + selection: str = "SOL", +): + """ + Adds ions to a solvated system to neutralize it or reach a concentration. + + Args: + s: Input run input file (.tpr) + p: Topology file (will be updated) + o: Output structure file + pname: Name of the positive ion + nname: Name of the negative ion + neutral: Add ions to neutralize the system + conc: Specify salt concentration (mol/liter) + selection: Group to replace with ions (usually 'SOL' or '13') + """ + s_path = Path(s) + p_path = Path(p) + if not s_path.exists(): + return {"error": f"TPR file {s} not found"} + + cmd = [ + "gmx", "genion", + "-s", str(s_path), + "-p", str(p_path), + "-o", o, + "-pname", pname, + "-nname", nname + ] + + if neutral: + cmd.append("-neutral") + if conc > 0: + cmd.extend(["-conc", str(conc)]) + + try: + # genion requires interactive selection of the solvent group + result = subprocess.run( + cmd, + input=selection, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [o, p] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def gmx_mdrun( + s: str = "topol.tpr", + deffnm: str = "md", + v: bool = True, + nt: int = 0, + nb: str = "auto", + pme: str = "auto", + gpu_id: Optional[str] = None, +): + """ + Executes the molecular dynamics simulation. + + Args: + s: Input run input file (.tpr) + deffnm: Default filename for all outputs + v: Verbose output + nt: Number of threads to use (0 for auto) + nb: Calculate non-bonded interactions on: 'auto', 'cpu', 'gpu' + pme: Calculate PME on: 'auto', 'cpu', 'gpu' + gpu_id: List of GPU device IDs to use + """ + s_path = Path(s) + if not s_path.exists(): + return {"error": f"TPR file {s} not found"} + + cmd = [ + "gmx", "mdrun", + "-s", str(s_path), + "-deffnm", deffnm, + "-nb", nb, + "-pme", pme + ] + + if v: + cmd.append("-v") + if nt > 0: + cmd.extend(["-nt", str(nt)]) + if gpu_id: + cmd.extend(["-gpu_id", gpu_id]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [f"{deffnm}.log", f"{deffnm}.xtc", f"{deffnm}.edr", f"{deffnm}.gro"] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def gmx_energy( + f: str = "ener.edr", + o: str = "energy.xvg", + selection: str = "Potential", +): + """ + Extracts energy terms from an energy file (.edr). + + Args: + f: Input energy file + o: Output graph file (.xvg) + selection: Energy term to extract (e.g., 'Potential', 'Temperature', 'Pressure') + """ + f_path = Path(f) + if not f_path.exists(): + return {"error": f"Energy file {f} not found"} + + cmd = ["gmx", "energy", "-f", str(f_path), "-o", o] + + try: + # selection is piped to stdin (e.g., "Potential 0" to select Potential and end) + input_str = f"{selection}\n0\n" + result = subprocess.run( + cmd, + input=input_str, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [o] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def gmx_rms( + s: str, + f: str, + o: str = "rms.xvg", + selection: str = "Backbone Backbone", +): + """ + Calculates Root Mean Square Deviation (RMSD). + + Args: + s: Reference structure file (.tpr, .gro) + f: Trajectory file (.xtc, .trr) + o: Output graph file (.xvg) + selection: Groups for fitting and calculation (e.g., 'Backbone Backbone') + """ + s_path = Path(s) + f_path = Path(f) + if not s_path.exists() or not f_path.exists(): + return {"error": "Input files not found"} + + cmd = ["gmx", "rms", "-s", str(s_path), "-f", str(f_path), "-o", o] + + try: + # selection usually requires two groups: one for fitting, one for calculation + result = subprocess.run( + cmd, + input=selection, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [o] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def gmx_trjconv( + f: str, + s: str, + o: str = "output.xtc", + pbc: str = "mol", + center: bool = True, + ur: str = "compact", + selection: str = "System", +): + """ + Converts and manipulates trajectory files (PBC treatment, centering). + + Args: + f: Input trajectory file + s: Input structure/tpr file + o: Output trajectory/structure file + pbc: PBC treatment: 'none', 'mol', 'res', 'atom', 'nojump', 'cluster' + center: Center the system + ur: Unit cell representation: 'rect', 'tric', 'compact' + selection: Group to write to output + """ + f_path = Path(f) + s_path = Path(s) + if not f_path.exists() or not s_path.exists(): + return {"error": "Input files not found"} + + cmd = [ + "gmx", "trjconv", + "-f", str(f_path), + "-s", str(s_path), + "-o", o, + "-pbc", pbc, + "-ur", ur + ] + + if center: + cmd.append("-center") + + try: + # trjconv often needs selection for centering and for output + input_str = f"{selection}\n{selection}\n" if center else f"{selection}\n" + result = subprocess.run( + cmd, + input=input_str, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [o] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gromacs/app/gromacs_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gromacs/app/gromacs_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c8c8ebbe8f1b570281037dcefeb9b6ea0ee8678a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gromacs/app/gromacs_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gromacs/app/gromacs_server.py') +SERVER_NAME = 'biosci_gromacs' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gromacs/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gromacs/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gromacs/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gromacs/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gromacs/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c75b9cbb5170acf7f24af3b2a63598fc518eddce --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gromacs/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-gromacs: + build: . + image: mcp-gromacs:latest + container_name: mcp-gromacs + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=gromacs + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gromacs/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gromacs/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..12eba8048e391284b3123e62844fe8b04ae88e91 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gromacs/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - gromacs + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gromacs/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gromacs/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gromacs/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gseapy/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gseapy/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4c98d38ba9dfc4f4d382f2396604b285363d4027 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gseapy/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install gseapy via conda (e.g., from bioconda) +RUN conda install -c bioconda gseapy -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/gseapy_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/gseapy_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/gseapy_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gseapy/app/gseapy_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gseapy/app/gseapy_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d8830c5b74372be8f0b51e4e49c3b0f993df31ac --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gseapy/app/gseapy_server.py @@ -0,0 +1,364 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Union + +@mcp.tool() +def gseapy_gsea( + data: str, + cls: str, + gmt: str, + outdir: str = "GSEA_Result", + min_size: int = 15, + max_size: int = 500, + permutation_num: int = 1000, + weighted_score_type: float = 1.0, + method: str = "signal_to_noise", + ascending: bool = False, + threads: int = 1, + format: str = "pdf", + graph_num: int = 20, + no_plot: bool = False, + seed: int = 123, + verbose: bool = False +): + """ + Run Gene Set Enrichment Analysis (GSEA). + + Args: + data: Path to expression data file (txt, csv, gct). + cls: Path to CLS file (class vector). + gmt: Path to gene set file (gmt). + outdir: Output directory. + min_size: Minimum allowed number of genes from gene set also the data set. + max_size: Maximum allowed number of genes from gene set also the data set. + permutation_num: Number of permutations. + weighted_score_type: Weighted score type. + method: Methods to calculate correlations. + ascending: Sorting order of enrichment scores. + threads: Number of threads. + format: Graphics format (pdf, png, svg). + graph_num: Number of top gene sets to plot. + no_plot: If True, do not create plots. + seed: Random seed. + verbose: Increase output verbosity. + """ + # Input validation + data_path = Path(data) + cls_path = Path(cls) + gmt_path = Path(gmt) + + if not data_path.exists(): + return {"error": f"Data file not found: {data}"} + if not cls_path.exists(): + return {"error": f"CLS file not found: {cls}"} + if not gmt_path.exists(): + return {"error": f"GMT file not found: {gmt}"} + + cmd = [ + "gseapy", "gsea", + "-d", str(data_path), + "-c", str(cls_path), + "-g", str(gmt_path), + "-o", outdir, + "--min-size", str(min_size), + "--max-size", str(max_size), + "-n", str(permutation_num), + "-w", str(weighted_score_type), + "-m", method, + "-t", str(threads), + "-f", format, + "--graph", str(graph_num), + "--seed", str(seed) + ] + + if ascending: + cmd.append("-a") + if no_plot: + cmd.append("--no-plot") + if verbose: + cmd.append("-v") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + output_files = [str(p) for p in Path(outdir).rglob("*") if p.is_file()] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "GSEA execution failed" + } + +@mcp.tool() +def gseapy_prerank( + rnk: str, + gmt: str, + outdir: str = "Prerank_Result", + min_size: int = 15, + max_size: int = 500, + permutation_num: int = 1000, + weighted_score_type: float = 1.0, + ascending: bool = False, + threads: int = 1, + format: str = "pdf", + graph_num: int = 20, + no_plot: bool = False, + seed: int = 123, + verbose: bool = False +): + """ + Run Pre-ranked Gene Set Enrichment Analysis. + + Args: + rnk: Path to ranked list file (rnk). + gmt: Path to gene set file (gmt). + outdir: Output directory. + min_size: Minimum allowed number of genes from gene set also the data set. + max_size: Maximum allowed number of genes from gene set also the data set. + permutation_num: Number of permutations. + weighted_score_type: Weighted score type. + ascending: Sorting order of enrichment scores. + threads: Number of threads. + format: Graphics format. + graph_num: Number of top gene sets to plot. + no_plot: If True, do not create plots. + seed: Random seed. + verbose: Increase output verbosity. + """ + rnk_path = Path(rnk) + gmt_path = Path(gmt) + + if not rnk_path.exists(): + return {"error": f"Ranked list file not found: {rnk}"} + if not gmt_path.exists(): + return {"error": f"GMT file not found: {gmt}"} + + cmd = [ + "gseapy", "prerank", + "-r", str(rnk_path), + "-g", str(gmt_path), + "-o", outdir, + "--min-size", str(min_size), + "--max-size", str(max_size), + "-n", str(permutation_num), + "-w", str(weighted_score_type), + "-t", str(threads), + "-f", format, + "--graph", str(graph_num), + "--seed", str(seed) + ] + + if ascending: + cmd.append("-a") + if no_plot: + cmd.append("--no-plot") + if verbose: + cmd.append("-v") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + output_files = [str(p) for p in Path(outdir).rglob("*") if p.is_file()] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Prerank execution failed" + } + +@mcp.tool() +def gseapy_ssgsea( + data: str, + gmt: str, + outdir: str = "ssGSEA_Result", + min_size: int = 15, + max_size: int = 500, + sample_norm_method: str = "rank", + weight: float = 0.25, + threads: int = 1, + format: str = "pdf", + graph_num: int = 20, + no_plot: bool = False, + seed: int = 123, + verbose: bool = False +): + """ + Run Single-sample Gene Set Enrichment Analysis (ssGSEA). + + Args: + data: Path to expression data file. + gmt: Path to gene set file. + outdir: Output directory. + min_size: Minimum allowed number of genes from gene set also the data set. + max_size: Maximum allowed number of genes from gene set also the data set. + sample_norm_method: Sample normalization method (rank, log, log_rank). + weight: Weighted score type. + threads: Number of threads. + format: Graphics format. + graph_num: Number of top gene sets to plot. + no_plot: If True, do not create plots. + seed: Random seed. + verbose: Increase output verbosity. + """ + data_path = Path(data) + gmt_path = Path(gmt) + + if not data_path.exists(): + return {"error": f"Data file not found: {data}"} + if not gmt_path.exists(): + return {"error": f"GMT file not found: {gmt}"} + + cmd = [ + "gseapy", "ssgsea", + "-d", str(data_path), + "-g", str(gmt_path), + "-o", outdir, + "--min-size", str(min_size), + "--max-size", str(max_size), + "-m", sample_norm_method, + "-w", str(weight), + "-t", str(threads), + "-f", format, + "--graph", str(graph_num), + "--seed", str(seed) + ] + + if no_plot: + cmd.append("--no-plot") + if verbose: + cmd.append("-v") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + output_files = [str(p) for p in Path(outdir).rglob("*") if p.is_file()] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "ssGSEA execution failed" + } + +@mcp.tool() +def gseapy_enrichr( + gene_list: str, + gene_sets: str, + outdir: str = "Enrichr_Result", + organism: str = "human", + format: str = "pdf", + no_plot: bool = False, + verbose: bool = False +): + """ + Run Gene Set Enrichment using Enrichr API. + + Args: + gene_list: Path to gene list file or a comma-separated string of genes. + gene_sets: Enrichr Library name(s) (comma-separated). + outdir: Output directory. + organism: Organism (human, mouse, yeast, fly, fish, worm). + format: Graphics format. + no_plot: If True, do not create plots. + verbose: Increase output verbosity. + """ + # Check if gene_list is a file or a string + gene_list_path = Path(gene_list) + input_arg = str(gene_list) + if gene_list_path.exists(): + input_arg = str(gene_list_path) + + cmd = [ + "gseapy", "enrichr", + "-i", input_arg, + "-g", gene_sets, + "-o", outdir, + "--organism", organism, + "-f", format + ] + + if no_plot: + cmd.append("--no-plot") + if verbose: + cmd.append("-v") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + output_files = [str(p) for p in Path(outdir).rglob("*") if p.is_file()] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Enrichr execution failed" + } + +@mcp.tool() +def gseapy_replot( + indir: str, + outdir: str = "Replot_Result", + format: str = "pdf", + verbose: bool = False +): + """ + Replot GSEA results from a previous run. + + Args: + indir: Input directory containing GSEA results. + outdir: Output directory for new plots. + format: Graphics format. + verbose: Increase output verbosity. + """ + indir_path = Path(indir) + if not indir_path.exists() or not indir_path.is_dir(): + return {"error": f"Input directory not found or invalid: {indir}"} + + cmd = [ + "gseapy", "replot", + "-i", str(indir_path), + "-o", outdir, + "-f", format + ] + + if verbose: + cmd.append("-v") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + output_files = [str(p) for p in Path(outdir).rglob("*") if p.is_file()] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Replot execution failed" + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gseapy/app/gseapy_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gseapy/app/gseapy_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..891a29f281710295defe95d0806472f5a0b846c9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gseapy/app/gseapy_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gseapy/app/gseapy_server.py') +SERVER_NAME = 'biosci_gseapy' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gseapy/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gseapy/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gseapy/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gseapy/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gseapy/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..4435ac46fd3fde41c2455bea0287c6b2f97436e4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gseapy/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-gseapy: + build: . + image: mcp-gseapy:latest + container_name: mcp-gseapy + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=gseapy + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gseapy/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gseapy/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..eabe3d57d295d6cdfda2c43ea4169f58753fffd5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gseapy/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - gseapy + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gseapy/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gseapy/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gseapy/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gtdbtk/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gtdbtk/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2391d138703b4aec0a0e34ce68623acd6f398a97 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gtdbtk/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install gtdbtk via conda (e.g., from bioconda) +RUN conda install -c bioconda gtdbtk -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/gtdbtk_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/gtdbtk_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/gtdbtk_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gtdbtk/app/gtdbtk_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gtdbtk/app/gtdbtk_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3a4b3b45d835414fdc0dd7d8fdb3f62f1c2eac39 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gtdbtk/app/gtdbtk_server.py @@ -0,0 +1,628 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided by the MCP framework. +def tool(*args, **kwargs): + def decorator(f): + return f + return decorator + +mcp = type("mcp", (), {"tool": tool}) + + +def _get_output_files(out_dir: Path) -> List[str]: + """Helper function to list expected output files from GTDB-Tk.""" + out_dir.mkdir(parents=True, exist_ok=True) + # Key summary files produced by classify_wf + summary_files = [ + "gtdbtk.ar53.summary.tsv", + "gtdbtk.bac120.summary.tsv", + "gtdbtk.ar53.markers_summary.tsv", + "gtdbtk.bac120.markers_summary.tsv", + "gtdbtk.log", + "gtdbtk.warnings.log", + ] + return [str(out_dir / f) for f in summary_files] + + +@mcp.tool() +def classify_wf( + genome_dir: Path, + out_dir: Path, + batchfile: Optional[Path] = None, + extension: str = "fna", + protein_dir: Optional[Path] = None, + gtdbtk_classification_file: Optional[Path] = None, + mash_db: Optional[Path] = None, + skip_gtdb_refs: bool = False, + place_species: bool = False, + ani_file: Optional[Path] = None, + ani_threshold: float = 0.95, + min_af: float = 0.05, + min_perc_aa: float = 10.0, + radius: int = 5, + pplacer_cpus: int = 1, + unaligned_only: bool = False, + keep_intermediates: bool = False, + scratch_dir: Optional[Path] = None, + cpus: int = 1, + min_mem: int = 4, + genes: bool = False, + no_mash: bool = False, + mash_d: int = 10000, + full_tree: bool = False, + force: bool = False, + write_single_copy_genes: bool = False, + write_raw_log: bool = False, + write_bins: bool = False, + attach_metadata: bool = False, + custom_taxonomy_file: Optional[Path] = None, + skip_ani_cache: bool = False, + tmpdir: Optional[Path] = None, + debug: bool = False, + verbose: bool = False, +) -> Dict[str, Any]: + """ + Run the GTDB-Tk classify workflow to assign taxonomic classifications to genomes. + + This is the primary workflow for classifying bacterial and archaeal genomes. + It identifies marker genes, aligns them, and places them in the GTDB reference tree. + """ + # --- Input Validation --- + if not genome_dir.is_dir(): + raise ValueError(f"Input genome directory not found: {genome_dir}") + if batchfile and not batchfile.is_file(): + raise ValueError(f"Batch file not found: {batchfile}") + if protein_dir and not protein_dir.is_dir(): + raise ValueError(f"Protein directory not found: {protein_dir}") + if gtdbtk_classification_file and not gtdbtk_classification_file.is_file(): + raise ValueError(f"GTDB-Tk classification file not found: {gtdbtk_classification_file}") + if mash_db and not mash_db.is_file(): + raise ValueError(f"Custom Mash sketch file not found: {mash_db}") + if ani_file and not ani_file.is_file(): + raise ValueError(f"Pre-computed ANI report not found: {ani_file}") + if custom_taxonomy_file and not custom_taxonomy_file.is_file(): + raise ValueError(f"Custom taxonomy file not found: {custom_taxonomy_file}") + + if not 0.0 <= ani_threshold <= 1.0: + raise ValueError("ani_threshold must be between 0.0 and 1.0") + if not 0.0 <= min_af <= 1.0: + raise ValueError("min_af must be between 0.0 and 1.0") + if not min_perc_aa >= 0: + raise ValueError("min_perc_aa must be non-negative") + if not cpus > 0: + raise ValueError("cpus must be a positive integer") + if not pplacer_cpus > 0: + raise ValueError("pplacer_cpus must be a positive integer") + if not min_mem > 0: + raise ValueError("min_mem must be a positive integer") + if not mash_d > 0: + raise ValueError("mash_d must be a positive integer") + + # --- Command Construction --- + cmd = [ + "gtdbtk", "classify_wf", + "--genome_dir", str(genome_dir), + "--out_dir", str(out_dir), + "--extension", extension, + "--ani_threshold", str(ani_threshold), + "--min_af", str(min_af), + "--min_perc_aa", str(min_perc_aa), + "--radius", str(radius), + "--pplacer_cpus", str(pplacer_cpus), + "--cpus", str(cpus), + "--min_mem", str(min_mem), + "--mash_d", str(mash_d), + ] + + if batchfile: + cmd.extend(["--batchfile", str(batchfile)]) + if protein_dir: + cmd.extend(["--protein_dir", str(protein_dir)]) + if gtdbtk_classification_file: + cmd.extend(["--gtdbtk_classification_file", str(gtdbtk_classification_file)]) + if mash_db: + cmd.extend(["--mash_db", str(mash_db)]) + if skip_gtdb_refs: + cmd.append("--skip_gtdb_refs") + if place_species: + cmd.append("--place_species") + if ani_file: + cmd.extend(["--ani_file", str(ani_file)]) + if unaligned_only: + cmd.append("--unaligned_only") + if keep_intermediates: + cmd.append("--keep_intermediates") + if scratch_dir: + cmd.extend(["--scratch_dir", str(scratch_dir)]) + if genes: + cmd.append("--genes") + if no_mash: + cmd.append("--no_mash") + if full_tree: + cmd.append("--full_tree") + if force: + cmd.append("--force") + if write_single_copy_genes: + cmd.append("--write_single_copy_genes") + if write_raw_log: + cmd.append("--write_raw_log") + if write_bins: + cmd.append("--write_bins") + if attach_metadata: + cmd.append("--attach_metadata") + if custom_taxonomy_file: + cmd.extend(["--custom_taxonomy_file", str(custom_taxonomy_file)]) + if skip_ani_cache: + cmd.append("--skip_ani_cache") + if tmpdir: + cmd.extend(["--tmpdir", str(tmpdir)]) + if debug: + cmd.append("--debug") + if verbose: + cmd.append("-v") + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + output_files = _get_output_files(out_dir) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"GTDB-Tk classify_wf failed with exit code {e.returncode}", + "output_files": [], + } + + +@mcp.tool() +def de_novo_wf( + genome_dir: Path, + outgroup_taxa: str, + out_dir: Path, + batchfile: Optional[Path] = None, + extension: str = "fna", + protein_dir: Optional[Path] = None, + msa_file: Optional[Path] = None, + skip_gtdb_refs: bool = False, + cpus: int = 1, + min_perc_aa: float = 10.0, + prot_model: str = "WAG", + keep_intermediates: bool = False, + scratch_dir: Optional[Path] = None, + force: bool = False, + tmpdir: Optional[Path] = None, + debug: bool = False, + verbose: bool = False, +) -> Dict[str, Any]: + """ + Run the GTDB-Tk de novo workflow to create a custom reference tree. + + This workflow is for creating a de novo tree from a set of user-provided genomes + and an outgroup, which can be used for subsequent classification runs. + """ + # --- Input Validation --- + if not genome_dir.is_dir(): + raise ValueError(f"Input genome directory not found: {genome_dir}") + if not outgroup_taxa: + raise ValueError("outgroup_taxa must be specified.") + if batchfile and not batchfile.is_file(): + raise ValueError(f"Batch file not found: {batchfile}") + if protein_dir and not protein_dir.is_dir(): + raise ValueError(f"Protein directory not found: {protein_dir}") + if msa_file and not msa_file.is_file(): + raise ValueError(f"MSA file not found: {msa_file}") + + if not cpus > 0: + raise ValueError("cpus must be a positive integer") + if not min_perc_aa >= 0: + raise ValueError("min_perc_aa must be non-negative") + + valid_prot_models = ["LG", "WAG", "JTT", "DAYHOFF"] + if prot_model not in valid_prot_models: + raise ValueError(f"prot_model must be one of {valid_prot_models}") + + # --- Command Construction --- + cmd = [ + "gtdbtk", "de_novo_wf", + "--genome_dir", str(genome_dir), + "--outgroup_taxa", outgroup_taxa, + "--out_dir", str(out_dir), + "--extension", extension, + "--cpus", str(cpus), + "--min_perc_aa", str(min_perc_aa), + "--prot_model", prot_model, + ] + + if batchfile: + cmd.extend(["--batchfile", str(batchfile)]) + if protein_dir: + cmd.extend(["--protein_dir", str(protein_dir)]) + if msa_file: + cmd.extend(["--msa_file", str(msa_file)]) + if skip_gtdb_refs: + cmd.append("--skip_gtdb_refs") + if keep_intermediates: + cmd.append("--keep_intermediates") + if scratch_dir: + cmd.extend(["--scratch_dir", str(scratch_dir)]) + if force: + cmd.append("--force") + if tmpdir: + cmd.extend(["--tmpdir", str(tmpdir)]) + if debug: + cmd.append("--debug") + if verbose: + cmd.append("-v") + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + # De novo workflow produces different outputs, primarily a tree file + out_dir.mkdir(parents=True, exist_ok=True) + output_files = [str(out_dir / "gtdbtk.denovo.tree.newick")] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"GTDB-Tk de_novo_wf failed with exit code {e.returncode}", + "output_files": [], + } + + +@mcp.tool() +def infer( + msa_file: Path, + out_dir: Path, + gtdbtk_classification_file: Optional[Path] = None, + reference_tree: Optional[Path] = None, + classification_file: Optional[Path] = None, + min_perc_aa: float = 10.0, + radius: int = 5, + pplacer_cpus: int = 1, + unaligned_only: bool = False, + keep_intermediates: bool = False, + scratch_dir: Optional[Path] = None, + cpus: int = 1, + min_mem: int = 4, + full_tree: bool = False, + force: bool = False, + tmpdir: Optional[Path] = None, + debug: bool = False, + verbose: bool = False, +) -> Dict[str, Any]: + """ + Infer taxonomic classification of genomes using a multiple sequence alignment. + + This is a lower-level command, typically part of the classify_wf, that performs + the phylogenetic placement and taxonomic inference steps. + """ + # --- Input Validation --- + if not msa_file.is_file(): + raise ValueError(f"MSA file not found: {msa_file}") + if gtdbtk_classification_file and not gtdbtk_classification_file.is_file(): + raise ValueError(f"GTDB-Tk classification file not found: {gtdbtk_classification_file}") + if reference_tree and not reference_tree.is_file(): + raise ValueError(f"Reference tree file not found: {reference_tree}") + if classification_file and not classification_file.is_file(): + raise ValueError(f"Classification file not found: {classification_file}") + + if not min_perc_aa >= 0: + raise ValueError("min_perc_aa must be non-negative") + if not cpus > 0: + raise ValueError("cpus must be a positive integer") + if not pplacer_cpus > 0: + raise ValueError("pplacer_cpus must be a positive integer") + if not min_mem > 0: + raise ValueError("min_mem must be a positive integer") + + # --- Command Construction --- + cmd = [ + "gtdbtk", "infer", + "--msa_file", str(msa_file), + "--out_dir", str(out_dir), + "--min_perc_aa", str(min_perc_aa), + "--radius", str(radius), + "--pplacer_cpus", str(pplacer_cpus), + "--cpus", str(cpus), + "--min_mem", str(min_mem), + ] + + if gtdbtk_classification_file: + cmd.extend(["--gtdbtk_classification_file", str(gtdbtk_classification_file)]) + if reference_tree: + cmd.extend(["--reference_tree", str(reference_tree)]) + if classification_file: + cmd.extend(["--classification_file", str(classification_file)]) + if unaligned_only: + cmd.append("--unaligned_only") + if keep_intermediates: + cmd.append("--keep_intermediates") + if scratch_dir: + cmd.extend(["--scratch_dir", str(scratch_dir)]) + if full_tree: + cmd.append("--full_tree") + if force: + cmd.append("--force") + if tmpdir: + cmd.extend(["--tmpdir", str(tmpdir)]) + if debug: + cmd.append("--debug") + if verbose: + cmd.append("-v") + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + output_files = _get_output_files(out_dir) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"GTDB-Tk infer failed with exit code {e.returncode}", + "output_files": [], + } + + +@mcp.tool() +def align( + genome_dir: Path, + out_dir: Path, + batchfile: Optional[Path] = None, + extension: str = "fna", + protein_dir: Optional[Path] = None, + mash_db: Optional[Path] = None, + skip_gtdb_refs: bool = False, + cpus: int = 1, + genes: bool = False, + no_mash: bool = False, + mash_d: int = 10000, + force: bool = False, + keep_intermediates: bool = False, + scratch_dir: Optional[Path] = None, + tmpdir: Optional[Path] = None, + debug: bool = False, + verbose: bool = False, +) -> Dict[str, Any]: + """ + Identify and align marker genes from a set of genomes. + + This is a lower-level command, typically part of the classify_wf, that performs + gene calling, marker gene identification, and alignment. + """ + # --- Input Validation --- + if not genome_dir.is_dir(): + raise ValueError(f"Input genome directory not found: {genome_dir}") + if batchfile and not batchfile.is_file(): + raise ValueError(f"Batch file not found: {batchfile}") + if protein_dir and not protein_dir.is_dir(): + raise ValueError(f"Protein directory not found: {protein_dir}") + if mash_db and not mash_db.is_file(): + raise ValueError(f"Custom Mash sketch file not found: {mash_db}") + + if not cpus > 0: + raise ValueError("cpus must be a positive integer") + if not mash_d > 0: + raise ValueError("mash_d must be a positive integer") + + # --- Command Construction --- + cmd = [ + "gtdbtk", "align", + "--genome_dir", str(genome_dir), + "--out_dir", str(out_dir), + "--extension", extension, + "--cpus", str(cpus), + "--mash_d", str(mash_d), + ] + + if batchfile: + cmd.extend(["--batchfile", str(batchfile)]) + if protein_dir: + cmd.extend(["--protein_dir", str(protein_dir)]) + if mash_db: + cmd.extend(["--mash_db", str(mash_db)]) + if skip_gtdb_refs: + cmd.append("--skip_gtdb_refs") + if genes: + cmd.append("--genes") + if no_mash: + cmd.append("--no_mash") + if force: + cmd.append("--force") + if keep_intermediates: + cmd.append("--keep_intermediates") + if scratch_dir: + cmd.extend(["--scratch_dir", str(scratch_dir)]) + if tmpdir: + cmd.extend(["--tmpdir", str(tmpdir)]) + if debug: + cmd.append("--debug") + if verbose: + cmd.append("-v") + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + # Align produces MSA files + out_dir.mkdir(parents=True, exist_ok=True) + output_files = [ + str(out_dir / "gtdbtk.bac120.user_msa.fasta"), + str(out_dir / "gtdbtk.ar53.user_msa.fasta"), + ] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"GTDB-Tk align failed with exit code {e.returncode}", + "output_files": [], + } + + +@mcp.tool() +def check_install( + full_check: bool = False, + tmpdir: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Check the GTDB-Tk installation and its dependencies. + """ + # --- Command Construction --- + cmd = ["gtdbtk", "check_install"] + if full_check: + cmd.append("--full_check") + if tmpdir: + cmd.extend(["--tmpdir", str(tmpdir)]) + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"GTDB-Tk check_install failed with exit code {e.returncode}", + "output_files": [], + } + + +@mcp.tool() +def download_data( + data_path: Optional[Path] = None, + symlink: bool = False, + wget: bool = False, + force: bool = False, +) -> Dict[str, Any]: + """ + Download the GTDB-Tk reference data. + """ + # --- Command Construction --- + cmd = ["gtdbtk", "download_data"] + if data_path: + cmd.extend(["--data_path", str(data_path)]) + if symlink: + cmd.append("--symlink") + if wget: + cmd.append("--wget") + if force: + cmd.append("--force") + + # --- Subprocess Execution --- + try: + # Note: This can be a very long-running process. + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"GTDB-Tk download_data failed with exit code {e.returncode}", + "output_files": [], + } + + +@mcp.tool() +def update_data() -> Dict[str, Any]: + """ + Update the GTDB-Tk reference data to the latest version. + This command assumes the GTDBTK_DATA_PATH environment variable is set. + """ + # --- Command Construction --- + cmd = ["gtdbtk", "update_data"] + + # --- Subprocess Execution --- + try: + # Note: This can be a very long-running process. + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"GTDB-Tk update_data failed with exit code {e.returncode}", + "output_files": [], + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gtdbtk/app/gtdbtk_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gtdbtk/app/gtdbtk_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..675cf5291046f333cd6c7c9106876e84acc1c828 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gtdbtk/app/gtdbtk_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gtdbtk/app/gtdbtk_server.py') +SERVER_NAME = 'biosci_gtdbtk' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gtdbtk/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gtdbtk/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gtdbtk/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gtdbtk/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gtdbtk/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..5360c0d4a5ede6951c59aaae292317ce8ac22aca --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gtdbtk/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-gtdbtk: + build: . + image: mcp-gtdbtk:latest + container_name: mcp-gtdbtk + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=gtdbtk + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gtdbtk/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gtdbtk/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c80f31ac047e22ad4444aeb1b08feab6697e135d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gtdbtk/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - gtdbtk + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gtdbtk/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gtdbtk/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gtdbtk/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_harpy/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_harpy/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2edda10ca7d458317d95614e371bbcc8d4c139b1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_harpy/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install harpy via conda (e.g., from bioconda) +RUN conda install -c bioconda harpy -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/harpy_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/harpy_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/harpy_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_harpy/app/harpy_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_harpy/app/harpy_server.py new file mode 100644 index 0000000000000000000000000000000000000000..29806255c5aaafa8860a735cb028d7b9c5beb80b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_harpy/app/harpy_server.py @@ -0,0 +1,853 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# MCP-compliant tool definitions for harpy + +# --- Data Processing Subcommands --- + +@mcp.tool() +def align( + reads_r1: Path, + reads_r2: Path, + reference: Path, + sample: str, + output_dir: Path, + threads: int = 8, + dry_run: bool = False, + setup: bool = False, +) -> dict: + """ + Aligns sample sequences to a reference genome assembly using Harpy. + + This function wraps the 'harpy align' command. It takes paired-end reads, + a reference genome, and a sample name to produce alignment files. + Note: Parameters are inferred from the tool's high-level documentation. + """ + if not reads_r1.is_file(): + raise FileNotFoundError(f"Input read file R1 not found: {reads_r1}") + if not reads_r2.is_file(): + raise FileNotFoundError(f"Input read file R2 not found: {reads_r2}") + if not reference.is_file(): + raise FileNotFoundError(f"Reference genome file not found: {reference}") + if threads <= 0: + raise ValueError("Threads must be a positive integer.") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "harpy", "align", + "--reads1", str(reads_r1), + "--reads2", str(reads_r2), + "--reference", str(reference), + "--sample", sample, + "--output", str(output_dir), + "--threads", str(threads), + ] + if dry_run: + cmd.append("--dry-run") + if setup: + cmd.append("--setup") + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + # Assuming the primary output is a BAM file named after the sample + output_bam = output_dir / f"{sample}.bam" + output_files = [str(output_bam)] if output_bam.exists() else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy align command failed", + "return_code": e.returncode, + } + +@mcp.tool() +def assemble( + reads_r1: Path, + reads_r2: Path, + sample: str, + output_dir: Path, + threads: int = 8, + dry_run: bool = False, + setup: bool = False, +) -> dict: + """ + Creates a genome assembly from linked-reads using Harpy. + + This function wraps the 'harpy assemble' command. + Note: Parameters are inferred from the tool's high-level documentation. + """ + if not reads_r1.is_file(): + raise FileNotFoundError(f"Input read file R1 not found: {reads_r1}") + if not reads_r2.is_file(): + raise FileNotFoundError(f"Input read file R2 not found: {reads_r2}") + if threads <= 0: + raise ValueError("Threads must be a positive integer.") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "harpy", "assemble", + "--reads1", str(reads_r1), + "--reads2", str(reads_r2), + "--sample", sample, + "--output", str(output_dir), + "--threads", str(threads), + ] + if dry_run: + cmd.append("--dry-run") + if setup: + cmd.append("--setup") + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + # Assuming the primary output is a FASTA file + output_fasta = output_dir / f"{sample}_assembly.fasta" + output_files = [str(output_fasta)] if output_fasta.exists() else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy assemble command failed", + "return_code": e.returncode, + } + +@mcp.tool() +def deconvolve( + bam: Path, + output_dir: Path, + threads: int = 8, + dry_run: bool = False, + setup: bool = False, +) -> dict: + """ + Resolves barcode sharing in unrelated molecules from a BAM file. + + This function wraps the 'harpy deconvolve' command. + Note: Parameters are inferred from the tool's high-level documentation. + """ + if not bam.is_file(): + raise FileNotFoundError(f"Input BAM file not found: {bam}") + if threads <= 0: + raise ValueError("Threads must be a positive integer.") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "harpy", "deconvolve", + "--bam", str(bam), + "--output", str(output_dir), + "--threads", str(threads), + ] + if dry_run: + cmd.append("--dry-run") + if setup: + cmd.append("--setup") + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + # Assuming output is a new BAM file + output_bam = output_dir / f"{bam.stem}.deconvolved.bam" + output_files = [str(output_bam)] if output_bam.exists() else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy deconvolve command failed", + "return_code": e.returncode, + } + +@mcp.tool() +def demultiplex( + reads_r1: Path, + reads_r2: Path, + barcodes: Path, + output_dir: Path, + threads: int = 8, + dry_run: bool = False, + setup: bool = False, +) -> dict: + """ + Demultiplexes haplotagged FASTQ files using Harpy. + + This function wraps the 'harpy demultiplex' command. + Note: Parameters are inferred from the tool's high-level documentation. + """ + if not reads_r1.is_file(): + raise FileNotFoundError(f"Input read file R1 not found: {reads_r1}") + if not reads_r2.is_file(): + raise FileNotFoundError(f"Input read file R2 not found: {reads_r2}") + if not barcodes.is_file(): + raise FileNotFoundError(f"Barcodes file not found: {barcodes}") + if threads <= 0: + raise ValueError("Threads must be a positive integer.") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "harpy", "demultiplex", + "--reads1", str(reads_r1), + "--reads2", str(reads_r2), + "--barcodes", str(barcodes), + "--output", str(output_dir), + "--threads", str(threads), + ] + if dry_run: + cmd.append("--dry-run") + if setup: + cmd.append("--setup") + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + # Output is likely a set of demultiplexed FASTQ files + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(p) for p in output_dir.glob("*.fastq.gz")], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy demultiplex command failed", + "return_code": e.returncode, + } + +@mcp.tool() +def impute( + vcf: Path, + bam: Path, + reference: Path, + output_dir: Path, + threads: int = 8, + dry_run: bool = False, + setup: bool = False, +) -> dict: + """ + Imputes variant genotypes from alignments using Harpy. + + This function wraps the 'harpy impute' command. + Note: Parameters are inferred from the tool's high-level documentation. + """ + if not vcf.is_file(): + raise FileNotFoundError(f"Input VCF file not found: {vcf}") + if not bam.is_file(): + raise FileNotFoundError(f"Input BAM file not found: {bam}") + if not reference.is_file(): + raise FileNotFoundError(f"Reference genome file not found: {reference}") + if threads <= 0: + raise ValueError("Threads must be a positive integer.") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "harpy", "impute", + "--vcf", str(vcf), + "--bam", str(bam), + "--reference", str(reference), + "--output", str(output_dir), + "--threads", str(threads), + ] + if dry_run: + cmd.append("--dry-run") + if setup: + cmd.append("--setup") + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + output_vcf = output_dir / f"{vcf.stem}.imputed.vcf.gz" + output_files = [str(output_vcf)] if output_vcf.exists() else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy impute command failed", + "return_code": e.returncode, + } + +@mcp.tool() +def metassembly( + reads_r1: Path, + reads_r2: Path, + sample: str, + output_dir: Path, + threads: int = 8, + dry_run: bool = False, + setup: bool = False, +) -> dict: + """ + Creates a metagenome assembly from linked-reads using Harpy. + + This function wraps the 'harpy metassembly' command. + Note: Parameters are inferred from the tool's high-level documentation. + """ + if not reads_r1.is_file(): + raise FileNotFoundError(f"Input read file R1 not found: {reads_r1}") + if not reads_r2.is_file(): + raise FileNotFoundError(f"Input read file R2 not found: {reads_r2}") + if threads <= 0: + raise ValueError("Threads must be a positive integer.") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "harpy", "metassembly", + "--reads1", str(reads_r1), + "--reads2", str(reads_r2), + "--sample", sample, + "--output", str(output_dir), + "--threads", str(threads), + ] + if dry_run: + cmd.append("--dry-run") + if setup: + cmd.append("--setup") + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + output_fasta = output_dir / f"{sample}_metassembly.fasta" + output_files = [str(output_fasta)] if output_fasta.exists() else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy metassembly command failed", + "return_code": e.returncode, + } + +@mcp.tool() +def phase( + vcf: Path, + bam: Path, + reference: Path, + output_dir: Path, + threads: int = 8, + dry_run: bool = False, + setup: bool = False, +) -> dict: + """ + Phases SNPs into haplotypes using Harpy. + + This function wraps the 'harpy phase' command. + Note: Parameters are inferred from the tool's high-level documentation. + """ + if not vcf.is_file(): + raise FileNotFoundError(f"Input VCF file not found: {vcf}") + if not bam.is_file(): + raise FileNotFoundError(f"Input BAM file not found: {bam}") + if not reference.is_file(): + raise FileNotFoundError(f"Reference genome file not found: {reference}") + if threads <= 0: + raise ValueError("Threads must be a positive integer.") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "harpy", "phase", + "--vcf", str(vcf), + "--bam", str(bam), + "--reference", str(reference), + "--output", str(output_dir), + "--threads", str(threads), + ] + if dry_run: + cmd.append("--dry-run") + if setup: + cmd.append("--setup") + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + output_vcf = output_dir / f"{vcf.stem}.phased.vcf.gz" + output_files = [str(output_vcf)] if output_vcf.exists() else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy phase command failed", + "return_code": e.returncode, + } + +@mcp.tool() +def qc( + reads_r1: Path, + reads_r2: Path, + sample: str, + output_dir: Path, + threads: int = 8, + dry_run: bool = False, + setup: bool = False, +) -> dict: + """ + Performs adapter removal, quality filtering, etc., on FASTQ files. + + This function wraps the 'harpy qc' command. + Note: Parameters are inferred from the tool's high-level documentation. + """ + if not reads_r1.is_file(): + raise FileNotFoundError(f"Input read file R1 not found: {reads_r1}") + if not reads_r2.is_file(): + raise FileNotFoundError(f"Input read file R2 not found: {reads_r2}") + if threads <= 0: + raise ValueError("Threads must be a positive integer.") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "harpy", "qc", + "--reads1", str(reads_r1), + "--reads2", str(reads_r2), + "--sample", sample, + "--output", str(output_dir), + "--threads", str(threads), + ] + if dry_run: + cmd.append("--dry-run") + if setup: + cmd.append("--setup") + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + # Assuming output is a pair of trimmed FASTQ files + out_r1 = output_dir / f"{sample}_R1.trimmed.fastq.gz" + out_r2 = output_dir / f"{sample}_R2.trimmed.fastq.gz" + output_files = [] + if out_r1.exists(): + output_files.append(str(out_r1)) + if out_r2.exists(): + output_files.append(str(out_r2)) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy qc command failed", + "return_code": e.returncode, + } + +@mcp.tool() +def simulate( + reference: Path, + output_dir: Path, + seed: Optional[int] = None, + dry_run: bool = False, + setup: bool = False, +) -> dict: + """ + Simulates genomic variants or linked reads using Harpy. + + This function wraps the 'harpy simulate' command. + Note: Parameters are inferred from the tool's high-level documentation. + """ + if not reference.is_file(): + raise FileNotFoundError(f"Reference genome file not found: {reference}") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "harpy", "simulate", + "--reference", str(reference), + "--output", str(output_dir), + ] + if seed is not None: + cmd.extend(["--seed", str(seed)]) + if dry_run: + cmd.append("--dry-run") + if setup: + cmd.append("--setup") + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(p) for p in output_dir.iterdir()], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy simulate command failed", + "return_code": e.returncode, + } + +@mcp.tool() +def snp( + bam: Path, + reference: Path, + output_dir: Path, + threads: int = 8, + dry_run: bool = False, + setup: bool = False, +) -> dict: + """ + Calls SNPs and small indels from alignments using Harpy. + + This function wraps the 'harpy snp' command. + Note: Parameters are inferred from the tool's high-level documentation. + """ + if not bam.is_file(): + raise FileNotFoundError(f"Input BAM file not found: {bam}") + if not reference.is_file(): + raise FileNotFoundError(f"Reference genome file not found: {reference}") + if threads <= 0: + raise ValueError("Threads must be a positive integer.") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "harpy", "snp", + "--bam", str(bam), + "--reference", str(reference), + "--output", str(output_dir), + "--threads", str(threads), + ] + if dry_run: + cmd.append("--dry-run") + if setup: + cmd.append("--setup") + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + output_vcf = output_dir / f"{bam.stem}.vcf.gz" + output_files = [str(output_vcf)] if output_vcf.exists() else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy snp command failed", + "return_code": e.returncode, + } + +@mcp.tool() +def sv( + bam: Path, + reference: Path, + output_dir: Path, + threads: int = 8, + dry_run: bool = False, + setup: bool = False, +) -> dict: + """ + Calls large structural variants (inversions, deletions, duplications). + + This function wraps the 'harpy sv' command. + Note: Parameters are inferred from the tool's high-level documentation. + """ + if not bam.is_file(): + raise FileNotFoundError(f"Input BAM file not found: {bam}") + if not reference.is_file(): + raise FileNotFoundError(f"Reference genome file not found: {reference}") + if threads <= 0: + raise ValueError("Threads must be a positive integer.") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "harpy", "sv", + "--bam", str(bam), + "--reference", str(reference), + "--output", str(output_dir), + "--threads", str(threads), + ] + if dry_run: + cmd.append("--dry-run") + if setup: + cmd.append("--setup") + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + output_vcf = output_dir / f"{bam.stem}.sv.vcf.gz" + output_files = [str(output_vcf)] if output_vcf.exists() else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy sv command failed", + "return_code": e.returncode, + } + +# --- Other and Troubleshooting Subcommands --- + +@mcp.tool() +def template( + workflow: str, + output_dir: Path, + hpc_profile: Optional[str] = None, +) -> dict: + """ + Creates template files and HPC configs for Harpy workflows. + + This function wraps the 'harpy template' command. + """ + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = ["harpy", "template", workflow, "--output", str(output_dir)] + if hpc_profile: + cmd.extend(["--hpc-profile", hpc_profile]) + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(p) for p in output_dir.iterdir()], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy template command failed", + "return_code": e.returncode, + } + +@mcp.tool() +def deps(force: bool = False) -> dict: + """ + Locally installs workflow dependencies for Harpy. + + This function wraps the 'harpy deps' command. + """ + cmd = ["harpy", "deps"] + if force: + cmd.append("--force") + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy deps command failed", + "return_code": e.returncode, + } + +@mcp.tool() +def diagnose(workflow_dir: Path) -> dict: + """ + Attempts to resolve errors in a failed Harpy workflow. + + This function wraps the 'harpy diagnose' command. + """ + if not workflow_dir.is_dir(): + raise NotADirectoryError(f"Workflow directory not found: {workflow_dir}") + + cmd = ["harpy", "diagnose", str(workflow_dir)] + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy diagnose command failed", + "return_code": e.returncode, + } + +@mcp.tool() +def resume(workflow_dir: Path) -> dict: + """ + Continues an incomplete Harpy workflow. + + This function wraps the 'harpy resume' command. + """ + if not workflow_dir.is_dir(): + raise NotADirectoryError(f"Workflow directory not found: {workflow_dir}") + + cmd = ["harpy", "resume", str(workflow_dir)] + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy resume command failed", + "return_code": e.returncode, + } + +@mcp.tool() +def validate(input_file: Path, file_type: str) -> dict: + """ + Runs various format checks for FASTQ, BAM, and other files. + + This function wraps the 'harpy validate' command. + """ + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + valid_types = ["fastq", "bam", "vcf"] + if file_type.lower() not in valid_types: + raise ValueError(f"file_type must be one of {valid_types}") + + cmd = ["harpy", "validate", file_type, str(input_file)] + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy validate command failed", + "return_code": e.returncode, + } + +@mcp.tool() +def view(workflow: str, output_file: Optional[Path] = None) -> dict: + """ + Views a workflow's components, such as its DAG. + + This function wraps the 'harpy view' command. + """ + cmd = ["harpy", "view", workflow] + if output_file: + cmd.extend(["--output", str(output_file)]) + + 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 [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Harpy view command failed", + "return_code": e.returncode, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_harpy/app/harpy_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_harpy/app/harpy_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..196bdd7c1175745bb1cb4b26db4a3d3373cbc18e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_harpy/app/harpy_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_harpy/app/harpy_server.py') +SERVER_NAME = 'biosci_harpy' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_harpy/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_harpy/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_harpy/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_harpy/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_harpy/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..ffd8498021f6e49151afb302a037f6f8aa7de3e7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_harpy/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-harpy: + build: . + image: mcp-harpy:latest + container_name: mcp-harpy + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=harpy + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_harpy/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_harpy/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..297e3c0ea533df263cfa11e50be4ef5ab3382e80 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_harpy/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - harpy + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_harpy/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_harpy/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_harpy/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hhsuite/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hhsuite/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..f514064f1919cc8cf7fc25cfa511c670c740a946 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hhsuite/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install hhsuite via conda (e.g., from bioconda) +RUN conda install -c bioconda hhsuite -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/hhsuite_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/hhsuite_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/hhsuite_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hhsuite/app/hhsuite_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hhsuite/app/hhsuite_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f45508a2a69b596f80f7cf35da121fa5b84c5e27 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hhsuite/app/hhsuite_server.py @@ -0,0 +1,449 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# @mcp.tool() - This decorator is commented out as per the instructions. +def hhblits( + input_file: Path, + database: Path, + output_file: Optional[Path] = None, + output_a3m: Optional[Path] = None, + output_hhm: Optional[Path] = None, + output_psi: Optional[Path] = None, + n_iterations: int = 2, + e_value_inclusion: float = 0.001, + e_value_report: float = 1.0, + min_query_coverage: int = 20, + min_seq_id_msa: int = 0, + max_seq_id_msa: int = 90, + min_coverage_msa: int = 0, + min_query_id_msa: int = 0, + min_score_per_col: float = -20.0, + neff: Optional[float] = None, + neff_max: float = 20.0, + max_filter: int = 20000, + diff: int = 1, + realign_max: int = 500, + mact: float = 0.35, + max_input_sequences: int = 1000001, + show_all_sequences: bool = False, + show_alt_alignments: int = 1, + show_all_hits: bool = False, + alignment_width: int = 80, + db_load_mode: int = 0, + db_presort_mode: int = 0, + input_format: Optional[str] = None, + tags: bool = False, + uppercase: bool = False, + local_alignment_file: Optional[Path] = None, + ss_scoring_mode: int = 2, + subst_matrix_score: int = 1, + avg_subst_score: int = 1, + correlation_score: int = 1, + ss_score_weight: float = 0.11, + subst_matrix_weight: float = 1.0, + avg_subst_weight: float = 0.6, + correlation_weight: float = 0.81, + gapb: float = 1.0, + gapc: float = 1.0, + gapd: float = 1.0, + gape: float = 1.0, + gapf: float = 1.0, + gapi: float = 1.0, + gapj: float = 1.0, + gapt: float = 1.0, + alignment_mode: int = 0, + global_alignment: bool = False, + local_alignment: bool = False, + calibrated_alignment: bool = False, + score_offset: float = 0.0, + exclude_cols: Optional[str] = None, + pca: float = 1.0, + pcb: float = 1.5, + pcf: float = 1.0, + pseudocount_mode: int = 0, + no_realign: bool = False, + context_file: Optional[Path] = None, + cpu: int = 2, + verbose: int = 2, + max_res: int = 10000, +): + """ + Run HHblits for sensitive sequence searching against a sequence database. + + HHblits is a tool for iterative sequence searching that is much faster than + PSI-BLAST but with comparable sensitivity. It represents both query and + database sequences by profile hidden Markov models (HMMs). + """ + # Input validation + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if local_alignment_file and not local_alignment_file.is_file(): + raise FileNotFoundError(f"Local alignment file not found: {local_alignment_file}") + if context_file and not context_file.is_file(): + raise FileNotFoundError(f"Context file not found: {context_file}") + + if not (0 <= diff <= 3): + raise ValueError("diff must be between 0 and 3.") + if not (0 <= db_load_mode <= 2): + raise ValueError("db_load_mode must be 0, 1, or 2.") + if not (0 <= db_presort_mode <= 2): + raise ValueError("db_presort_mode must be 0, 1, or 2.") + if not (0 <= ss_scoring_mode <= 2): + raise ValueError("ss_scoring_mode must be 0, 1, or 2.") + if not (0 <= alignment_mode <= 3): + raise ValueError("alignment_mode must be between 0 and 3.") + if not (0 <= pseudocount_mode <= 1): + raise ValueError("pseudocount_mode must be 0 or 1.") + if not (0 <= verbose <= 2): + raise ValueError("verbose must be 0, 1, or 2.") + if sum([global_alignment, local_alignment, calibrated_alignment]) > 1: + raise ValueError("Only one of global_alignment, local_alignment, or calibrated_alignment can be set.") + + # Command construction + cmd = ["hhblits", "-i", str(input_file), "-d", str(database)] + + # Handle default output file naming + if output_file is None: + output_file = input_file.with_suffix(".hhr") + cmd.extend(["-o", str(output_file)]) + + output_files = [str(output_file)] + + if output_a3m: + cmd.extend(["-oa3m", str(output_a3m)]) + output_files.append(str(output_a3m)) + if output_hhm: + cmd.extend(["-ohhm", str(output_hhm)]) + output_files.append(str(output_hhm)) + if output_psi: + cmd.extend(["-opsi", str(output_psi)]) + output_files.append(str(output_psi)) + if max_res != 10000: + cmd.extend(["-maxres", str(max_res)]) + if n_iterations != 2: + cmd.extend(["-n", str(n_iterations)]) + if e_value_inclusion != 0.001: + cmd.extend(["-e", str(e_value_inclusion)]) + if e_value_report != 1.0: + cmd.extend(["-E", str(e_value_report)]) + if min_query_coverage != 20: + cmd.extend(["-p", str(min_query_coverage)]) + if min_seq_id_msa != 0: + cmd.extend(["-s", str(min_seq_id_msa)]) + if max_seq_id_msa != 90: + cmd.extend(["-id", str(max_seq_id_msa)]) + if min_coverage_msa != 0: + cmd.extend(["-cov", str(min_coverage_msa)]) + if min_query_id_msa != 0: + cmd.extend(["-qid", str(min_query_id_msa)]) + if min_score_per_col != -20.0: + cmd.extend(["-qsc", str(min_score_per_col)]) + if neff is not None: + cmd.extend(["-neff", str(neff)]) + if neff_max != 20.0: + cmd.extend(["-neffmax", str(neff_max)]) + if max_filter != 20000: + cmd.extend(["-maxfilt", str(max_filter)]) + if diff != 1: + cmd.extend(["-diff", str(diff)]) + if realign_max != 500: + cmd.extend(["-realign_max", str(realign_max)]) + if mact != 0.35: + cmd.extend(["-mact", str(mact)]) + if max_input_sequences != 1000001: + cmd.extend(["-maxseq", str(max_input_sequences)]) + if show_all_sequences: + cmd.append("-all") + if show_alt_alignments != 1: + cmd.extend(["-alt", str(show_alt_alignments)]) + if show_all_hits: + cmd.append("-show_all") + if alignment_width != 80: + cmd.extend(["-aliw", str(alignment_width)]) + if db_load_mode != 0: + cmd.extend(["-db_load_mode", str(db_load_mode)]) + if db_presort_mode != 0: + cmd.extend(["-db_presort_mode", str(db_presort_mode)]) + if input_format: + cmd.extend(["-M", input_format]) + if tags: + cmd.append("-tags") + if uppercase: + cmd.append("-uc") + if local_alignment_file: + cmd.extend(["-g", str(local_alignment_file)]) + if ss_scoring_mode != 2: + cmd.extend(["-ssm", str(ss_scoring_mode)]) + if subst_matrix_score != 1: + cmd.extend(["-sc", str(subst_matrix_score)]) + if avg_subst_score != 1: + cmd.extend(["-sa", str(avg_subst_score)]) + if correlation_score != 1: + cmd.extend(["-corr", str(correlation_score)]) + if ss_score_weight != 0.11: + cmd.extend(["-ssw", str(ss_score_weight)]) + if subst_matrix_weight != 1.0: + cmd.extend(["-scw", str(subst_matrix_weight)]) + if avg_subst_weight != 0.6: + cmd.extend(["-saw", str(avg_subst_weight)]) + if correlation_weight != 0.81: + cmd.extend(["-corrw", str(correlation_weight)]) + if gapb != 1.0: cmd.extend(["-gapb", str(gapb)]) + if gapc != 1.0: cmd.extend(["-gapc", str(gapc)]) + if gapd != 1.0: cmd.extend(["-gapd", str(gapd)]) + if gape != 1.0: cmd.extend(["-gape", str(gape)]) + if gapf != 1.0: cmd.extend(["-gapf", str(gapf)]) + if gapi != 1.0: cmd.extend(["-gapi", str(gapi)]) + if gapj != 1.0: cmd.extend(["-gapj", str(gapj)]) + if gapt != 1.0: cmd.extend(["-gapt", str(gapt)]) + if alignment_mode != 0: + cmd.extend(["-al", str(alignment_mode)]) + if global_alignment: cmd.append("-glob") + if local_alignment: cmd.append("-loc") + if calibrated_alignment: cmd.append("-cal") + if score_offset != 0.0: + cmd.extend(["-shift", str(score_offset)]) + if exclude_cols: + cmd.extend(["-excl", exclude_cols]) + if pca != 1.0: cmd.extend(["-pca", str(pca)]) + if pcb != 1.5: cmd.extend(["-pcb", str(pcb)]) + if pcf != 1.0: cmd.extend(["-pcf", str(pcf)]) + if pseudocount_mode != 0: + cmd.extend(["-pcm", str(pseudocount_mode)]) + if no_realign: + cmd.append("-norealign") + if context_file: + cmd.extend(["-contxt", str(context_file)]) + if cpu != 2: + cmd.extend(["-cpu", str(cpu)]) + if verbose != 2: + cmd.extend(["-v", str(verbose)]) + + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "HHblits failed", + "return_code": e.returncode, + } + +# @mcp.tool() - This decorator is commented out as per the instructions. +def hhsearch( + input_file: Path, + database: Path, + output_file: Optional[Path] = None, + output_a3m: Optional[Path] = None, + output_atab: Optional[Path] = None, + e_value_report: float = 1.0, + min_query_coverage: int = 20, + min_coverage: int = 0, + min_query_id: int = 0, + max_filter: int = 1000, + mact: float = 0.35, + max_input_sequences: int = 1000001, + show_all_sequences: bool = False, + show_alt_alignments: int = 1, + show_all_hits: bool = False, + alignment_width: int = 80, + db_load_mode: int = 0, + db_presort_mode: int = 0, + input_format: Optional[str] = None, + tags: bool = False, + uppercase: bool = False, + local_alignment_file: Optional[Path] = None, + ss_scoring_mode: int = 2, + subst_matrix_score: int = 1, + avg_subst_score: int = 1, + correlation_score: int = 1, + ss_score_weight: float = 0.11, + subst_matrix_weight: float = 1.0, + avg_subst_weight: float = 0.6, + correlation_weight: float = 0.81, + gapb: float = 1.0, + gapc: float = 1.0, + gapd: float = 1.0, + gape: float = 1.0, + gapf: float = 1.0, + gapi: float = 1.0, + gapj: float = 1.0, + gapt: float = 1.0, + alignment_mode: int = 0, + global_alignment: bool = False, + local_alignment: bool = False, + calibrated_alignment: bool = False, + score_offset: float = 0.0, + exclude_cols: Optional[str] = None, + pca: float = 1.0, + pcb: float = 1.5, + pcf: float = 1.0, + pseudocount_mode: int = 0, + no_realign: bool = False, + context_file: Optional[Path] = None, + cpu: int = 2, + verbose: int = 2, + max_res: int = 10000, +): + """ + Search a database of HMMs with a query sequence or HMM. + + HHsearch is a sensitive protein homology detection tool based on the + pairwise comparison of profile hidden Markov models (HMMs). + """ + # Input validation + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if local_alignment_file and not local_alignment_file.is_file(): + raise FileNotFoundError(f"Local alignment file not found: {local_alignment_file}") + if context_file and not context_file.is_file(): + raise FileNotFoundError(f"Context file not found: {context_file}") + + if not (0 <= db_load_mode <= 2): + raise ValueError("db_load_mode must be 0, 1, or 2.") + if not (0 <= db_presort_mode <= 2): + raise ValueError("db_presort_mode must be 0, 1, or 2.") + if not (0 <= ss_scoring_mode <= 2): + raise ValueError("ss_scoring_mode must be 0, 1, or 2.") + if not (0 <= alignment_mode <= 3): + raise ValueError("alignment_mode must be between 0 and 3.") + if not (0 <= pseudocount_mode <= 1): + raise ValueError("pseudocount_mode must be 0 or 1.") + if not (0 <= verbose <= 2): + raise ValueError("verbose must be 0, 1, or 2.") + if sum([global_alignment, local_alignment, calibrated_alignment]) > 1: + raise ValueError("Only one of global_alignment, local_alignment, or calibrated_alignment can be set.") + + # Command construction + cmd = ["hhsearch", "-i", str(input_file), "-d", str(database)] + + if output_file is None: + output_file = input_file.with_suffix(".hhr") + cmd.extend(["-o", str(output_file)]) + + output_files = [str(output_file)] + + if output_a3m: + cmd.extend(["-oa3m", str(output_a3m)]) + output_files.append(str(output_a3m)) + if output_atab: + cmd.extend(["-atab", str(output_atab)]) + output_files.append(str(output_atab)) + if max_res != 10000: + cmd.extend(["-maxres", str(max_res)]) + if e_value_report != 1.0: + cmd.extend(["-e", str(e_value_report)]) + if min_query_coverage != 20: + cmd.extend(["-p", str(min_query_coverage)]) + if min_coverage != 0: + cmd.extend(["-cov", str(min_coverage)]) + if min_query_id != 0: + cmd.extend(["-qid", str(min_query_id)]) + if max_filter != 1000: + cmd.extend(["-maxfilt", str(max_filter)]) + if mact != 0.35: + cmd.extend(["-mact", str(mact)]) + if max_input_sequences != 1000001: + cmd.extend(["-maxseq", str(max_input_sequences)]) + if show_all_sequences: + cmd.append("-all") + if show_alt_alignments != 1: + cmd.extend(["-alt", str(show_alt_alignments)]) + if show_all_hits: + cmd.append("-show_all") + if alignment_width != 80: + cmd.extend(["-aliw", str(alignment_width)]) + if db_load_mode != 0: + cmd.extend(["-db_load_mode", str(db_load_mode)]) + if db_presort_mode != 0: + cmd.extend(["-db_presort_mode", str(db_presort_mode)]) + if input_format: + cmd.extend(["-M", input_format]) + if tags: + cmd.append("-tags") + if uppercase: + cmd.append("-uc") + if local_alignment_file: + cmd.extend(["-g", str(local_alignment_file)]) + if ss_scoring_mode != 2: + cmd.extend(["-ssm", str(ss_scoring_mode)]) + if subst_matrix_score != 1: + cmd.extend(["-sc", str(subst_matrix_score)]) + if avg_subst_score != 1: + cmd.extend(["-sa", str(avg_subst_score)]) + if correlation_score != 1: + cmd.extend(["-corr", str(correlation_score)]) + if ss_score_weight != 0.11: + cmd.extend(["-ssw", str(ss_score_weight)]) + if subst_matrix_weight != 1.0: + cmd.extend(["-scw", str(subst_matrix_weight)]) + if avg_subst_weight != 0.6: + cmd.extend(["-saw", str(avg_subst_weight)]) + if correlation_weight != 0.81: + cmd.extend(["-corrw", str(correlation_weight)]) + if gapb != 1.0: cmd.extend(["-gapb", str(gapb)]) + if gapc != 1.0: cmd.extend(["-gapc", str(gapc)]) + if gapd != 1.0: cmd.extend(["-gapd", str(gapd)]) + if gape != 1.0: cmd.extend(["-gape", str(gape)]) + if gapf != 1.0: cmd.extend(["-gapf", str(gapf)]) + if gapi != 1.0: cmd.extend(["-gapi", str(gapi)]) + if gapj != 1.0: cmd.extend(["-gapj", str(gapj)]) + if gapt != 1.0: cmd.extend(["-gapt", str(gapt)]) + if alignment_mode != 0: + cmd.extend(["-al", str(alignment_mode)]) + if global_alignment: cmd.append("-glob") + if local_alignment: cmd.append("-loc") + if calibrated_alignment: cmd.append("-cal") + if score_offset != 0.0: + cmd.extend(["-shift", str(score_offset)]) + if exclude_cols: + cmd.extend(["-excl", exclude_cols]) + if pca != 1.0: cmd.extend(["-pca", str(pca)]) + if pcb != 1.5: cmd.extend(["-pcb", str(pcb)]) + if pcf != 1.0: cmd.extend(["-pcf", str(pcf)]) + if pseudocount_mode != 0: + cmd.extend(["-pcm", str(pseudocount_mode)]) + if no_realign: + cmd.append("-norealign") + if context_file: + cmd.extend(["-contxt", str(context_file)]) + if cpu != 2: + cmd.extend(["-cpu", str(cpu)]) + if verbose != 2: + cmd.extend(["-v", str(verbose)]) + + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "HHsearch failed", + "return_code": e.returncode, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hhsuite/app/hhsuite_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hhsuite/app/hhsuite_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..11ef2bb18e77e4a04635d9148caa4aa12335ff75 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hhsuite/app/hhsuite_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hhsuite/app/hhsuite_server.py') +SERVER_NAME = 'biosci_hhsuite' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hhsuite/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hhsuite/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hhsuite/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hhsuite/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hhsuite/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..5dd2b663ebe1ba63c13a3490850a063babd44097 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hhsuite/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-hhsuite: + build: . + image: mcp-hhsuite:latest + container_name: mcp-hhsuite + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=hhsuite + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hhsuite/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hhsuite/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4bd9c79b390350a47889869622b1bd24b0333799 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hhsuite/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - hhsuite + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hhsuite/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hhsuite/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hhsuite/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hicexplorer/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hicexplorer/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..83409c9f7a291dca9975cd20229c0bdb2c16adc7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hicexplorer/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install hicexplorer via conda (e.g., from bioconda) +RUN conda install -c bioconda hicexplorer -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/hicexplorer_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/hicexplorer_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/hicexplorer_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hicexplorer/app/hicexplorer_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hicexplorer/app/hicexplorer_server.py new file mode 100644 index 0000000000000000000000000000000000000000..acacc6ab22024bf70a727d2b41a8fd1398f2cb7f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hicexplorer/app/hicexplorer_server.py @@ -0,0 +1,683 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# @mcp.tool() - This decorator is commented out as per the instructions. +# In a real MCP environment, it would be uncommented. + +def hic_build_matrix( + sam_files: List[Path], + out_file_name: Path, + bin_size: int = 10000, + threads: int = 4, + restriction_sequence: Optional[str] = None, + restriction_file: Optional[Path] = None, + dangling_ends: Optional[str] = None, + min_mapping_quality: int = 10, + keep_self_circles: bool = False, + keep_self_ligations: bool = False, + keep_duplicates: bool = False, + min_sequence_length: int = 25, + max_sequence_length: int = 0, + min_insert_size: int = 100, + max_insert_size: int = 0, + min_coverage: int = 0, + max_coverage: int = 1000, + stats_file: Optional[Path] = None, + qc_folder: Optional[Path] = None, + chromosome_sizes: Optional[Path] = None, + region: Optional[str] = None, + matrix_format: str = "cool", + tmp_dir: Optional[Path] = None, + enforce_sorted: bool = False, + short_read_names: bool = False, + center_read: bool = False, + quiet: bool = False, +) -> dict: + """ + Builds a Hi-C contact matrix from aligned sequencing reads. + + This tool processes SAM/BAM files from Hi-C experiments to create a binned contact matrix. + It includes steps for filtering reads based on quality, length, and ligation artifacts. + """ + # Input validation + if not all(f.is_file() for f in sam_files): + raise FileNotFoundError("One or more input SAM/BAM files not found.") + if restriction_file and not restriction_file.is_file(): + raise FileNotFoundError(f"Restriction file not found: {restriction_file}") + if chromosome_sizes and not chromosome_sizes.is_file(): + raise FileNotFoundError(f"Chromosome sizes file not found: {chromosome_sizes}") + if bin_size <= 0: + raise ValueError("bin_size must be a positive integer.") + if threads <= 0: + raise ValueError("threads must be a positive integer.") + if matrix_format not in ["cool", "h5"]: + raise ValueError("matrix_format must be either 'cool' or 'h5'.") + + cmd = [ + "hicBuildMatrix", + "--samFiles", *[str(f) for f in sam_files], + "--outFileName", str(out_file_name), + "--binSize", str(bin_size), + "--threads", str(threads), + "--minMappingQuality", str(min_mapping_quality), + "--minSequenceLength", str(min_sequence_length), + "--minInsertSize", str(min_insert_size), + "--minCoverage", str(min_coverage), + "--maxCoverage", str(max_coverage), + ] + + if restriction_sequence: + cmd.extend(["--restrictionSequence", restriction_sequence]) + if restriction_file: + cmd.extend(["--restrictionFile", str(restriction_file)]) + if dangling_ends: + cmd.extend(["--danglingEnds", dangling_ends]) + if keep_self_circles: + cmd.append("--keepSelfCircles") + if keep_self_ligations: + cmd.append("--keepSelfLigations") + if keep_duplicates: + cmd.append("--keepDuplicates") + if max_sequence_length > 0: + cmd.extend(["--maxSequenceLength", str(max_sequence_length)]) + if max_insert_size > 0: + cmd.extend(["--maxInsertSize", str(max_insert_size)]) + if stats_file: + cmd.extend(["--statsFile", str(stats_file)]) + if qc_folder: + cmd.extend(["--qcFolder", str(qc_folder)]) + if chromosome_sizes: + cmd.extend(["--chromosomeSizes", str(chromosome_sizes)]) + if region: + cmd.extend(["--region", region]) + if matrix_format: + cmd.extend(["--matrixFormat", matrix_format]) + if tmp_dir: + cmd.extend(["--tmpDir", str(tmp_dir)]) + if enforce_sorted: + cmd.append("--enforceSorted") + if short_read_names: + cmd.append("--shortReadNames") + if center_read: + cmd.append("--center_read") + if quiet: + cmd.append("--quiet") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + output_files = [str(out_file_name)] + if stats_file: + output_files.append(str(stats_file)) + if qc_folder: + # This is a directory, so we might list its contents or just return the path + output_files.append(str(qc_folder)) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"hicBuildMatrix failed with exit code {e.returncode}", + "output_files": [], + } + +# @mcp.tool() +def hic_correct_matrix( + matrix: Path, + out_file_name: Path, + correction_method: str, + filter_threshold: Optional[List[float]] = None, + chromosome: Optional[str] = None, + iterations: Optional[int] = None, + threads: int = 1, + dump_correction_factors: Optional[Path] = None, + load_correction_factors: Optional[Path] = None, + correction_factor_format: str = "hdf5", + version: bool = False, +) -> dict: + """ + Corrects a Hi-C matrix using methods like ICE or KR. + + This tool applies normalization to a raw Hi-C matrix to remove biases, + such as those from restriction enzyme sites, GC content, and mappability. + """ + # Input validation + if not matrix.is_file(): + raise FileNotFoundError(f"Input matrix file not found: {matrix}") + if correction_method not in ["ICE", "KR"]: + raise ValueError("correction_method must be either 'ICE' or 'KR'.") + if threads <= 0: + raise ValueError("threads must be a positive integer.") + if correction_factor_format not in ["hdf5", "tsv"]: + raise ValueError("correction_factor_format must be 'hdf5' or 'tsv'.") + + cmd = [ + "hicCorrectMatrix", + "correct", + "--matrix", str(matrix), + "--correctionMethod", correction_method, + "--outFileName", str(out_file_name), + "--threads", str(threads), + "--correctionFactorFormat", correction_factor_format, + ] + + if filter_threshold: + cmd.extend(["--filterThreshold", *[str(f) for f in filter_threshold]]) + if chromosome: + cmd.extend(["--chromosome", chromosome]) + if iterations is not None: + cmd.extend(["--iterations", str(iterations)]) + if dump_correction_factors: + cmd.extend(["--dumpCorrectionFactors", str(dump_correction_factors)]) + if load_correction_factors: + cmd.extend(["--loadCorrectionFactors", str(load_correction_factors)]) + if version: + cmd.append("--version") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + output_files = [str(out_file_name)] + if dump_correction_factors: + output_files.append(str(dump_correction_factors)) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"hicCorrectMatrix failed with exit code {e.returncode}", + "output_files": [], + } + +# @mcp.tool() +def hic_find_tads( + matrix: Path, + out_prefix: str, + correct_for_depth: bool = False, + min_depth: int = 10000, + max_depth: int = 100000, + step: int = 10000, + threshold_comparisons: float = 0.01, + delta: float = 0.01, + correct_for_multiple_testing: Optional[str] = None, + z_score_threshold: float = -2.0, + threads: int = 4, + tad_separation_threshold: float = 0.0, +) -> dict: + """ + Identifies Topologically Associating Domains (TADs) in a Hi-C matrix. + + This tool uses an insulation score-based method to find TAD boundaries and domains. + """ + # Input validation + if not matrix.is_file(): + raise FileNotFoundError(f"Input matrix file not found: {matrix}") + if threads <= 0: + raise ValueError("threads must be a positive integer.") + if correct_for_multiple_testing and correct_for_multiple_testing not in ["fdr", "bonferroni"]: + raise ValueError("correct_for_multiple_testing must be 'fdr' or 'bonferroni'.") + + cmd = [ + "hicFindTADs", + "--matrix", str(matrix), + "--outPrefix", out_prefix, + "--minDepth", str(min_depth), + "--maxDepth", str(max_depth), + "--step", str(step), + "--thresholdComparisons", str(threshold_comparisons), + "--delta", str(delta), + "--zscore_threshold", str(z_score_threshold), + "--threads", str(threads), + "--TAD_separation_threshold", str(tad_separation_threshold), + ] + + if correct_for_depth: + cmd.append("--correctForDepth") + if correct_for_multiple_testing: + cmd.extend(["--correctForMultipleTesting", correct_for_multiple_testing]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + # Expected output files based on prefix + output_files = [ + f"{out_prefix}_zscore_matrix.h5", + f"{out_prefix}_score.bm", + f"{out_prefix}_boundaries.bed", + f"{out_prefix}_domains.bed", + f"{out_prefix}_TAD_separation_score.bm", + ] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"hicFindTADs failed with exit code {e.returncode}", + "output_files": [], + } + +# @mcp.tool() +def hic_plot_matrix( + matrix: Path, + out_file_name: Path, + region: Optional[str] = None, + region2: Optional[str] = None, + chromosome: Optional[str] = None, + title: Optional[str] = None, + v_min: Optional[float] = None, + v_max: Optional[float] = None, + color_map: str = "RdYlBu_r", + log1p: bool = False, + clear_masked_bins: bool = False, + show_masked_bins: bool = False, + loops: Optional[Path] = None, + dpi: int = 300, + bigwig: Optional[Path] = None, + bigwig_y_min: Optional[float] = None, + bigwig_y_max: Optional[float] = None, + bigwig_color: str = "black", + per_chromosome: bool = False, + pca: Optional[Path] = None, + tads: Optional[Path] = None, + scale_factor: float = 1.0, +) -> dict: + """ + Plots a Hi-C contact matrix for a specified region. + + This tool generates a heatmap visualization of a Hi-C matrix, with options to overlay + TADs, loops, PCA eigenvectors (A/B compartments), and bigWig tracks. + """ + # Input validation + if not matrix.is_file(): + raise FileNotFoundError(f"Input matrix file not found: {matrix}") + if loops and not loops.is_file(): + raise FileNotFoundError(f"Loops file not found: {loops}") + if bigwig and not bigwig.is_file(): + raise FileNotFoundError(f"Bigwig file not found: {bigwig}") + if pca and not pca.is_file(): + raise FileNotFoundError(f"PCA file not found: {pca}") + if tads and not tads.is_file(): + raise FileNotFoundError(f"TADs file not found: {tads}") + if dpi <= 0: + raise ValueError("DPI must be a positive integer.") + + cmd = [ + "hicPlotMatrix", + "--matrix", str(matrix), + "--outFileName", str(out_file_name), + "--colorMap", color_map, + "--dpi", str(dpi), + "--scaleFactor", str(scale_factor), + ] + + if region: + cmd.extend(["--region", region]) + if region2: + cmd.extend(["--region2", region2]) + if chromosome: + cmd.extend(["--chromosome", chromosome]) + if title: + cmd.extend(["--title", title]) + if v_min is not None: + cmd.extend(["--vMin", str(v_min)]) + if v_max is not None: + cmd.extend(["--vMax", str(v_max)]) + if log1p: + cmd.append("--log1p") + if clear_masked_bins: + cmd.append("--clearMaskedBins") + if show_masked_bins: + cmd.append("--show_masked_bins") + if loops: + cmd.extend(["--loops", str(loops)]) + if bigwig: + cmd.extend(["--bigwig", str(bigwig)]) + if bigwig_y_min is not None: + cmd.extend(["--bigwig_y_min", str(bigwig_y_min)]) + if bigwig_y_max is not None: + cmd.extend(["--bigwig_y_max", str(bigwig_y_max)]) + cmd.extend(["--bigwig_color", bigwig_color]) + if per_chromosome: + cmd.append("--perChromosome") + if pca: + cmd.extend(["--pca", str(pca)]) + if tads: + cmd.extend(["--TADs", str(tads)]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_file_name)], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"hicPlotMatrix failed with exit code {e.returncode}", + "output_files": [], + } + +# @mcp.tool() +def hic_pca( + matrix: Path, + out_file_name_bigwig: Path, + out_file_name_bedgraph: Path, + format: str = "bigwig", + chromosomes: Optional[List[str]] = None, + number_of_eigenvectors: int = 1, + threads: int = 4, +) -> dict: + """ + Computes A/B compartments using Principal Component Analysis (PCA). + + This tool calculates the first few eigenvectors of the observed/expected-transformed + and Pearson-correlation-transformed Hi-C matrix to identify genomic compartments. + """ + # Input validation + if not matrix.is_file(): + raise FileNotFoundError(f"Input matrix file not found: {matrix}") + if format not in ["bigwig", "bedgraph"]: + raise ValueError("Format must be 'bigwig' or 'bedgraph'.") + if threads <= 0: + raise ValueError("threads must be a positive integer.") + if number_of_eigenvectors <= 0: + raise ValueError("number_of_eigenvectors must be a positive integer.") + + cmd = [ + "hicPCA", + "--matrix", str(matrix), + "--format", format, + "--numberOfEigenvectors", str(number_of_eigenvectors), + "--threads", str(threads), + ] + + if format == "bigwig": + cmd.extend(["--outputFileName", str(out_file_name_bigwig)]) + else: # bedgraph + cmd.extend(["--outputFileName", str(out_file_name_bedgraph)]) + + if chromosomes: + cmd.extend(["--chromosomes", *chromosomes]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + output_files = [] + if format == "bigwig": + output_files.append(str(out_file_name_bigwig)) + else: + output_files.append(str(out_file_name_bedgraph)) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"hicPCA failed with exit code {e.returncode}", + "output_files": [], + } + +# @mcp.tool() +def hic_compare_matrices( + matrices: List[Path], + out_file_name: Path, + operation: str, + region: Optional[str] = None, + chromosome: Optional[str] = None, + v_min: Optional[float] = None, + v_max: Optional[float] = None, + color_map: str = "jet", + log1p: bool = False, + plot_title: Optional[str] = None, + dpi: int = 300, +) -> dict: + """ + Compares two or more Hi-C matrices using various operations. + + This tool can compute the difference, ratio, or log2ratio between two matrices, + or find the mean of multiple matrices. The result is saved as a new matrix and a plot. + """ + # Input validation + if len(matrices) < 2: + raise ValueError("At least two matrices are required for comparison.") + if not all(f.is_file() for f in matrices): + raise FileNotFoundError("One or more input matrix files not found.") + if operation not in ["difference", "ratio", "log2ratio", "mean"]: + raise ValueError("Operation must be one of 'difference', 'ratio', 'log2ratio', 'mean'.") + if dpi <= 0: + raise ValueError("DPI must be a positive integer.") + + cmd = [ + "hicCompareMatrices", + "--matrices", *[str(m) for m in matrices], + "--outFileName", str(out_file_name), + "--operation", operation, + "--colorMap", color_map, + "--dpi", str(dpi), + ] + + if region: + cmd.extend(["--region", region]) + if chromosome: + cmd.extend(["--chromosome", chromosome]) + if v_min is not None: + cmd.extend(["--vMin", str(v_min)]) + if v_max is not None: + cmd.extend(["--vMax", str(v_max)]) + if log1p: + cmd.append("--log1p") + if plot_title: + cmd.extend(["--plotTitle", plot_title]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + # The tool creates a matrix (.h5 or .cool) and a plot (.png, .pdf, etc.) + # We return the path provided by the user, assuming the extension is correct. + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_file_name)], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"hicCompareMatrices failed with exit code {e.returncode}", + "output_files": [], + } + +# @mcp.tool() +def hic_convert_format( + in_file_name: Path, + out_file_name: Path, + in_format: str, + out_format: str, + threads: int = 1, + load_as_cooler: bool = False, + store_as_cooler: bool = False, +) -> dict: + """ + Converts Hi-C matrices between different formats. + + Supported formats include homer, hic-pro, cool, and h5 (HiCExplorer's format). + """ + # Input validation + if not in_file_name.is_file(): + raise FileNotFoundError(f"Input file not found: {in_file_name}") + supported_formats = ["homer", "hicpro", "cool", "h5"] + if in_format not in supported_formats: + raise ValueError(f"Input format '{in_format}' is not supported.") + if out_format not in supported_formats: + raise ValueError(f"Output format '{out_format}' is not supported.") + if threads <= 0: + raise ValueError("threads must be a positive integer.") + + cmd = [ + "hicConvertFormat", + "--inFileName", str(in_file_name), + "--outFileName", str(out_file_name), + "--inputFormat", in_format, + "--outputFormat", out_format, + "--threads", str(threads), + ] + + if load_as_cooler: + cmd.append("--load_as_cooler") + if store_as_cooler: + cmd.append("--store_as_cooler") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_file_name)], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"hicConvertFormat failed with exit code {e.returncode}", + "output_files": [], + } + +# @mcp.tool() +def hic_detect_loops( + matrix: Path, + out_file_name: Path, + window_size: int = 10, + peak_width: int = 6, + p_value_threshold: float = 0.01, + threads: int = 4, + chromosomes: Optional[List[str]] = None, +) -> dict: + """ + Detects chromatin loops in a Hi-C matrix using the HiCCUPS algorithm. + """ + # Input validation + if not matrix.is_file(): + raise FileNotFoundError(f"Input matrix file not found: {matrix}") + if threads <= 0: + raise ValueError("threads must be a positive integer.") + if window_size <= 0: + raise ValueError("window_size must be a positive integer.") + if peak_width <= 0: + raise ValueError("peak_width must be a positive integer.") + if not (0 < p_value_threshold <= 1): + raise ValueError("p_value_threshold must be between 0 and 1.") + + cmd = [ + "hicDetectLoops", + "--matrix", str(matrix), + "--outputFile", str(out_file_name), + "--windowSize", str(window_size), + "--peakWidth", str(peak_width), + "--pValue", str(p_value_threshold), + "--threads", str(threads), + ] + + if chromosomes: + cmd.extend(["--chromosomes", *chromosomes]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(out_file_name)], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"hicDetectLoops failed with exit code {e.returncode}", + "output_files": [], + } + +# @mcp.tool() +def hic_quick_qc( + bam_files: List[Path], + out_prefix: str, + threads: int = 4, + bin_size: int = 500000, + tmp_dir: Optional[Path] = None, + config_file: Optional[Path] = None, +) -> dict: + """ + Generates a comprehensive QC report for one or more Hi-C datasets. + """ + # Input validation + if not all(f.is_file() for f in bam_files): + raise FileNotFoundError("One or more input BAM files not found.") + if threads <= 0: + raise ValueError("threads must be a positive integer.") + if bin_size <= 0: + raise ValueError("bin_size must be a positive integer.") + if config_file and not config_file.is_file(): + raise FileNotFoundError(f"Config file not found: {config_file}") + + cmd = [ + "hicQuickQC", + "--bamfiles", *[str(f) for f in bam_files], + "--outPrefix", out_prefix, + "--threads", str(threads), + "--binSize", str(bin_size), + ] + + if tmp_dir: + cmd.extend(["--tmpdir", str(tmp_dir)]) + if config_file: + cmd.extend(["--configFile", str(config_file)]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + # The tool creates an HTML report and a folder with data + output_files = [f"{out_prefix}.html", f"{out_prefix}_qc"] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"hicQuickQC failed with exit code {e.returncode}", + "output_files": [], + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hicexplorer/app/hicexplorer_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hicexplorer/app/hicexplorer_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5cb26e5acbe9f7f97ab2c65ee7d2394cd771a3cc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hicexplorer/app/hicexplorer_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hicexplorer/app/hicexplorer_server.py') +SERVER_NAME = 'biosci_hicexplorer' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hicexplorer/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hicexplorer/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hicexplorer/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hicexplorer/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hicexplorer/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..94500985754dd7519d7f0306df52ae97de438691 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hicexplorer/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-hicexplorer: + build: . + image: mcp-hicexplorer:latest + container_name: mcp-hicexplorer + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=hicexplorer + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hicexplorer/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hicexplorer/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..84541a801de77aab09c16dd83dfc8b7cc14dec8d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hicexplorer/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - hicexplorer + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hicexplorer/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hicexplorer/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hicexplorer/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hifiasm/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hifiasm/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..29eab5646afbc222e4f45d971b3cca493fe33e35 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hifiasm/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install hifiasm via conda (e.g., from bioconda) +RUN conda install -c bioconda hifiasm -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/hifiasm_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/hifiasm_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/hifiasm_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hifiasm/app/hifiasm_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hifiasm/app/hifiasm_server.py new file mode 100644 index 0000000000000000000000000000000000000000..12a1e2ed5c5f63238fa311f7c76da690e4c54e34 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hifiasm/app/hifiasm_server.py @@ -0,0 +1,194 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict, Any + +@mcp.tool() +def hifiasm_assemble( + output_prefix: Path, + hifi_reads: Optional[List[Path]] = None, + ont_reads: Optional[Path] = None, + num_threads: int = 1, + hic_read1: Optional[Path] = None, + hic_read2: Optional[Path] = None, + paternal_yak: Optional[Path] = None, + maternal_yak: Optional[Path] = None, + ultralong_reads: Optional[Path] = None, + ignore_precomputed_overlaps: bool = False, + write_paf: bool = False, + write_ec_fasta: Optional[Path] = None, + disable_duplication_purging: bool = False, + trim_ends_bp: int = 0, + bloom_filter_level: Optional[int] = None, + enable_dual_scaffolding: bool = False, + telomere_motif: Optional[str] = None, +) -> Dict[str, Any]: + """ + Haplotype-resolved de novo assembler for PacBio HiFi reads, and also supports ONT reads, + Hi-C data, trio-binning, and ultra-long ONT reads for telomere-to-telomere assembly. + + Args: + output_prefix: Prefix for all output files (e.g., 'NA12878.asm'). The parent directory + must exist. + hifi_reads: List of input PacBio HiFi reads in FASTA/FASTQ format (gzipped or not). + Cannot be used with `ont_reads`. At least one of `hifi_reads` or `ont_reads` + must be provided. Each file must exist. + ont_reads: Input ONT simplex R10 reads in FASTQ format (gzipped or not). + Enables ONT assembly mode. Cannot be used with `hifi_reads`. + The file must exist. + num_threads: Number of CPU threads to use. Must be a positive integer. + hic_read1: First paired-end Hi-C read file (e.g., read1.fq.gz). + Requires `hic_read2` to also be provided. The file must exist. + hic_read2: Second paired-end Hi-C read file (e.g., read2.fq.gz). + Requires `hic_read1` to also be provided. The file must exist. + paternal_yak: Paternal k-mer count file generated by 'yak count'. + Requires `maternal_yak` to also be provided. The file must exist. + maternal_yak: Maternal k-mer count file generated by 'yak count'. + Requires `paternal_yak` to also be provided. The file must exist. + ultralong_reads: Input ultra-long ONT reads in FASTQ format (gzipped or not) + for telomere-to-telomere assembly. The file must exist. + ignore_precomputed_overlaps: If True, ignore precomputed overlaps and redo overlapping + from raw reads. + write_paf: If True, dump read overlaps in PAF format. + write_ec_fasta: Path to dump error corrected reads in FASTA format. + Use `/dev/null` to discard. If a file path, its parent directory must exist. + disable_duplication_purging: If True, disable haplotig duplication purging. + Recommended for inbred or homozygous genomes. + trim_ends_bp: Trim both ends of reads by this many base pairs. + Must be a non-negative integer. + bloom_filter_level: Bloom filter level for k-mer counting. + Use 0 for small genomes to disable (saves 16GB RAM). + Use 38 or 39 for very large genomes to save memory. + Must be a non-negative integer if specified. + enable_dual_scaffolding: If True, enable self-scaffolding to improve contiguity + for diploid genome assembly. + telomere_motif: Specify a telomere motif (e.g., 'CCCTAA') to preserve more telomeres + for T2T assemblies. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + command = ["hifiasm"] + output_files = [] + + # --- Input Validation and Command Construction --- + + # Validate output_prefix parent directory + if not output_prefix.parent.is_dir(): + raise ValueError(f"Output prefix parent directory does not exist: {output_prefix.parent}") + command.extend(["-o", str(output_prefix)]) + + # Validate num_threads + if num_threads <= 0: + raise ValueError("Number of threads (num_threads) must be a positive integer.") + command.extend(["-t", str(num_threads)]) + + # Validate primary read input (HiFi or ONT, but not both) + if hifi_reads and ont_reads: + raise ValueError("Cannot provide both HiFi reads and ONT reads. Choose one primary input type.") + if not hifi_reads and not ont_reads: + raise ValueError("At least one of hifi_reads or ont_reads must be provided.") + + if hifi_reads: + for read_file in hifi_reads: + if not read_file.is_file(): + raise FileNotFoundError(f"HiFi read file not found: {read_file}") + command.append(str(read_file)) + elif ont_reads: + if not ont_reads.is_file(): + raise FileNotFoundError(f"ONT read file not found: {ont_reads}") + command.append("--ont") + command.append(str(ont_reads)) + + # Hi-C reads validation + if (hic_read1 and not hic_read2) or (not hic_read1 and hic_read2): + raise ValueError("Both hic_read1 and hic_read2 must be provided if either is specified.") + if hic_read1 and hic_read2: + if not hic_read1.is_file(): + raise FileNotFoundError(f"Hi-C read 1 file not found: {hic_read1}") + if not hic_read2.is_file(): + raise FileNotFoundError(f"Hi-C read 2 file not found: {hic_read2}") + command.extend(["--h1", str(hic_read1), "--h2", str(hic_read2)]) + + # Trio binning (yak files) validation + if (paternal_yak and not maternal_yak) or (not paternal_yak and maternal_yak): + raise ValueError("Both paternal_yak and maternal_yak must be provided if either is specified.") + if paternal_yak and maternal_yak: + if not paternal_yak.is_file(): + raise FileNotFoundError(f"Paternal yak file not found: {paternal_yak}") + if not maternal_yak.is_file(): + raise FileNotFoundError(f"Maternal yak file not found: {maternal_yak}") + command.extend(["-1", str(paternal_yak), "-2", str(maternal_yak)]) + + # Ultra-long ONT reads + if ultralong_reads: + if not ultralong_reads.is_file(): + raise FileNotFoundError(f"Ultra-long ONT read file not found: {ultralong_reads}") + command.extend(["--ul", str(ultralong_reads)]) + + # Optional flags and parameters + if ignore_precomputed_overlaps: + command.append("-i") + if write_paf: + command.append("--write-paf") + output_files.append(str(output_prefix.with_suffix(".paf"))) + if write_ec_fasta: + if str(write_ec_fasta) != "/dev/null" and not write_ec_fasta.parent.is_dir(): + raise ValueError(f"Output directory for error corrected FASTA does not exist: {write_ec_fasta.parent}") + command.extend(["--write-ec", str(write_ec_fasta)]) + if str(write_ec_fasta) != "/dev/null": + output_files.append(str(write_ec_fasta)) + if disable_duplication_purging: + command.append("-l0") # -l0 disables purging + if trim_ends_bp < 0: + raise ValueError("Trim ends base pairs (trim_ends_bp) must be a non-negative integer.") + if trim_ends_bp > 0: + command.extend(["-z", str(trim_ends_bp)]) + if bloom_filter_level is not None: + if bloom_filter_level < 0: + raise ValueError("Bloom filter level (bloom_filter_level) must be a non-negative integer.") + command.extend(["-f", str(bloom_filter_level)]) + if enable_dual_scaffolding: + command.append("--dual-scaf") + if telomere_motif: + command.extend(["--telo-m", telomere_motif]) + + # --- Determine expected output files --- + # Common outputs + output_files.append(str(output_prefix.with_suffix(".bp.p_ctg.gfa"))) + output_files.append(str(output_prefix.with_suffix(".bp.hap1.p_ctg.gfa"))) + output_files.append(str(output_prefix.with_suffix(".bp.hap2.p_ctg.gfa"))) + output_files.append(str(output_prefix.with_suffix(".ec.bin"))) + output_files.append(str(output_prefix.with_suffix(".ovlp.source.bin"))) + output_files.append(str(output_prefix.with_suffix(".ovlp.reverse.bin"))) + + # Trio binning specific outputs + if paternal_yak and maternal_yak: + output_files.append(str(output_prefix.with_suffix(".dip.hap1.p_ctg.gfa"))) + output_files.append(str(output_prefix.with_suffix(".dip.hap2.p_ctg.gfa"))) + + # --- Execute Command --- + command_str = " ".join(map(str, command)) + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": str(e) + } + + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": stderr, + "output_files": [str(f) for f in output_files] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hifiasm/app/hifiasm_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hifiasm/app/hifiasm_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a931f30449406d836e032da52774bb063f3306cd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hifiasm/app/hifiasm_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hifiasm/app/hifiasm_server.py') +SERVER_NAME = 'biosci_hifiasm' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hifiasm/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hifiasm/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hifiasm/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hifiasm/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hifiasm/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..60c8f7fe302d3929db2a0e6e368c300c1072bbb7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hifiasm/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-hifiasm: + build: . + image: mcp-hifiasm:latest + container_name: mcp-hifiasm + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=hifiasm + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hifiasm/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hifiasm/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a7d8c781f4fac41f5af4f7dbc43d6cbb47c6e928 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hifiasm/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - hifiasm + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hifiasm/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hifiasm/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hifiasm/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hisat2/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hisat2/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..0b86be0a97e6c7083f4146fef19a90fd1701373d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hisat2/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install hisat2 via conda (e.g., from bioconda) +RUN conda install -c bioconda hisat2 -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/hisat2_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/hisat2_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/hisat2_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hisat2/app/hisat2_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hisat2/app/hisat2_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9fed5d8a0c4fcaf1d5a9e6456822fe79a9da6a65 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hisat2/app/hisat2_server.py @@ -0,0 +1,609 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List, Dict + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided by the MCP framework. +def tool(): + def decorator(f): + return f + return decorator + +mcp = type("mcp", (), {"tool": tool})() + + +@mcp.tool() +def hisat2_align( + index_prefix: Path, + sam_output: Path, + mate1_files: Optional[str] = None, + mate2_files: Optional[str] = None, + unpaired_reads: Optional[str] = None, + input_format: str = "fastq", + skip: int = 0, + upto: Optional[int] = None, + trim5: int = 0, + trim3: int = 0, + quality_encoding: str = "phred33", + max_seed_mismatches: int = 0, + seed_length: int = 20, + seed_interval: str = "S,1,0.50", + n_ceil: str = "L,0,0.15", + pen_cansplice: int = 0, + pen_noncansplice: int = 12, + pen_canintronlen: str = "G,-8,1", + pen_noncanintronlen: str = "G,-8,1", + min_intronlen: int = 20, + max_intronlen: int = 500000, + known_splicesite_infile: Optional[Path] = None, + novel_splicesite_outfile: Optional[Path] = None, + novel_splicesite_infile: Optional[Path] = None, + no_temp_splicesite: bool = False, + no_softclip: bool = False, + sp: str = "2,1", + mismatch_penalty: str = "6,2", + np: int = 1, + read_gap_penalty: str = "5,3", + ref_gap_penalty: str = "5,3", + score_min: str = "L,-0.6,-0.6", + k: Optional[int] = None, + report_all: bool = False, + secondary: bool = False, + min_frag_len: int = 0, + max_frag_len: int = 500, + mate_orientation: Optional[str] = None, + no_mixed: bool = False, + no_discordant: bool = False, + summary_file: Optional[Path] = None, + new_summary: bool = False, + met_file: Optional[Path] = None, + met_stderr: bool = False, + met_interval: int = 1, + unaligned_reads_file: Optional[Path] = None, + aligned_reads_file: Optional[Path] = None, + unaligned_concordant_reads_file: Optional[Path] = None, + aligned_concordant_reads_file: Optional[Path] = None, + quiet: bool = False, + no_head: bool = False, + no_sq: bool = False, + rg_id: Optional[str] = None, + rg: Optional[List[str]] = None, + remove_chrname: bool = False, + add_chrname: bool = False, + dta: bool = False, + dta_cufflinks: bool = False, + no_spliced_alignment: bool = False, + rna_strandness: Optional[str] = None, + transcriptome_mapping_only: bool = False, + bwa_mem: bool = False, + threads: int = 1, + reorder: bool = False, + mm: bool = False, + qc_filter: bool = False, + seed: int = 0, + non_deterministic: bool = False, +) -> Dict: + """ + Aligns sequencing reads to a reference genome using HISAT2. + + This function wraps the main 'hisat2' alignment command, providing a comprehensive + interface to its numerous options for input, alignment, scoring, paired-end, + output, and performance tuning. + """ + # Input validation + if not (mate1_files and mate2_files) and not unpaired_reads: + raise ValueError("Either paired-end reads (-1 and -2) or unpaired reads (-U) must be provided.") + if (mate1_files and not mate2_files) or (not mate1_files and mate2_files): + raise ValueError("For paired-end alignment, both -1 and -2 must be specified.") + + valid_formats = ["fastq", "fasta", "raw"] + if input_format not in valid_formats: + raise ValueError(f"Invalid input_format '{input_format}'. Must be one of {valid_formats}.") + + valid_qualities = ["phred33", "phred64", "solexa-quals"] + if quality_encoding not in valid_qualities: + raise ValueError(f"Invalid quality_encoding '{quality_encoding}'. Must be one of {valid_qualities}.") + + if mate_orientation and mate_orientation not in ["fr", "rf", "ff"]: + raise ValueError("Invalid mate_orientation. Must be one of 'fr', 'rf', 'ff'.") + + if rna_strandness and rna_strandness not in ["F", "R", "FR", "RF"]: + raise ValueError("Invalid rna_strandness. Must be one of 'F', 'R', 'FR', 'RF'.") + + if not index_prefix.parent.exists(): + raise FileNotFoundError(f"Index directory not found: {index_prefix.parent}") + + cmd = ["hisat2"] + + # Input options + cmd.extend(["-x", str(index_prefix)]) + if mate1_files: + cmd.extend(["-1", mate1_files]) + if mate2_files: + cmd.extend(["-2", mate2_files]) + if unpaired_reads: + cmd.extend(["-U", unpaired_reads]) + + if input_format == "fasta": + cmd.append("-f") + elif input_format == "raw": + cmd.append("-r") + else: # fastq is default + cmd.append("-q") + + if skip > 0: + cmd.extend(["-s", str(skip)]) + if upto is not None: + cmd.extend(["-u", str(upto)]) + if trim5 > 0: + cmd.extend(["-5", str(trim5)]) + if trim3 > 0: + cmd.extend(["-3", str(trim3)]) + + cmd.append(f"--{quality_encoding}") + + # Alignment options + cmd.extend(["-N", str(max_seed_mismatches)]) + cmd.extend(["-L", str(seed_length)]) + cmd.extend(["-i", seed_interval]) + cmd.extend(["--n-ceil", n_ceil]) + cmd.extend(["--pen-cansplice", str(pen_cansplice)]) + cmd.extend(["--pen-noncansplice", str(pen_noncansplice)]) + cmd.extend(["--pen-canintronlen", pen_canintronlen]) + cmd.extend(["--pen-noncanintronlen", pen_noncanintronlen]) + cmd.extend(["--min-intronlen", str(min_intronlen)]) + cmd.extend(["--max-intronlen", str(max_intronlen)]) + if known_splicesite_infile: + cmd.extend(["--known-splicesite-infile", str(known_splicesite_infile)]) + if novel_splicesite_outfile: + cmd.extend(["--novel-splicesite-outfile", str(novel_splicesite_outfile)]) + if novel_splicesite_infile: + cmd.extend(["--novel-splicesite-infile", str(novel_splicesite_infile)]) + if no_temp_splicesite: + cmd.append("--no-temp-splicesite") + if no_softclip: + cmd.append("--no-softclip") + cmd.extend(["--sp", sp]) + + # Scoring options + cmd.extend(["--mp", mismatch_penalty]) + cmd.extend(["--np", str(np)]) + cmd.extend(["--rdg", read_gap_penalty]) + cmd.extend(["--rfg", ref_gap_penalty]) + cmd.extend(["--score-min", score_min]) + + # Reporting options + if k is not None: + cmd.extend(["-k", str(k)]) + if report_all: + cmd.append("--all") + if secondary: + cmd.append("--secondary") + + # Paired-end options + if mate1_files: + cmd.extend(["-I", str(min_frag_len)]) + cmd.extend(["-X", str(max_frag_len)]) + if mate_orientation: + cmd.append(f"--{mate_orientation}") + if no_mixed: + cmd.append("--no-mixed") + if no_discordant: + cmd.append("--no-discordant") + + # Output options + cmd.extend(["-S", str(sam_output)]) + if summary_file: + cmd.extend(["--summary-file", str(summary_file)]) + if new_summary: + cmd.append("--new-summary") + if met_file: + cmd.extend(["--met-file", str(met_file)]) + if met_stderr: + cmd.append("--met-stderr") + cmd.extend(["--met", str(met_interval)]) + if unaligned_reads_file: + cmd.extend(["--un", str(unaligned_reads_file)]) + if aligned_reads_file: + cmd.extend(["--al", str(aligned_reads_file)]) + if unaligned_concordant_reads_file: + cmd.extend(["--un-conc", str(unaligned_concordant_reads_file)]) + if aligned_concordant_reads_file: + cmd.extend(["--al-conc", str(aligned_concordant_reads_file)]) + if quiet: + cmd.append("--quiet") + if no_head: + cmd.append("--no-head") + if no_sq: + cmd.append("--no-sq") + if rg_id: + cmd.extend(["--rg-id", rg_id]) + if rg: + for r in rg: + cmd.extend(["--rg", r]) + if remove_chrname: + cmd.append("--remove-chrname") + if add_chrname: + cmd.append("--add-chrname") + if dta: + cmd.append("--dta") + if dta_cufflinks: + cmd.append("--dta-cufflinks") + if no_spliced_alignment: + cmd.append("--no-spliced-alignment") + if rna_strandness: + cmd.extend(["--rna-strandness", rna_strandness]) + if transcriptome_mapping_only: + cmd.append("--transcriptome-mapping-only") + if bwa_mem: + cmd.append("--bwa-mem") + + # Performance options + cmd.extend(["-p", str(threads)]) + if reorder: + cmd.append("--reorder") + if mm: + cmd.append("--mm") + if qc_filter: + cmd.append("--qc-filter") + cmd.extend(["--seed", str(seed)]) + if non_deterministic: + cmd.append("--non-deterministic") + + command_str = " ".join(cmd) + output_files = {"sam_output": str(sam_output)} + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + # Add other potential output files to the list + if summary_file: output_files["summary_file"] = str(summary_file) + if met_file: output_files["met_file"] = str(met_file) + if unaligned_reads_file: output_files["unaligned_reads_file"] = str(unaligned_reads_file) + if aligned_reads_file: output_files["aligned_reads_file"] = str(aligned_reads_file) + if unaligned_concordant_reads_file: output_files["unaligned_concordant_reads_file"] = str(unaligned_concordant_reads_file) + if aligned_concordant_reads_file: output_files["aligned_concordant_reads_file"] = str(aligned_concordant_reads_file) + if novel_splicesite_outfile: output_files["novel_splicesite_outfile"] = str(novel_splicesite_outfile) + + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"HISAT2 alignment failed with exit code {e.returncode}", + "output_files": {}, + } + +@mcp.tool() +def hisat2_build( + reference_in: str, + index_basename: str, + large_index: bool = False, + no_auto: bool = False, + packed: bool = False, + bmax: Optional[int] = None, + bmaxdivn: int = 4, + dcv: int = 1024, + no_dc: bool = False, + no_ref: bool = False, + just_ac: bool = False, + offrate: int = 5, + ftabchars: int = 10, + local_offrate: int = 3, + local_ftabchars: int = 6, + snp_file: Optional[Path] = None, + haplotype_file: Optional[Path] = None, + ss_file: Optional[Path] = None, + exon_file: Optional[Path] = None, + threads: int = 1, + seed: int = 0, + quiet: bool = False, +) -> Dict: + """ + Builds a HISAT2 index from a set of reference sequences. + + This function wraps the 'hisat2-build' command, which constructs the index files + required by the main 'hisat2' aligner. + """ + # Input validation + # Assuming reference_in is a comma-separated list of file paths + for ref_path_str in reference_in.split(','): + if not Path(ref_path_str).exists(): + raise FileNotFoundError(f"Reference FASTA file not found: {ref_path_str}") + + cmd = ["hisat2-build"] + + # Options + if large_index: + cmd.append("--large-index") + if no_auto: + cmd.append("--noauto") + if packed: + cmd.append("--packed") + if bmax is not None: + cmd.extend(["--bmax", str(bmax)]) + cmd.extend(["--bmaxdivn", str(bmaxdivn)]) + cmd.extend(["--dcv", str(dcv)]) + if no_dc: + cmd.append("--nodc") + if no_ref: + cmd.append("--noref") + if just_ac: + cmd.append("--just-ac") + cmd.extend(["--offrate", str(offrate)]) + cmd.extend(["--ftabchars", str(ftabchars)]) + cmd.extend(["--localoffrate", str(local_offrate)]) + cmd.extend(["--localftabchars", str(local_ftabchars)]) + if snp_file: + cmd.extend(["--snp", str(snp_file)]) + if haplotype_file: + cmd.extend(["--haplotype", str(haplotype_file)]) + if ss_file: + cmd.extend(["--ss", str(ss_file)]) + if exon_file: + cmd.extend(["--exon", str(exon_file)]) + cmd.extend(["-p", str(threads)]) + cmd.extend(["--seed", str(seed)]) + if quiet: + cmd.append("--quiet") + + # Positional arguments + cmd.extend([reference_in, index_basename]) + + command_str = " ".join(cmd) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + # Find created index files + output_dir = Path(index_basename).parent + base = Path(index_basename).name + index_files = [str(p) for p in output_dir.glob(f"{base}*.ht2")] + + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"index_files": index_files}, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"HISAT2 build failed with exit code {e.returncode}", + "output_files": {}, + } + +@mcp.tool() +def hisat2_inspect( + index_basename: str, + names: bool = False, + summary: bool = False, + snp: bool = False, + ss: bool = False, + haplotype: bool = False, + extract: Optional[str] = None, + across: Optional[int] = None, + verbose: bool = False, +) -> Dict: + """ + Inspects a HISAT2 index to extract information. + + This function wraps the 'hisat2-inspect' command. It can print reference sequence + names, a summary of the index, or extract specific sequences. + """ + # Input validation + modes = [names, summary, snp, ss, haplotype, extract is not None] + if sum(modes) > 1: + raise ValueError("Only one inspection mode (--names, --summary, --snp, --ss, --haplotype, --extract) can be active at a time.") + if sum(modes) == 0: + raise ValueError("At least one inspection mode must be selected.") + + if not Path(f"{index_basename}.1.ht2").exists(): + raise FileNotFoundError(f"Index file not found for basename: {index_basename}") + + cmd = ["hisat2-inspect"] + + if names: + cmd.append("--names") + if summary: + cmd.append("--summary") + if snp: + cmd.append("--snp") + if ss: + cmd.append("--ss") + if haplotype: + cmd.append("--haplotype") + if extract: + cmd.extend(["--extract", extract]) + if across is not None: + cmd.extend(["--across", str(across)]) + if verbose: + cmd.append("--verbose") + + cmd.append(index_basename) + 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": {}, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"HISAT2 inspect failed with exit code {e.returncode}", + "output_files": {}, + } + +@mcp.tool() +def hisat2_extract_splice_sites( + gtf_file: Path, + output_file: Path, +) -> Dict: + """ + Extracts splice sites from a GTF file for use with hisat2-build. + + This function wraps the 'hisat2_extract_splice_sites.py' utility script. + """ + if not gtf_file.exists(): + raise FileNotFoundError(f"Input GTF file not found: {gtf_file}") + + cmd = ["hisat2_extract_splice_sites.py", str(gtf_file)] + command_str = " ".join(cmd) + f" > {output_file}" + + try: + with open(output_file, "w") as f_out: + result = subprocess.run(cmd, stdout=f_out, stderr=subprocess.PIPE, text=True, check=True) + + return { + "command_executed": command_str, + "stdout": "", # stdout is redirected to file + "stderr": result.stderr, + "output_files": {"splice_sites": str(output_file)}, + } + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: 'hisat2_extract_splice_sites.py' not found. Make sure the HISAT2 scripts are in your PATH.", + "error": "Executable not found", + "output_files": {}, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout or "", + "stderr": e.stderr or "", + "error": f"Script failed with exit code {e.returncode}", + "output_files": {}, + } + +@mcp.tool() +def hisat2_extract_exons( + gtf_file: Path, + output_file: Path, +) -> Dict: + """ + Extracts exons from a GTF file for use with hisat2-build. + + This function wraps the 'hisat2_extract_exons.py' utility script. + """ + if not gtf_file.exists(): + raise FileNotFoundError(f"Input GTF file not found: {gtf_file}") + + cmd = ["hisat2_extract_exons.py", str(gtf_file)] + command_str = " ".join(cmd) + f" > {output_file}" + + try: + with open(output_file, "w") as f_out: + result = subprocess.run(cmd, stdout=f_out, stderr=subprocess.PIPE, text=True, check=True) + + return { + "command_executed": command_str, + "stdout": "", # stdout is redirected to file + "stderr": result.stderr, + "output_files": {"exons": str(output_file)}, + } + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: 'hisat2_extract_exons.py' not found. Make sure the HISAT2 scripts are in your PATH.", + "error": "Executable not found", + "output_files": {}, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout or "", + "stderr": e.stderr or "", + "error": f"Script failed with exit code {e.returncode}", + "output_files": {}, + } + +@mcp.tool() +def hisat2_simulate_reads( + reference_fasta: Path, + num_reads: int, + output_prefix: str, + read_len: int = 100, + error_rate: float = 0.01, + max_mismatches: int = 4, + insert_size: int = 300, + insert_stdev: int = 30, + paired_end: bool = False, + quiet: bool = False, +) -> Dict: + """ + Simulates sequencing reads from a reference genome. + + This function wraps the 'hisat2_simulate_reads.py' utility script. + """ + if not reference_fasta.exists(): + raise FileNotFoundError(f"Reference FASTA file not found: {reference_fasta}") + if num_reads <= 0: + raise ValueError("Number of reads must be positive.") + + cmd = [ + "hisat2_simulate_reads.py", + str(reference_fasta), + str(num_reads), + "--output-prefix", output_prefix, + "--read-len", str(read_len), + "--error-rate", str(error_rate), + "--max-mismatches", str(max_mismatches), + "--insert-size", str(insert_size), + "--insert-stdev", str(insert_stdev), + ] + if paired_end: + cmd.append("--paired-end") + if quiet: + cmd.append("--quiet") + + command_str = " ".join(cmd) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + output_files = {} + if paired_end: + output_files["mate1"] = f"{output_prefix}.1.fq" + output_files["mate2"] = f"{output_prefix}.2.fq" + else: + output_files["reads"] = f"{output_prefix}.fq" + + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: 'hisat2_simulate_reads.py' not found. Make sure the HISAT2 scripts are in your PATH.", + "error": "Executable not found", + "output_files": {}, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Script failed with exit code {e.returncode}", + "output_files": {}, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hisat2/app/hisat2_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hisat2/app/hisat2_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3b82282bc498ddbe2e5b0a769a9be661f1cf95f0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hisat2/app/hisat2_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hisat2/app/hisat2_server.py') +SERVER_NAME = 'biosci_hisat2' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hisat2/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hisat2/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hisat2/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hisat2/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hisat2/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..5745e33428aaa7cfe9b6f75dda93d76d14a6ff54 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hisat2/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-hisat2: + build: . + image: mcp-hisat2:latest + container_name: mcp-hisat2 + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=hisat2 + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hisat2/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hisat2/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b8e575dd31bac67b89dcbfe6a17b1744837fdfe4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hisat2/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - hisat2 + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hisat2/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hisat2/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hisat2/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hmmer/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hmmer/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4c15664fdf70ee93628bbf59835f65c8ecaa296d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hmmer/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install hmmer via conda (e.g., from bioconda) +RUN conda install -c bioconda hmmer -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/hmmer_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/hmmer_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/hmmer_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hmmer/app/hmmer_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hmmer/app/hmmer_server.py new file mode 100644 index 0000000000000000000000000000000000000000..31f5e330185551b36cc0a9d147349a2d3d68660a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hmmer/app/hmmer_server.py @@ -0,0 +1,1229 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# Assuming mcp.tool is available in the environment. +# No need to import mcp or define a dummy decorator in the final production code. + +@mcp.tool() +def hmmbuild( + msafile: Path, + hmmfile_out: Path, + name: Optional[str] = None, + output_summary: Optional[Path] = None, + output_annotated_msa: Optional[Path] = None, + informat: Optional[str] = None, + seed: int = 0, + cpu: int = 1, + amino: bool = False, + dna: bool = False, + rna: bool = False, + hand: bool = False, + fast: bool = False, + small: bool = False, + symfrac: float = 0.5, + fragthresh: float = 0.5, + w_beta: Optional[float] = None, + w_length: Optional[int] = None, + wid: Optional[float] = None, + eent: bool = False, + eset: Optional[float] = None, + pnone: bool = False, + plaplace: bool = False, + archpri: float = 0.85, + gapmax: float = 0.5, +) -> dict: + """ + Build a profile HMM from a multiple sequence alignment. + + Args: + msafile: Input multiple sequence alignment file. + hmmfile_out: Output HMM file. + name: Name the HMM . + output_summary: Direct summary output to a file . + output_annotated_msa: Resave annotated MSA to a file . + informat: Assert that the input MSA is in format . + seed: Set the random number seed to (0 means use time). + cpu: Number of parallel CPU workers to use. + amino: Assert that the MSA contains protein sequences. + dna: Assert that the MSA contains DNA sequences. + rna: Assert that the MSA contains RNA sequences. + hand: Manually set model architecture (requires reference annotation). + fast: Use fast heuristic methods for model construction. + small: Use small memory/fast construction pipeline. + symfrac: Set minimum fraction of symbols in columns to be consensus. + fragthresh: Set fragment score threshold. + w_beta: Set beta for window-based relative weights. + w_length: Set window length for relative weights. + wid: Set identity threshold for relative weights. + eent: Use entropy weighting. + eset: Set effective sequence number for entropy weights. + pnone: Don't use any prior. + plaplace: Use a Laplace +1 prior. + archpri: Set architecture posterior probability threshold. + gapmax: Set maximum column fraction of gaps to be consensus. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + if not msafile.is_file(): + raise FileNotFoundError(f"Input MSA file not found: {msafile}") + if cpu < 1: + raise ValueError("The number of CPUs must be a positive integer (>=1).") + if seed < 0: + raise ValueError("The seed must be a non-negative integer.") + if not 0.0 <= symfrac <= 1.0: + raise ValueError("symfrac must be between 0.0 and 1.0.") + if not 0.0 <= fragthresh <= 1.0: + raise ValueError("fragthresh must be between 0.0 and 1.0.") + if not 0.0 <= archpri <= 1.0: + raise ValueError("archpri must be between 0.0 and 1.0.") + if not 0.0 <= gapmax <= 1.0: + raise ValueError("gapmax must be between 0.0 and 1.0.") + + seq_type_flags = [amino, dna, rna] + if sum(seq_type_flags) > 1: + raise ValueError("Only one of --amino, --dna, or --rna can be specified.") + + cmd = ["hmmbuild"] + + if name: + cmd.extend(["-n", name]) + if output_summary: + cmd.extend(["-o", str(output_summary)]) + if output_annotated_msa: + cmd.extend(["-O", str(output_annotated_msa)]) + if informat: + cmd.extend(["--informat", informat]) + if seed != 0: + cmd.extend(["--seed", str(seed)]) + if cpu != 1: + cmd.extend(["--cpu", str(cpu)]) + if amino: + cmd.append("--amino") + if dna: + cmd.append("--dna") + if rna: + cmd.append("--rna") + if hand: + cmd.append("--hand") + if fast: + cmd.append("--fast") + if small: + cmd.append("--small") + if symfrac != 0.5: + cmd.extend(["--symfrac", str(symfrac)]) + if fragthresh != 0.5: + cmd.extend(["--fragthresh", str(fragthresh)]) + if w_beta is not None: + cmd.extend(["--w_beta", str(w_beta)]) + if w_length is not None: + cmd.extend(["--w_length", str(w_length)]) + if wid is not None: + cmd.extend(["--wid", str(wid)]) + if eent: + cmd.append("--eent") + if eset is not None: + cmd.extend(["--eset", str(eset)]) + if pnone: + cmd.append("--pnone") + if plaplace: + cmd.append("--plaplace") + if archpri != 0.85: + cmd.extend(["--archpri", str(archpri)]) + if gapmax != 0.5: + cmd.extend(["--gapmax", str(gapmax)]) + + cmd.extend([str(hmmfile_out), str(msafile)]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + output_files = [str(hmmfile_out)] + if output_summary: + output_files.append(str(output_summary)) + if output_annotated_msa: + output_files.append(str(output_annotated_msa)) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"hmmbuild failed with exit code {e.returncode}", + "output_files": [], + } + +@mcp.tool() +def hmmpress( + hmmfile: Path, + force: bool = False, +) -> dict: + """ + Prepare an HMM database for hmmscan. + + This command creates several binary files derived from the input HMM file. + These files are required for `hmmscan` to work efficiently. + + Args: + hmmfile: The HMM database file to press. + force: Force overwrite of any previous pressed files. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + if not hmmfile.is_file(): + raise FileNotFoundError(f"Input HMM file not found: {hmmfile}") + + cmd = ["hmmpress"] + if force: + cmd.append("-f") + cmd.append(str(hmmfile)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + base_path = str(hmmfile) + output_files = [ + f"{base_path}.h3m", + f"{base_path}.h3i", + f"{base_path}.h3f", + f"{base_path}.h3p", + ] + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"hmmpress failed with exit code {e.returncode}", + "output_files": [], + } + +def _run_hmmer_search( + program: str, + query_file: Path, + db_file: Path, + output_file: Optional[Path] = None, + alignment_output: Optional[Path] = None, + tblout: Optional[Path] = None, + domtblout: Optional[Path] = None, + pfamtblout: Optional[Path] = None, + acc: bool = False, + noali: bool = False, + notextw: bool = False, + textw: int = 120, + e_value_threshold: float = 10.0, + p_value_threshold: Optional[float] = None, + score_threshold: Optional[float] = None, + dom_e_value_threshold: float = 10.0, + dom_p_value_threshold: Optional[float] = None, + dom_score_threshold: Optional[float] = None, + inc_e_value: Optional[float] = None, + inc_p_value: Optional[float] = None, + inc_score: Optional[float] = None, + inc_dom_e_value: Optional[float] = None, + inc_dom_p_value: Optional[float] = None, + inc_dom_score: Optional[float] = None, + cut_ga: bool = False, + cut_nc: bool = False, + cut_tc: bool = False, + max_sensitivity: bool = False, + f1: Optional[float] = None, + f2: Optional[float] = None, + f3: Optional[float] = None, + nobias: bool = False, + nonull2: bool = False, + z_value: Optional[float] = None, + dom_z_value: Optional[float] = None, + seed: int = 0, + qformat: Optional[str] = None, + tformat: Optional[str] = None, + cpu: int = 1, + jackhmmer_iterations: Optional[int] = None, +) -> dict: + """Internal helper function to run HMMER protein search programs.""" + if not query_file.is_file(): + raise FileNotFoundError(f"Input query file not found: {query_file}") + if not db_file.is_file(): + raise FileNotFoundError(f"Input database file not found: {db_file}") + if cpu < 1: + raise ValueError("The number of CPUs must be a positive integer (>=1).") + if seed < 0: + raise ValueError("The seed must be a non-negative integer.") + if notextw and textw != 120: + raise ValueError("Cannot specify --notextw and a custom --textw simultaneously.") + if not 0.0 <= e_value_threshold: + raise ValueError("E-value threshold must be non-negative.") + if p_value_threshold is not None and not 0.0 <= p_value_threshold <= 1.0: + raise ValueError("P-value threshold must be between 0.0 and 1.0.") + if not 0.0 <= dom_e_value_threshold: + raise ValueError("Domain E-value threshold must be non-negative.") + if dom_p_value_threshold is not None and not 0.0 <= dom_p_value_threshold <= 1.0: + raise ValueError("Domain P-value threshold must be between 0.0 and 1.0.") + + if inc_e_value is not None and not 0.0 <= inc_e_value: + raise ValueError("Inclusion E-value threshold must be non-negative.") + if inc_p_value is not None and not 0.0 <= inc_p_value <= 1.0: + raise ValueError("Inclusion P-value threshold must be between 0.0 and 1.0.") + if inc_dom_e_value is not None and not 0.0 <= inc_dom_e_value: + raise ValueError("Inclusion domain E-value threshold must be non-negative.") + if inc_dom_p_value is not None and not 0.0 <= inc_dom_p_value <= 1.0: + raise ValueError("Inclusion domain P-value threshold must be between 0.0 and 1.0.") + + cut_options = [cut_ga, cut_nc, cut_tc] + if sum(cut_options) > 1: + raise ValueError("Only one of --cut_ga, --cut_nc, or --cut_tc can be used at a time.") + + cmd = [program] + output_files = [] + + if output_file: + cmd.extend(["-o", str(output_file)]) + output_files.append(str(output_file)) + if alignment_output: + cmd.extend(["-A", str(alignment_output)]) + output_files.append(str(alignment_output)) + if tblout: + cmd.extend(["--tblout", str(tblout)]) + output_files.append(str(tblout)) + if domtblout: + cmd.extend(["--domtblout", str(domtblout)]) + output_files.append(str(domtblout)) + if pfamtblout: + cmd.extend(["--pfamtblout", str(pfamtblout)]) + output_files.append(str(pfamtblout)) + if acc: + cmd.append("--acc") + if noali: + cmd.append("--noali") + if notextw: + cmd.append("--notextw") + elif textw != 120: + cmd.extend(["--textw", str(textw)]) + + if e_value_threshold != 10.0: + cmd.extend(["-E", str(e_value_threshold)]) + if p_value_threshold is not None: + cmd.extend(["--pvalue", str(p_value_threshold)]) + if score_threshold is not None: + cmd.extend(["-T", str(score_threshold)]) + if dom_e_value_threshold != 10.0: + cmd.extend(["--domE", str(dom_e_value_threshold)]) + if dom_p_value_threshold is not None: + cmd.extend(["--dompvalue", str(dom_p_value_threshold)]) + if dom_score_threshold is not None: + cmd.extend(["--domT", str(dom_score_threshold)]) + + if inc_e_value is not None: + cmd.extend(["--incE", str(inc_e_value)]) + if inc_p_value is not None: + cmd.extend(["--incpvalue", str(inc_p_value)]) + if inc_score is not None: + cmd.extend(["--incT", str(inc_score)]) + if inc_dom_e_value is not None: + cmd.extend(["--incdomE", str(inc_dom_e_value)]) + if inc_dom_p_value is not None: + cmd.extend(["--incdompvalue", str(inc_dom_p_value)]) + if inc_dom_score is not None: + cmd.extend(["--incdomT", str(inc_dom_score)]) + + if cut_ga: + cmd.append("--cut_ga") + if cut_nc: + cmd.append("--cut_nc") + if cut_tc: + cmd.append("--cut_tc") + + if max_sensitivity: + cmd.append("--max") + if f1 is not None: + cmd.extend(["--F1", str(f1)]) + if f2 is not None: + cmd.extend(["--F2", str(f2)]) + if f3 is not None: + cmd.extend(["--F3", str(f3)]) + if nobias: + cmd.append("--nobias") + + if nonull2: + cmd.append("--nonull2") + if z_value is not None: + cmd.extend(["-Z", str(z_value)]) + if dom_z_value is not None: + cmd.extend(["--domZ", str(dom_z_value)]) + if seed != 0: + cmd.extend(["--seed", str(seed)]) + if qformat: + cmd.extend(["--qformat", qformat]) + if tformat: + cmd.extend(["--tformat", tformat]) + if cpu != 1: + cmd.extend(["--cpu", str(cpu)]) + + if jackhmmer_iterations is not None: + cmd.extend(["-N", str(jackhmmer_iterations)]) + + cmd.extend([str(query_file), str(db_file)]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"{program} failed with exit code {e.returncode}", + "output_files": [], + } + +@mcp.tool() +def hmmsearch( + hmmfile: Path, + seqdb: Path, + output_file: Optional[Path] = None, + alignment_output: Optional[Path] = None, + tblout: Optional[Path] = None, + domtblout: Optional[Path] = None, + pfamtblout: Optional[Path] = None, + acc: bool = False, + noali: bool = False, + notextw: bool = False, + textw: int = 120, + e_value_threshold: float = 10.0, + p_value_threshold: Optional[float] = None, + score_threshold: Optional[float] = None, + dom_e_value_threshold: float = 10.0, + dom_p_value_threshold: Optional[float] = None, + dom_score_threshold: Optional[float] = None, + inc_e_value: Optional[float] = None, + inc_p_value: Optional[float] = None, + inc_score: Optional[float] = None, + inc_dom_e_value: Optional[float] = None, + inc_dom_p_value: Optional[float] = None, + inc_dom_score: Optional[float] = None, + cut_ga: bool = False, + cut_nc: bool = False, + cut_tc: bool = False, + max_sensitivity: bool = False, + f1: Optional[float] = None, + f2: Optional[float] = None, + f3: Optional[float] = None, + nobias: bool = False, + nonull2: bool = False, + z_value: Optional[float] = None, + dom_z_value: Optional[float] = None, + seed: int = 0, + tformat: Optional[str] = None, + cpu: int = 1, +) -> dict: + """ + Search a profile HMM against a sequence database. + + Args: + hmmfile: Input HMM profile file. + seqdb: Target sequence database file. + output_file: Direct output to a file instead of stdout. + alignment_output: Save multiple alignment of all hits to a file. + tblout: Save a simple tabular output file. + domtblout: Save a simple tabular output file of domains. + pfamtblout: Save a pfam-style tabular output file. + acc: Use accessions instead of names in output. + noali: Do not output alignments, making the output smaller. + notextw: Unlimit ASCII text output line width. + textw: Set ASCII text output line width (default 120). + e_value_threshold: Report sequences with E-value <= this threshold. + p_value_threshold: Report sequences with P-value <= this threshold. + score_threshold: Report sequences with score >= this threshold. + dom_e_value_threshold: Report domains with E-value <= this threshold. + dom_p_value_threshold: Report domains with P-value <= this threshold. + dom_score_threshold: Report domains with score >= this threshold. + inc_e_value: Include sequences with E-value <= this threshold. + inc_p_value: Include sequences with P-value <= this threshold. + inc_score: Include sequences with score >= this threshold. + inc_dom_e_value: Include domains with E-value <= this threshold. + inc_dom_p_value: Include domains with P-value <= this threshold. + inc_dom_score: Include domains with score >= this threshold. + cut_ga: Use GA gathering thresholds for inclusion. + cut_nc: Use NC noise thresholds for inclusion. + cut_tc: Use TC trusted thresholds for inclusion. + max_sensitivity: Turn off all heuristics and run full Forward/Viterbi. + f1, f2, f3: Stage 1/2/3 (MSV/Vit/Fwd) thresholds. + nobias: Turn off composition bias filter. + nonull2: Turn off biased composition score corrections. + z_value: Set number of sequences for E-value calculation. + dom_z_value: Set number of domains for E-value calculation. + seed: Set random number seed (0=use time). + tformat: Assert target seqdb is in a specific format. + cpu: Number of parallel CPU workers to use. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + return _run_hmmer_search( + program="hmmsearch", + query_file=hmmfile, + db_file=seqdb, + output_file=output_file, + alignment_output=alignment_output, + tblout=tblout, + domtblout=domtblout, + pfamtblout=pfamtblout, + acc=acc, + noali=noali, + notextw=notextw, + textw=textw, + e_value_threshold=e_value_threshold, + p_value_threshold=p_value_threshold, + score_threshold=score_threshold, + dom_e_value_threshold=dom_e_value_threshold, + dom_p_value_threshold=dom_p_value_threshold, + dom_score_threshold=dom_score_threshold, + inc_e_value=inc_e_value, + inc_p_value=inc_p_value, + inc_score=inc_score, + inc_dom_e_value=inc_dom_e_value, + inc_dom_p_value=inc_dom_p_value, + inc_dom_score=inc_dom_score, + cut_ga=cut_ga, + cut_nc=cut_nc, + cut_tc=cut_tc, + max_sensitivity=max_sensitivity, + f1=f1, + f2=f2, + f3=f3, + nobias=nobias, + nonull2=nonull2, + z_value=z_value, + dom_z_value=dom_z_value, + seed=seed, + tformat=tformat, + cpu=cpu, + ) + +@mcp.tool() +def phmmer( + seqfile: Path, + seqdb: Path, + output_file: Optional[Path] = None, + alignment_output: Optional[Path] = None, + tblout: Optional[Path] = None, + domtblout: Optional[Path] = None, + acc: bool = False, + noali: bool = False, + notextw: bool = False, + textw: int = 120, + e_value_threshold: float = 10.0, + score_threshold: Optional[float] = None, + dom_e_value_threshold: float = 10.0, + dom_score_threshold: Optional[float] = None, + inc_e_value: Optional[float] = None, + inc_score: Optional[float] = None, + inc_dom_e_value: Optional[float] = None, + inc_dom_score: Optional[float] = None, + nobias: bool = False, + nonull2: bool = False, + z_value: Optional[float] = None, + dom_z_value: Optional[float] = None, + seed: int = 0, + qformat: Optional[str] = None, + tformat: Optional[str] = None, + cpu: int = 1, +) -> dict: + """ + Search a protein sequence against a protein sequence database. + + Args: + seqfile: Input sequence file. + seqdb: Target sequence database file. + output_file: Direct output to a file instead of stdout. + alignment_output: Save multiple alignment of all hits to a file. + tblout: Save a simple tabular output file. + domtblout: Save a simple tabular output file of domains. + acc: Use accessions instead of names in output. + noali: Do not output alignments, making the output smaller. + notextw: Unlimit ASCII text output line width. + textw: Set ASCII text output line width (default 120). + e_value_threshold: Report sequences with E-value <= this threshold. + score_threshold: Report sequences with score >= this threshold. + dom_e_value_threshold: Report domains with E-value <= this threshold. + dom_score_threshold: Report domains with score >= this threshold. + inc_e_value: Include sequences with E-value <= this threshold. + inc_score: Include sequences with score >= this threshold. + inc_dom_e_value: Include domains with E-value <= this threshold. + inc_dom_score: Include domains with score >= this threshold. + nobias: Turn off composition bias filter. + nonull2: Turn off biased composition score corrections. + z_value: Set number of sequences for E-value calculation. + dom_z_value: Set number of domains for E-value calculation. + seed: Set random number seed (0=use time). + qformat: Assert query seqfile is in a specific format. + tformat: Assert target seqdb is in a specific format. + cpu: Number of parallel CPU workers to use. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + return _run_hmmer_search( + program="phmmer", + query_file=seqfile, + db_file=seqdb, + output_file=output_file, + alignment_output=alignment_output, + tblout=tblout, + domtblout=domtblout, + acc=acc, + noali=noali, + notextw=notextw, + textw=textw, + e_value_threshold=e_value_threshold, + score_threshold=score_threshold, + dom_e_value_threshold=dom_e_value_threshold, + dom_score_threshold=dom_score_threshold, + inc_e_value=inc_e_value, + inc_score=inc_score, + inc_dom_e_value=inc_dom_e_value, + inc_dom_score=inc_dom_score, + nobias=nobias, + nonull2=nonull2, + z_value=z_value, + dom_z_value=dom_z_value, + seed=seed, + qformat=qformat, + tformat=tformat, + cpu=cpu, + ) + +@mcp.tool() +def hmmscan( + hmmdb: Path, + seqfile: Path, + output_file: Optional[Path] = None, + tblout: Optional[Path] = None, + domtblout: Optional[Path] = None, + pfamtblout: Optional[Path] = None, + acc: bool = False, + noali: bool = False, + notextw: bool = False, + textw: int = 120, + e_value_threshold: float = 10.0, + score_threshold: Optional[float] = None, + dom_e_value_threshold: float = 10.0, + dom_score_threshold: Optional[float] = None, + inc_e_value: Optional[float] = None, + inc_score: Optional[float] = None, + inc_dom_e_value: Optional[float] = None, + inc_dom_score: Optional[float] = None, + cut_ga: bool = False, + cut_nc: bool = False, + cut_tc: bool = False, + max_sensitivity: bool = False, + f1: Optional[float] = None, + f2: Optional[float] = None, + f3: Optional[float] = None, + nobias: bool = False, + nonull2: bool = False, + z_value: Optional[float] = None, + dom_z_value: Optional[float] = None, + seed: int = 0, + cpu: int = 1, +) -> dict: + """ + Search a sequence against a profile HMM database. + Note: The HMM database must be prepared with `hmmpress` first. + + Args: + hmmdb: HMM profile database file (must be pressed). + seqfile: Input sequence file. + output_file: Direct output to a file instead of stdout. + tblout: Save a simple tabular output file. + domtblout: Save a simple tabular output file of domains. + pfamtblout: Save a pfam-style tabular output file. + acc: Use accessions instead of names in output. + noali: Do not output alignments, making the output smaller. + notextw: Unlimit ASCII text output line width. + textw: Set ASCII text output line width (default 120). + e_value_threshold: Report sequences with E-value <= this threshold. + score_threshold: Report sequences with score >= this threshold. + dom_e_value_threshold: Report domains with E-value <= this threshold. + dom_score_threshold: Report domains with score >= this threshold. + inc_e_value: Include sequences with E-value <= this threshold. + inc_score: Include sequences with score >= this threshold. + inc_dom_e_value: Include domains with E-value <= this threshold. + inc_dom_score: Include domains with score >= this threshold. + cut_ga: Use GA gathering thresholds for inclusion. + cut_nc: Use NC noise thresholds for inclusion. + cut_tc: Use TC trusted thresholds for inclusion. + max_sensitivity: Turn off all heuristics and run full Forward/Viterbi. + f1, f2, f3: Stage 1/2/3 (MSV/Vit/Fwd) thresholds. + nobias: Turn off composition bias filter. + nonull2: Turn off biased composition score corrections. + z_value: Set number of sequences for E-value calculation. + dom_z_value: Set number of domains for E-value calculation. + seed: Set random number seed (0=use time). + cpu: Number of parallel CPU workers to use. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + return _run_hmmer_search( + program="hmmscan", + query_file=hmmdb, + db_file=seqfile, + output_file=output_file, + tblout=tblout, + domtblout=domtblout, + pfamtblout=pfamtblout, + acc=acc, + noali=noali, + notextw=notextw, + textw=textw, + e_value_threshold=e_value_threshold, + score_threshold=score_threshold, + dom_e_value_threshold=dom_e_value_threshold, + dom_score_threshold=dom_score_threshold, + inc_e_value=inc_e_value, + inc_score=inc_score, + inc_dom_e_value=inc_dom_e_value, + inc_dom_score=inc_dom_score, + cut_ga=cut_ga, + cut_nc=cut_nc, + cut_tc=cut_tc, + max_sensitivity=max_sensitivity, + f1=f1, + f2=f2, + f3=f3, + nobias=nobias, + nonull2=nonull2, + z_value=z_value, + dom_z_value=dom_z_value, + seed=seed, + cpu=cpu, + ) + +@mcp.tool() +def jackhmmer( + seqfile: Path, + seqdb: Path, + iterations: int = 5, + output_file: Optional[Path] = None, + alignment_output: Optional[Path] = None, + tblout: Optional[Path] = None, + domtblout: Optional[Path] = None, + acc: bool = False, + noali: bool = False, + notextw: bool = False, + textw: int = 120, + e_value_threshold: float = 10.0, + score_threshold: Optional[float] = None, + dom_e_value_threshold: float = 10.0, + dom_score_threshold: Optional[float] = None, + inc_e_value: float = 0.01, + inc_score: Optional[float] = None, + inc_dom_e_value: float = 0.01, + inc_dom_score: Optional[float] = None, + nobias: bool = False, + nonull2: bool = False, + z_value: Optional[float] = None, + dom_z_value: Optional[float] = None, + seed: int = 0, + qformat: Optional[str] = None, + tformat: Optional[str] = None, + cpu: int = 1, +) -> dict: + """ + Iteratively search a protein sequence against a protein sequence database. + + Args: + seqfile: Input sequence file. + seqdb: Target sequence database file. + iterations: Number of iterations to perform. + output_file: Direct output to a file instead of stdout. + alignment_output: Save multiple alignment of all hits to a file. + tblout: Save a simple tabular output file. + domtblout: Save a simple tabular output file of domains. + acc: Use accessions instead of names in output. + noali: Do not output alignments, making the output smaller. + notextw: Unlimit ASCII text output line width. + textw: Set ASCII text output line width (default 120). + e_value_threshold: Report sequences with E-value <= this threshold. + score_threshold: Report sequences with score >= this threshold. + dom_e_value_threshold: Report domains with E-value <= this threshold. + dom_score_threshold: Report domains with score >= this threshold. + inc_e_value: Include sequences with E-value <= this threshold in the next round. + inc_score: Include sequences with score >= this threshold in the next round. + inc_dom_e_value: Include domains with E-value <= this threshold in the next round. + inc_dom_score: Include domains with score >= this threshold in the next round. + nobias: Turn off composition bias filter. + nonull2: Turn off biased composition score corrections. + z_value: Set number of sequences for E-value calculation. + dom_z_value: Set number of domains for E-value calculation. + seed: Set random number seed (0=use time). + qformat: Assert query seqfile is in a specific format. + tformat: Assert target seqdb is in a specific format. + cpu: Number of parallel CPU workers to use. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + if iterations < 1: + raise ValueError("Number of iterations must be a positive integer.") + + return _run_hmmer_search( + program="jackhmmer", + query_file=seqfile, + db_file=seqdb, + output_file=output_file, + alignment_output=alignment_output, + tblout=tblout, + domtblout=domtblout, + acc=acc, + noali=noali, + notextw=notextw, + textw=textw, + e_value_threshold=e_value_threshold, + score_threshold=score_threshold, + dom_e_value_threshold=dom_e_value_threshold, + dom_score_threshold=dom_score_threshold, + inc_e_value=inc_e_value, + inc_score=inc_score, + inc_dom_e_value=inc_dom_e_value, + inc_dom_score=inc_dom_score, + nobias=nobias, + nonull2=nonull2, + z_value=z_value, + dom_z_value=dom_z_value, + seed=seed, + qformat=qformat, + tformat=tformat, + cpu=cpu, + jackhmmer_iterations=iterations, + ) + +@mcp.tool() +def nhmmer( + seqfile: Path, + seqdb: Path, + output_file: Optional[Path] = None, + tblout: Optional[Path] = None, + domtblout: Optional[Path] = None, + acc: bool = False, + noali: bool = False, + notextw: bool = False, + textw: int = 120, + e_value_threshold: float = 10.0, + score_threshold: Optional[float] = None, + dom_e_value_threshold: float = 10.0, + dom_score_threshold: Optional[float] = None, + watson: bool = False, + crick: bool = False, + qformat: Optional[str] = None, + tformat: Optional[str] = None, + cpu: int = 1, +) -> dict: + """ + Search a DNA/RNA sequence against a DNA/RNA sequence database. + + Args: + seqfile: Input nucleotide sequence file. + seqdb: Target nucleotide sequence database file. + output_file: Direct output to a file instead of stdout. + tblout: Save a simple tabular output file. + domtblout: Save a simple tabular output file of domains. + acc: Use accessions instead of names in output. + noali: Do not output alignments, making the output smaller. + notextw: Unlimit ASCII text output line width. + textw: Set ASCII text output line width (default 120). + e_value_threshold: Report sequences with E-value <= this threshold. + score_threshold: Report sequences with score >= this threshold. + dom_e_value_threshold: Report domains with E-value <= this threshold. + dom_score_threshold: Report domains with score >= this threshold. + watson: Only search the top strand. + crick: Only search the bottom strand. + qformat: Assert query seqfile is in a specific format. + tformat: Assert target seqdb is in a specific format. + cpu: Number of parallel CPU workers to use. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + if not seqfile.is_file(): + raise FileNotFoundError(f"Input query file not found: {seqfile}") + if not seqdb.is_file(): + raise FileNotFoundError(f"Input database file not found: {seqdb}") + if watson and crick: + raise ValueError("Cannot use --watson and --crick simultaneously.") + if cpu < 1: + raise ValueError("The number of CPUs must be a positive integer (>=1).") + if notextw and textw != 120: + raise ValueError("Cannot specify --notextw and a custom --textw simultaneously.") + if not 0.0 <= e_value_threshold: + raise ValueError("E-value threshold must be non-negative.") + if not 0.0 <= dom_e_value_threshold: + raise ValueError("Domain E-value threshold must be non-negative.") + + cmd = ["nhmmer"] + output_files = [] + + if output_file: + cmd.extend(["-o", str(output_file)]) + output_files.append(str(output_file)) + if tblout: + cmd.extend(["--tblout", str(tblout)]) + output_files.append(str(tblout)) + if domtblout: + cmd.extend(["--domtblout", str(domtblout)]) + output_files.append(str(domtblout)) + if acc: + cmd.append("--acc") + if noali: + cmd.append("--noali") + if notextw: + cmd.append("--notextw") + elif textw != 120: + cmd.extend(["--textw", str(textw)]) + + if e_value_threshold != 10.0: + cmd.extend(["-E", str(e_value_threshold)]) + if score_threshold is not None: + cmd.extend(["-T", str(score_threshold)]) + if dom_e_value_threshold != 10.0: + cmd.extend(["--domE", str(dom_e_value_threshold)]) + if dom_score_threshold is not None: + cmd.extend(["--domT", str(dom_score_threshold)]) + + if watson: + cmd.append("--watson") + if crick: + cmd.append("--crick") + if qformat: + cmd.extend(["--qformat", qformat]) + if tformat: + cmd.extend(["--tformat", tformat]) + if cpu != 1: + cmd.extend(["--cpu", str(cpu)]) + + cmd.extend([str(seqfile), str(seqdb)]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"nhmmer failed with exit code {e.returncode}", + "output_files": [], + } + +@mcp.tool() +def nhmmscan( + hmmdb: Path, + seqfile: Path, + output_file: Optional[Path] = None, + tblout: Optional[Path] = None, + domtblout: Optional[Path] = None, + acc: bool = False, + noali: bool = False, + notextw: bool = False, + textw: int = 120, + e_value_threshold: float = 10.0, + score_threshold: Optional[float] = None, + dom_e_value_threshold: float = 10.0, + dom_score_threshold: Optional[float] = None, + cpu: int = 1, +) -> dict: + """ + Search a DNA/RNA sequence against a DNA/RNA profile HMM database. + Note: The HMM database must be prepared with `hmmpress` first. + + Args: + hmmdb: Nucleotide HMM profile database file (must be pressed). + seqfile: Input nucleotide sequence file. + output_file: Direct output to a file instead of stdout. + tblout: Save a simple tabular output file. + domtblout: Save a simple tabular output file of domains. + acc: Use accessions instead of names in output. + noali: Do not output alignments, making the output smaller. + notextw: Unlimit ASCII text output line width. + textw: Set ASCII text output line width (default 120). + e_value_threshold: Report sequences with E-value <= this threshold. + score_threshold: Report sequences with score >= this threshold. + dom_e_value_threshold: Report domains with E-value <= this threshold. + dom_score_threshold: Report domains with score >= this threshold. + cpu: Number of parallel CPU workers to use. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + if not hmmdb.is_file(): + raise FileNotFoundError(f"Input HMM database not found: {hmmdb}") + if not seqfile.is_file(): + raise FileNotFoundError(f"Input sequence file not found: {seqfile}") + if cpu < 1: + raise ValueError("The number of CPUs must be a positive integer (>=1).") + if notextw and textw != 120: + raise ValueError("Cannot specify --notextw and a custom --textw simultaneously.") + if not 0.0 <= e_value_threshold: + raise ValueError("E-value threshold must be non-negative.") + if not 0.0 <= dom_e_value_threshold: + raise ValueError("Domain E-value threshold must be non-negative.") + + cmd = ["nhmmscan"] + output_files = [] + + if output_file: + cmd.extend(["-o", str(output_file)]) + output_files.append(str(output_file)) + if tblout: + cmd.extend(["--tblout", str(tblout)]) + output_files.append(str(tblout)) + if domtblout: + cmd.extend(["--domtblout", str(domtblout)]) + output_files.append(str(domtblout)) + if acc: + cmd.append("--acc") + if noali: + cmd.append("--noali") + if notextw: + cmd.append("--notextw") + elif textw != 120: + cmd.extend(["--textw", str(textw)]) + + if e_value_threshold != 10.0: + cmd.extend(["-E", str(e_value_threshold)]) + if score_threshold is not None: + cmd.extend(["-T", str(score_threshold)]) + if dom_e_value_threshold != 10.0: + cmd.extend(["--domE", str(dom_e_value_threshold)]) + if dom_score_threshold is not None: + cmd.extend(["--domT", str(dom_score_threshold)]) + + if cpu != 1: + cmd.extend(["--cpu", str(cpu)]) + + cmd.extend([str(hmmdb), str(seqfile)]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"nhmmscan failed with exit code {e.returncode}", + "output_files": [], + } + +@mcp.tool() +def hmmalign( + hmmfile: Path, + seqfile: Path, + output_file: Optional[Path] = None, + trim: bool = False, + amino: bool = False, + dna: bool = False, + rna: bool = False, + informat: Optional[str] = None, + outformat: str = "Stockholm", + allcol: bool = False, + substitute: bool = False, + mapali: Optional[Path] = None, +) -> dict: + """ + Align sequences to a profile HMM. + + Args: + hmmfile: The profile HMM file. + seqfile: The sequence file to align. + output_file: Direct output to a file instead of stdout. + trim: Trim alignment to model consensus columns. + amino: Assert that the sequence file contains protein sequences. + dna: Assert that the sequence file contains DNA sequences. + rna: Assert that the sequence file contains RNA sequences. + informat: Assert that the input sequence file is in a specific format. + outformat: Output alignment in a specific format (default: Stockholm). + allcol: Show all columns, including non-consensus. + substitute: Substitute non-consensus residues with '.'. + mapali: Map coordinates from an existing alignment file. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + if not hmmfile.is_file(): + raise FileNotFoundError(f"Input HMM file not found: {hmmfile}") + if not seqfile.is_file(): + raise FileNotFoundError(f"Input sequence file not found: {seqfile}") + + seq_type_flags = [amino, dna, rna] + if sum(seq_type_flags) > 1: + raise ValueError("Only one of --amino, --dna, or --rna can be specified.") + + cmd = ["hmmalign"] + output_files = [] + + if output_file: + cmd.extend(["-o", str(output_file)]) + output_files.append(str(output_file)) + if trim: + cmd.append("--trim") + if amino: + cmd.append("--amino") + if dna: + cmd.append("--dna") + if rna: + cmd.append("--rna") + if informat: + cmd.extend(["--informat", informat]) + if outformat != "Stockholm": + cmd.extend(["--outformat", outformat]) + if allcol: + cmd.append("--allcol") + if substitute: + cmd.append("--sub") + if mapali: + if not mapali.is_file(): + raise FileNotFoundError(f"Map alignment file not found: {mapali}") + cmd.extend(["--mapali", str(mapali)]) + + cmd.extend([str(hmmfile), str(seqfile)]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"hmmalign failed with exit code {e.returncode}", + "output_files": [], + } + +@mcp.tool() +def hmmfetch( + hmmfile: Path, + key: Optional[str] = None, + output_file: Optional[Path] = None, + index_mode: bool = False, +) -> dict: + """ + Retrieve one or more profile HMMs from an HMM file or index it. + + Args: + hmmfile: The HMM file or database. + key: The key (name or accession) of the HMM to retrieve. Required if not in index_mode. + output_file: Output HMM to a file instead of stdout. + index_mode: If True, index the HMM file instead of fetching a key. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + if not hmmfile.is_file(): + raise FileNotFoundError(f"Input HMM file not found: {hmmfile}") + if not index_mode and not key: + raise ValueError("A 'key' must be provided unless in 'index_mode'.") + if index_mode and key: + raise ValueError("Cannot specify a 'key' when in 'index_mode'.") + + cmd = ["hmmfetch"] + output_files = [] + + if output_file: + cmd.extend(["-o", str(output_file)]) + output_files.append(str(output_file)) + + if index_mode: + cmd.append("--index") + cmd.append(str(hmmfile)) + else: + cmd.extend([str(hmmfile), key]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + if index_mode: + output_files.append(str(hmmfile.with_suffix(hmmfile.suffix + ".ssi"))) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"hmmfetch failed with exit code {e.returncode}", + "output_files": [], + } + +@mcp.tool() +def hmmstat( + hmmfile: Path, +) -> dict: + """ + Show summary statistics for a profile HMM file. + + Args: + hmmfile: The input HMM file. + + Returns: + A dictionary containing the command executed, stdout, and stderr. + """ + if not hmmfile.is_file(): + raise FileNotFoundError(f"Input HMM file not found: {hmmfile}") + + cmd = ["hmmstat", str(hmmfile)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"hmmstat failed with exit code {e.returncode}", + "output_files": [], + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hmmer/app/hmmer_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hmmer/app/hmmer_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..293561930eab7386f549de996c04261621071810 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hmmer/app/hmmer_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hmmer/app/hmmer_server.py') +SERVER_NAME = 'biosci_hmmer' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hmmer/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hmmer/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hmmer/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hmmer/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hmmer/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..dd08eb8769c85c85ce77b7ad5e606d160f1be880 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hmmer/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-hmmer: + build: . + image: mcp-hmmer:latest + container_name: mcp-hmmer + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=hmmer + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hmmer/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hmmer/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4e4863515ac3478c4bea4c93c882eb1ff9f20468 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hmmer/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - hmmer + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hmmer/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hmmer/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hmmer/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htseq/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htseq/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6e00cb1838cf5af18b49110381266a402d523abd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htseq/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install htseq via conda (e.g., from bioconda) +RUN conda install -c bioconda htseq -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/htseq_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/htseq_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/htseq_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htseq/app/htseq_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htseq/app/htseq_server.py new file mode 100644 index 0000000000000000000000000000000000000000..780129842686fc298384085062bebb4d6238cbd7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htseq/app/htseq_server.py @@ -0,0 +1,182 @@ +import subprocess +from pathlib import Path +from typing import Optional, List + +# Assume mcp is imported and the decorator is available +# import mcp + +@mcp.tool() +def htseq_count( + alignment_file: Path, + gff_file: Path, + output_file: Optional[Path] = None, + format: str = "sam", + order: str = "name", + stranded: str = "yes", + a: int = 10, + type: str = "exon", + idattr: str = "gene_id", + mode: str = "union", + nonunique: str = "none", + samout: Optional[Path] = None, + quiet: bool = False, + max_reads_in_buffer: int = 30000000, + nprocesses: int = 1, + add_chromosome_info: bool = False, + feature_query: str = "name", + secondary_alignments: str = "score", + supplementary_alignments: str = "score", +) -> dict: + """ + Runs htseq-count to count how many sequencing reads map to each feature. + + This tool takes an alignment file (SAM/BAM) and a feature file (GFF/GTF) + and calculates for each feature the number of reads mapping to it. + + Args: + alignment_file: The alignment file in SAM or BAM format. + gff_file: The feature file in GFF or GTF format. + output_file: Optional path to write the counts output. If not provided, + counts are returned in the 'stdout' field. + format: Type of alignment_file data. Must be 'sam' or 'bam'. + order: For paired-end data, sorting order of the alignment file. + Must be 'pos' or 'name'. + stranded: Whether the data is from a strand-specific assay. + Must be 'yes', 'no', or 'reverse'. + a: Skip all reads with alignment quality lower than this value. + type: Feature type (3rd column in GFF file) to be used. + idattr: GFF attribute to be used as feature ID (e.g., 'gene_id'). + mode: Mode to handle reads overlapping multiple features. Must be + 'union', 'intersection-strict', or 'intersection-nonempty'. + nonunique: Mode to handle reads that align to multiple features. + Must be 'none' or 'all'. + samout: Optional path to write out all SAM alignment records, annotated + with the feature they have been assigned to. + quiet: Suppress progress report and warnings. + max_reads_in_buffer: Maximum number of reads to keep in memory. + Must be a positive, even number. + nprocesses: Number of processes to use. + add_chromosome_info: Store chromosome and position of the feature. + feature_query: Method to query features. Must be 'name' or 'read'. + secondary_alignments: How to deal with secondary alignments. + Must be 'score' or 'ignore'. + supplementary_alignments: How to deal with supplementary alignments. + Must be 'score' or 'ignore'. + + Returns: + A dictionary containing the command executed, stdout, stderr, + and a list of output files. + """ + # --- Input Validation --- + if not alignment_file.is_file(): + raise FileNotFoundError(f"Alignment file not found: {alignment_file}") + if not gff_file.is_file(): + raise FileNotFoundError(f"GFF/GTF file not found: {gff_file}") + + # Validate choice parameters + valid_formats = ["sam", "bam"] + if format not in valid_formats: + raise ValueError(f"Invalid format '{format}'. Must be one of {valid_formats}") + + valid_orders = ["pos", "name"] + if order not in valid_orders: + raise ValueError(f"Invalid order '{order}'. Must be one of {valid_orders}") + + valid_stranded = ["yes", "no", "reverse"] + if stranded not in valid_stranded: + raise ValueError(f"Invalid strandedness '{stranded}'. Must be one of {valid_stranded}") + + valid_modes = ["union", "intersection-strict", "intersection-nonempty"] + if mode not in valid_modes: + raise ValueError(f"Invalid mode '{mode}'. Must be one of {valid_modes}") + + valid_nonunique = ["none", "all"] + if nonunique not in valid_nonunique: + raise ValueError(f"Invalid nonunique mode '{nonunique}'. Must be one of {valid_nonunique}") + + valid_feature_query = ["name", "read"] + if feature_query not in valid_feature_query: + raise ValueError(f"Invalid feature_query '{feature_query}'. Must be one of {valid_feature_query}") + + valid_secondary = ["score", "ignore"] + if secondary_alignments not in valid_secondary: + raise ValueError(f"Invalid secondary_alignments mode '{secondary_alignments}'. Must be one of {valid_secondary}") + + valid_supplementary = ["score", "ignore"] + if supplementary_alignments not in valid_supplementary: + raise ValueError(f"Invalid supplementary_alignments mode '{supplementary_alignments}'. Must be one of {valid_supplementary}") + + # Validate integer parameters + if a < 0: + raise ValueError("Minimum alignment quality 'a' cannot be negative.") + if max_reads_in_buffer <= 0 or max_reads_in_buffer % 2 != 0: + raise ValueError("'max_reads_in_buffer' must be a positive, even number.") + if nprocesses < 1: + raise ValueError("'nprocesses' must be at least 1.") + + # --- Command Construction --- + cmd = ["htseq-count"] + cmd.extend(["--format", format]) + cmd.extend(["--order", order]) + cmd.extend(["--stranded", stranded]) + cmd.extend(["-a", str(a)]) + cmd.extend(["--type", type]) + cmd.extend(["--idattr", idattr]) + cmd.extend(["--mode", mode]) + cmd.extend(["--nonunique", nonunique]) + cmd.extend(["--max-reads-in-buffer", str(max_reads_in_buffer)]) + cmd.extend(["--nprocesses", str(nprocesses)]) + cmd.extend(["--feature-query", feature_query]) + cmd.extend(["--secondary-alignments", secondary_alignments]) + cmd.extend(["--supplementary-alignments", supplementary_alignments]) + + if samout: + cmd.extend(["--samout", str(samout)]) + if quiet: + cmd.append("--quiet") + if add_chromosome_info: + cmd.append("--add-chromosome-info") + + # Positional arguments must be last + cmd.extend([str(alignment_file), str(gff_file)]) + command_executed = " ".join(cmd) + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + + output_files: List[str] = [] + if output_file: + output_file.write_text(result.stdout) + output_files.append(str(output_file)) + if samout: + output_files.append(str(samout)) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'htseq-count' command not found. Please ensure HTSeq is installed and in your PATH.", + "error": "Command not found", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"htseq-count failed with exit code {e.returncode}", + "output_files": [] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htseq/app/htseq_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htseq/app/htseq_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f19fa64dbc17fc317871060c18fbafe677f36cce --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htseq/app/htseq_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htseq/app/htseq_server.py') +SERVER_NAME = 'biosci_htseq' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htseq/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htseq/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htseq/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htseq/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htseq/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..9866d73ab39b96b4a7d11b9f2fba35598e22e1c2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htseq/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-htseq: + build: . + image: mcp-htseq:latest + container_name: mcp-htseq + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=htseq + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htseq/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htseq/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..93913d98e91a3b073b9de5b75cdad7f2180ef59c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htseq/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - htseq + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htseq/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htseq/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htseq/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htslib/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htslib/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..69287830e207e0566ca244844e6c92df8c650ebd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htslib/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install htslib via conda (e.g., from bioconda) +RUN conda install -c bioconda htslib -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/htslib_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/htslib_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/htslib_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htslib/app/htslib_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htslib/app/htslib_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f9eb4947a86b6ae962a409a56c3c39cf997b78aa --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htslib/app/htslib_server.py @@ -0,0 +1,367 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# @mcp.tool() decorator is implied for each function as per the instructions. + +def bgzip( + file: Path, + output: Optional[Path] = None, + stdout: bool = False, + decompress: bool = False, + force: bool = False, + index: bool = False, + index_name: Optional[Path] = None, + reindex: bool = False, + rebgzip: bool = False, + test: bool = False, + compress_level: int = -1, + size: int = 0, + threads: int = 1, +): + """ + Compresses or decompresses files in a block-based GZIP (BGZF) format. + + bgzip is a block-based compression utility that is compatible with GZIP. + It is essential for creating indexable compressed genomic data files. + """ + # Input validation + if not file.exists(): + raise FileNotFoundError(f"Input file not found: {file}") + if compress_level < -1 or compress_level > 9: + raise ValueError("compress_level must be between -1 and 9.") + if threads < 1: + raise ValueError("threads must be at least 1.") + if size < 0: + raise ValueError("size must be a non-negative integer.") + if stdout and output: + raise ValueError("Cannot use --output and --stdout simultaneously.") + if decompress and rebgzip: + raise ValueError("Cannot use --decompress and --rebgzip simultaneously.") + + cmd = ["bgzip"] + + if stdout: + cmd.append("--stdout") + if decompress: + cmd.append("--decompress") + if force: + cmd.append("--force") + if index: + cmd.append("--index") + if reindex: + cmd.append("--reindex") + if rebgzip: + cmd.append("--rebgzip") + if test: + cmd.append("--test") + + if output: + cmd.extend(["--output", str(output)]) + if index_name: + cmd.extend(["--index-name", str(index_name)]) + if compress_level != -1: + cmd.extend(["--compress-level", str(compress_level)]) + if size > 0: + cmd.extend(["--size", str(size)]) + if threads > 1: + cmd.extend(["--threads", str(threads)]) + + cmd.append(str(file)) + + command_executed = " ".join(cmd) + output_files = [] + + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + if output: + output_files.append(str(output)) + elif not stdout and not test: + # Infer output file name + if decompress: + if str(file).endswith(".gz"): + output_files.append(str(file)[:-3]) + else: + output_files.append(f"{file}.gz") + + if index and index_name: + output_files.append(str(index_name)) + elif index and not stdout: + output_files.append(f"{output or file}.gzi") + + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": f"bgzip failed with exit code {e.returncode}", + } + + +def tabix( + in_file: Path, + regions: Optional[List[str]] = None, + preset: Optional[str] = None, + sequence_col: int = 0, + begin_col: int = 0, + end_col: int = 0, + skip_lines: int = 0, + comment_char: str = "#", + zero_based: bool = False, + force: bool = False, + csi: bool = False, + min_shift: int = 0, + list_chroms: bool = False, + print_header: bool = False, + header_only: bool = False, + region_file: Optional[Path] = None, +): + """ + Indexes or queries TAB-delimited genome position files. + + Tabix can be used in two modes: + 1. Indexing: If 'regions' and 'region_file' are not provided, it creates an index file for in_file. + 2. Querying: If 'regions' or 'region_file' is provided, it retrieves data for those regions. + """ + # Input validation + if not in_file.exists(): + raise FileNotFoundError(f"Input file not found: {in_file}") + if region_file and not region_file.exists(): + raise FileNotFoundError(f"Region file not found: {region_file}") + if regions and region_file: + raise ValueError("Cannot specify both 'regions' and 'region_file'.") + if preset and preset not in ["gff", "bed", "sam", "vcf", "psltbl"]: + raise ValueError("Invalid preset. Must be one of: gff, bed, sam, vcf, psltbl.") + if list_chroms and (regions or region_file): + raise ValueError("Cannot use --list-chroms with region queries.") + + is_indexing = not (regions or region_file or list_chroms) + + cmd = ["tabix"] + + # Indexing options + if is_indexing: + if preset: + cmd.extend(["--preset", preset]) + if sequence_col > 0: + cmd.extend(["--sequence", str(sequence_col)]) + if begin_col > 0: + cmd.extend(["--begin", str(begin_col)]) + if end_col > 0: + cmd.extend(["--end", str(end_col)]) + if skip_lines > 0: + cmd.extend(["--skip-lines", str(skip_lines)]) + if comment_char != "#": + cmd.extend(["--comment", comment_char]) + if zero_based: + cmd.append("--zero-based") + if force: + cmd.append("--force") + if csi: + cmd.append("--csi") + if min_shift > 0: + cmd.extend(["--min-shift", str(min_shift)]) + # Querying options + else: + if print_header: + cmd.append("--print-header") + if header_only: + cmd.append("--header-only") + if list_chroms: + cmd.append("--list-chroms") + if region_file: + cmd.extend(["--region-file", str(region_file)]) + + cmd.append(str(in_file)) + + if regions: + cmd.extend(regions) + + command_executed = " ".join(cmd) + output_files = [] + + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + if is_indexing: + index_suffix = ".csi" if csi else ".tbi" + output_files.append(f"{in_file}{index_suffix}") + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": f"tabix failed with exit code {e.returncode}", + } + + +def htsfile( + file: Path, + print_format: bool = False, + print_compression: bool = False, + header_only: bool = False, + no_header: bool = False, +): + """ + Identifies file type, compression, and prints headers for HTS files. + + This utility inspects a high-throughput sequencing file (e.g., SAM, BAM, CRAM, VCF, BCF) + and reports its properties. + """ + # Input validation + if not file.exists(): + raise FileNotFoundError(f"Input file not found: {file}") + if header_only and no_header: + raise ValueError("Cannot use --header-only and --no-header simultaneously.") + + cmd = ["htsfile"] + + if print_format: + cmd.append("--print-format") + if print_compression: + cmd.append("--print-compression") + if header_only: + cmd.append("--header-only") + if no_header: + cmd.append("--no-header") + + cmd.append(str(file)) + + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": f"htsfile failed with exit code {e.returncode}", + } + + +def annot_tsv( + vcf_file: Path, + annotations: Path, + columns: Optional[str] = None, + definitions: Optional[Path] = None, + output: Optional[Path] = None, + output_type: str = "v", + regions: Optional[str] = None, + regions_file: Optional[Path] = None, + samples: Optional[str] = None, + samples_file: Optional[Path] = None, + header_only: bool = False, + threads: int = 1, +): + """ + Annotates a VCF/BCF file from a tab-delimited file. + """ + # Input validation + if not vcf_file.exists(): + raise FileNotFoundError(f"Input VCF/BCF file not found: {vcf_file}") + if not annotations.exists(): + raise FileNotFoundError(f"Annotation file not found: {annotations}") + if definitions and not definitions.exists(): + raise FileNotFoundError(f"Definitions file not found: {definitions}") + if regions and regions_file: + raise ValueError("Cannot specify both --regions and --regions-file.") + if samples and samples_file: + raise ValueError("Cannot specify both --samples and --samples-file.") + if output_type not in ["b", "u", "z", "v"]: + raise ValueError("output_type must be one of 'b', 'u', 'z', or 'v'.") + if threads < 1: + raise ValueError("threads must be at least 1.") + + cmd = ["annot-tsv"] + + cmd.extend(["--annotations", str(annotations)]) + + if columns: + cmd.extend(["--columns", columns]) + if definitions: + cmd.extend(["--definitions", str(definitions)]) + if output: + cmd.extend(["--output", str(output)]) + if output_type: + cmd.extend(["--output-type", output_type]) + if regions: + cmd.extend(["--regions", regions]) + if regions_file: + cmd.extend(["--regions-file", str(regions_file)]) + if samples: + cmd.extend(["--samples", samples]) + if samples_file: + cmd.extend(["--samples-file", str(samples_file)]) + if header_only: + cmd.append("--header-only") + if threads > 1: + cmd.extend(["--threads", str(threads)]) + + cmd.append(str(vcf_file)) + + command_executed = " ".join(cmd) + output_files = [] + + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + if output: + output_files.append(str(output)) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": f"annot-tsv failed with exit code {e.returncode}", + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htslib/app/htslib_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htslib/app/htslib_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..886cb471b6bebd90cfbc4acbf26aeb69c1d3bef5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htslib/app/htslib_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htslib/app/htslib_server.py') +SERVER_NAME = 'biosci_htslib' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htslib/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htslib/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htslib/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htslib/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htslib/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..ed1c9e129291fbe8bab6941dab7a18082047c5cf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htslib/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-htslib: + build: . + image: mcp-htslib:latest + container_name: mcp-htslib + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=htslib + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htslib/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htslib/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..aafce78bd43bd2f24a107348daec9a28fea2f0fd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htslib/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - htslib + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htslib/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htslib/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_htslib/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_humann/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_humann/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_humann/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_humann2/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_humann2/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ceb86a74d9ee61bc7e36c4ad956473f05f286495 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_humann2/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install humann2 via conda (e.g., from bioconda) +RUN conda install -c bioconda humann2 -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/humann2_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/humann2_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/humann2_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_humann2/app/humann2_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_humann2/app/humann2_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f798b3cd964ac0cd8d88f9e86d2de64bb3cb563a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_humann2/app/humann2_server.py @@ -0,0 +1,701 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Literal, Optional + +# It is assumed that the @mcp.tool decorator is available in the execution environment. +# Since we cannot import it, we will define a placeholder decorator to allow the code to be syntactically valid. +def tool(*args, **kwargs): + def decorator(f): + return f + return decorator + +mcp = type("mcp", (), {"tool": tool}) + + +@mcp.tool() +def humann2( + input_file: Path, + output_dir: Path, + input_format: Optional[Literal["fastq", "fasta", "sam", "bam", "biom"]] = None, + output_format: Literal["tsv", "biom"] = "tsv", + output_max_decimals: int = 10, + output_basename: Optional[str] = None, + remove_temp_output: bool = False, + log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = "INFO", + bypass_prescreen: bool = False, + bypass_nucleotide_index: bool = False, + bypass_translated_search: bool = False, + bypass_nucleotide_search: bool = False, + verbose: bool = False, + threads: int = 1, + prescreen_threshold: float = 0.01, + identity_threshold: float = 50.0, + translated_subject_coverage_threshold: float = 50.0, + translated_query_coverage_threshold: float = 90.0, + nucleotide_subject_coverage_threshold: float = 50.0, + nucleotide_query_coverage_threshold: float = 90.0, + evalue_threshold: float = 1.0, + pathways_database: Optional[Path] = None, + nucleotide_database: Optional[Path] = None, + protein_database: Optional[Path] = None, + search_mode: Literal["uniref50", "uniref90"] = "uniref50", + gap_fill: Literal["on", "off"] = "on", + minpath: Literal["on", "off"] = "on", + xipe: Literal["on", "off"] = "off", + o_log: Optional[Path] = None, + remove_stratified_output: bool = False, + remove_column_headers_from_pathabundance: bool = False, + taxonomic_profile: Optional[Path] = None, + id_mapping: Optional[Path] = None, + pathways: Literal["metacyc", "unipathway"] = "metacyc", + memory_use: Literal["minimum", "maximum"] = "maximum", + resume: bool = False, +) -> dict: + """ + Runs the HUMAnN2 pipeline for metagenomic or metatranscriptomic functional profiling. + + Args: + input_file: Path to the input file (fastq, fasta, sam, bam, or biom format). + output_dir: Path to the directory to write output files. + input_format: The format of the input file. + output_format: The format of the final output files. + output_max_decimals: The number of decimals to print in the output files. + output_basename: The basename of the output files. + remove_temp_output: If True, remove temporary output files. + log_level: The logging level. + bypass_prescreen: If True, bypass the prescreen step. + bypass_nucleotide_index: If True, bypass the nucleotide index step. + bypass_translated_search: If True, bypass the translated search step. + bypass_nucleotide_search: If True, bypass the nucleotide search step. + verbose: If True, provide additional printouts during the run. + threads: Number of threads/processes to use. + prescreen_threshold: Percent of reads that must map to continue with nucleotide search. + identity_threshold: Identity threshold for alignments. + translated_subject_coverage_threshold: Subject coverage threshold for translated alignments. + translated_query_coverage_threshold: Query coverage threshold for translated alignments. + nucleotide_subject_coverage_threshold: Subject coverage threshold for nucleotide alignments. + nucleotide_query_coverage_threshold: Query coverage threshold for nucleotide alignments. + evalue_threshold: E-value threshold for alignments. + pathways_database: Path to the pathways database. + nucleotide_database: Path to the nucleotide database. + protein_database: Path to the protein database. + search_mode: The search mode to use. + gap_fill: Turn gap filling on or off. + minpath: Turn MinPath on or off. + xipe: Turn XIPE on or off. + o_log: Path to the log file. + remove_stratified_output: If True, do not create stratified output files. + remove_column_headers_from_pathabundance: If True, do not print column headers in pathabundance output. + taxonomic_profile: Path to a taxonomic profile file for prescreening. + id_mapping: Path to a file for mapping IDs to gene families. + pathways: The pathways database to use. + memory_use: The memory use setting. + resume: If True, resume a previous run. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output file paths. + """ + # Input validation + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if threads < 1: + raise ValueError("Number of threads must be at least 1.") + if not (0.0 <= prescreen_threshold <= 100.0): + raise ValueError("prescreen_threshold must be between 0.0 and 100.0.") + if not (0.0 <= identity_threshold <= 100.0): + raise ValueError("identity_threshold must be between 0.0 and 100.0.") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "humann2", + "--input", str(input_file), + "--output", str(output_dir), + "--output-format", output_format, + "--output-max-decimals", str(output_max_decimals), + "--log-level", log_level, + "--threads", str(threads), + "--prescreen-threshold", str(prescreen_threshold), + "--identity-threshold", str(identity_threshold), + "--translated-subject-coverage-threshold", str(translated_subject_coverage_threshold), + "--translated-query-coverage-threshold", str(translated_query_coverage_threshold), + "--nucleotide-subject-coverage-threshold", str(nucleotide_subject_coverage_threshold), + "--nucleotide-query-coverage-threshold", str(nucleotide_query_coverage_threshold), + "--evalue-threshold", str(evalue_threshold), + "--search-mode", search_mode, + "--gap-fill", gap_fill, + "--minpath", minpath, + "--xipe", xipe, + "--pathways", pathways, + "--memory-use", memory_use, + ] + + # Optional arguments + if input_format: + cmd.extend(["--input-format", input_format]) + if output_basename: + cmd.extend(["--output-basename", output_basename]) + else: + output_basename = input_file.stem + if remove_temp_output: + cmd.append("--remove-temp-output") + if bypass_prescreen: + cmd.append("--bypass-prescreen") + if bypass_nucleotide_index: + cmd.append("--bypass-nucleotide-index") + if bypass_translated_search: + cmd.append("--bypass-translated-search") + if bypass_nucleotide_search: + cmd.append("--bypass-nucleotide-search") + if verbose: + cmd.append("--verbose") + if pathways_database: + cmd.extend(["--pathways-database", str(pathways_database)]) + if nucleotide_database: + cmd.extend(["--nucleotide-database", str(nucleotide_database)]) + if protein_database: + cmd.extend(["--protein-database", str(protein_database)]) + if o_log: + cmd.extend(["--o-log", str(o_log)]) + if remove_stratified_output: + cmd.append("--remove-stratified-output") + if remove_column_headers_from_pathabundance: + cmd.append("--remove-column-headers-from-pathabundance") + if taxonomic_profile: + cmd.extend(["--taxonomic-profile", str(taxonomic_profile)]) + if id_mapping: + cmd.extend(["--id-mapping", str(id_mapping)]) + if resume: + cmd.append("--resume") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + + # Define expected output files + gene_families_file = output_dir / f"{output_basename}_genefamilies.{output_format}" + path_abundance_file = output_dir / f"{output_basename}_pathabundance.{output_format}" + path_coverage_file = output_dir / f"{output_basename}_pathcoverage.{output_format}" + + output_files = [ + str(p) for p in [gene_families_file, path_abundance_file, path_coverage_file] if p.exists() + ] + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"humann2 failed with exit code {e.returncode}", + "output_files": [], + } + + +@mcp.tool() +def humann2_join_tables( + input_dir: Path, + output_file: Path, + file_name: str = "humann2_genefamilies.tsv", + verbose: bool = False, + search_subdirectories: bool = False, + sample_name_in_header: bool = False, +) -> dict: + """ + Joins multiple HUMAnN2 output tables into a single table. + + Args: + input_dir: Path to the directory of HUMAnN2 output files to join. + output_file: Path to the file to write the joined table to. + file_name: The name of the files in the directory to join. + verbose: If True, provide additional printouts. + search_subdirectories: If True, search subdirectories for files to join. + sample_name_in_header: If True, expect sample name in the header instead of the file name. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the output file path. + """ + if not input_dir.is_dir(): + raise FileNotFoundError(f"Input directory not found: {input_dir}") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + cmd = [ + "humann2_join_tables", + "--input", str(input_dir), + "--output", str(output_file), + "--file_name", file_name, + ] + + if verbose: + cmd.append("--verbose") + if search_subdirectories: + cmd.append("--search-subdirectories") + if sample_name_in_header: + cmd.append("--sample-name-in-header") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file)] if output_file.exists() else [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"humann2_join_tables failed with exit code {e.returncode}", + "output_files": [], + } + + +@mcp.tool() +def humann2_renorm_table( + input_file: Path, + output_file: Path, + units: Literal["cpm", "relab"] = "cpm", + verbose: bool = False, + update_snames: Optional[Path] = None, + special: Optional[Literal["UNMAPPED", "UNGROUPED", "UNINTEGRATED"]] = None, + mode: Literal["community", "sample"] = "community", +) -> dict: + """ + Renormalizes a HUMAnN2 output table to new units. + + Args: + input_file: Path to the input table to renormalize. + output_file: Path to the file to write the renormalized table to. + units: The units to convert to (copies per million or relative abundance). + verbose: If True, provide additional printouts. + update_snames: Path to a file to replace sample names with new names. + special: Handle special features (UNMAPPED, UNGROUPED, UNINTEGRATED). + mode: Renormalize by community total or by sample total. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the output file path. + """ + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + cmd = [ + "humann2_renorm_table", + "--input", str(input_file), + "--output", str(output_file), + "--units", units, + "--mode", mode, + ] + + if verbose: + cmd.append("--verbose") + if update_snames: + if not update_snames.is_file(): + raise FileNotFoundError(f"Sample names file not found: {update_snames}") + cmd.extend(["--update-snames", str(update_snames)]) + if special: + cmd.extend(["--special", special]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file)] if output_file.exists() else [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"humann2_renorm_table failed with exit code {e.returncode}", + "output_files": [], + } + + +@mcp.tool() +def humann2_regroup_table( + input_file: Path, + output_file: Path, + groups: Optional[str] = None, + custom: Optional[Path] = None, + ungrouped: bool = False, + verbose: bool = False, +) -> dict: + """ + Regroups a HUMAnN2 gene families table to a new functional classification. + + Args: + input_file: Path to the input table to regroup. + output_file: Path to the file to write the regrouped table to. + groups: The database groups to use (e.g., uniref50_ko). + custom: Path to a custom mapping file for regrouping. + ungrouped: If True, report the total of all features not in a group. + verbose: If True, provide additional printouts. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the output file path. + """ + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if not groups and not custom: + raise ValueError("Either --groups or --custom must be provided.") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + cmd = [ + "humann2_regroup_table", + "--input", str(input_file), + "--output", str(output_file), + ] + + if groups: + cmd.extend(["--groups", groups]) + if custom: + if not custom.is_file(): + raise FileNotFoundError(f"Custom mapping file not found: {custom}") + cmd.extend(["--custom", str(custom)]) + if ungrouped: + cmd.append("--ungrouped") + if verbose: + cmd.append("--verbose") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file)] if output_file.exists() else [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"humann2_regroup_table failed with exit code {e.returncode}", + "output_files": [], + } + + +@mcp.tool() +def humann2_split_table( + input_file: Path, + output_dir: Path, + group_metadata: Optional[Path] = None, + group_column: Optional[str] = None, +) -> dict: + """ + Splits a HUMAnN2 table into multiple tables based on sample metadata. + + Args: + input_file: Path to the input table to split. + output_dir: Path to the directory to write the split tables to. + group_metadata: Path to a metadata file for grouping samples. + group_column: The column in the metadata file to use for grouping. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output file paths. + """ + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if group_metadata and not group_column: + raise ValueError("--group-column is required when --group-metadata is provided.") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "humann2_split_table", + "--input", str(input_file), + "--output", str(output_dir), + ] + + if group_metadata: + if not group_metadata.is_file(): + raise FileNotFoundError(f"Metadata file not found: {group_metadata}") + cmd.extend(["--group-metadata", str(group_metadata)]) + cmd.extend(["--group-column", group_column]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + # Since output files are numerous and names are data-dependent, list directory contents + output_files = [str(p) for p in output_dir.glob('*')] + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"humann2_split_table failed with exit code {e.returncode}", + "output_files": [], + } + + +@mcp.tool() +def humann2_stratify_table( + input_file: Path, + output_file: Path, + remove_zeros: bool = False, + verbose: bool = False, +) -> dict: + """ + Stratifies a HUMAnN2 table, separating contributions from different taxa. + + Args: + input_file: Path to the input table to stratify. + output_file: Path to the file to write the stratified table to. + remove_zeros: If True, remove rows with all zeros from the output. + verbose: If True, provide additional printouts. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the output file path. + """ + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + cmd = [ + "humann2_stratify_table", + "--input", str(input_file), + "--output", str(output_file), + ] + + if remove_zeros: + cmd.append("--remove-zeros") + if verbose: + cmd.append("--verbose") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file)] if output_file.exists() else [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"humann2_stratify_table failed with exit code {e.returncode}", + "output_files": [], + } + + +@mcp.tool() +def humann2_barplot( + input_file: Path, + output_file: Path, + fignum: int = 1, + sort: Literal["sum", "metadata"] = "sum", + as_genera: bool = False, + top: int = 10, + last: str = "Other", + scaling: Literal["log", "sqrt", "none"] = "log", + metadata: Optional[Path] = None, + category: Optional[str] = None, + colormap: str = "jet", + xlabel: str = "Sample", + ylabel: str = "Abundance", + title: str = "HUMAnN2 Barplot", +) -> dict: + """ + Generates a barplot from a HUMAnN2 abundance table. + + Args: + input_file: Path to the input table to plot. + output_file: Path to the file to write the plot to. + fignum: The figure number to use. + sort: The method to sort the samples. + as_genera: If True, treat taxa as genera. + top: The number of top features to plot. + last: The name of the last feature to plot (e.g., 'Other'). + scaling: The scaling to use for the plot. + metadata: Path to a metadata file for sorting. + category: The category in the metadata file to use for sorting. + colormap: The colormap to use for the plot. + xlabel: The x-axis label. + ylabel: The y-axis label. + title: The title of the plot. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the output file path. + """ + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if sort == "metadata" and not metadata: + raise ValueError("--metadata is required when sort='metadata'.") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + cmd = [ + "humann2_barplot", + "--input", str(input_file), + "--output", str(output_file), + "--fignum", str(fignum), + "--sort", sort, + "--top", str(top), + "--last", last, + "--scaling", scaling, + "--colormap", colormap, + "--xlabel", xlabel, + "--ylabel", ylabel, + "--title", title, + ] + + if as_genera: + cmd.append("--as-genera") + if metadata: + if not metadata.is_file(): + raise FileNotFoundError(f"Metadata file not found: {metadata}") + cmd.extend(["--metadata", str(metadata)]) + if category: + cmd.extend(["--category", category]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file)] if output_file.exists() else [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"humann2_barplot failed with exit code {e.returncode}", + "output_files": [], + } + + +@mcp.tool() +def humann2_build_custom_database( + input_file: Path, + output_dir: Path, + database_type: Literal["nucleotide", "protein"], + id_mapping: Optional[Path] = None, +) -> dict: + """ + Builds a custom database for use with HUMAnN2. + + Args: + input_file: Path to the input fasta file of sequences. + output_dir: Path to the directory to write the new database to. + database_type: The type of database to build. + id_mapping: Path to a file mapping sequence IDs to gene families. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + if not input_file.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_file}") + + output_dir.mkdir(parents=True, exist_ok=True) + + cmd = [ + "humann2_build_custom_database", + "--input", str(input_file), + "--output", str(output_dir), + "--database-type", database_type, + ] + + if id_mapping: + if not id_mapping.is_file(): + raise FileNotFoundError(f"ID mapping file not found: {id_mapping}") + cmd.extend(["--id-mapping", str(id_mapping)]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + # Output files are numerous and names are data-dependent, list directory contents + output_files = [str(p) for p in output_dir.glob('*')] + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"humann2_build_custom_database failed with exit code {e.returncode}", + "output_files": [], + } + + +@mcp.tool() +def humann2_databases( + download: Optional[Literal["chocophlan", "uniref", "utility_mapping"]] = None, + location: Optional[Path] = None, + update_config: bool = False, + database_version: Literal["DEMO", "FULL"] = "FULL", +) -> dict: + """ + Downloads and manages HUMAnN2 databases. + + Args: + download: The name of the database to download. + location: The location to download the database to. + update_config: If True, update the HUMAnN2 config file with new database locations. + database_version: The version of the database to download. + + Returns: + A dictionary containing the command executed, stdout, and stderr. + """ + cmd = ["humann2_databases"] + + if download: + if not location: + raise ValueError("--location is required when --download is specified.") + location.mkdir(parents=True, exist_ok=True) + cmd.extend(["--download", download, "--location", str(location)]) + cmd.extend(["--database-version", database_version]) + elif update_config: + cmd.append("--update-config") + else: + raise ValueError("Either --download or --update-config must be specified.") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"humann2_databases failed with exit code {e.returncode}", + "output_files": [], + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_humann2/app/humann2_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_humann2/app/humann2_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3fbb6d58b5dd3ba5dd45a4a7ea93f3a4cdcb0545 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_humann2/app/humann2_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_humann2/app/humann2_server.py') +SERVER_NAME = 'biosci_humann2' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_humann2/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_humann2/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_humann2/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_humann2/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_humann2/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d1bcef4b160ba0701e2f86aad71612d1159f48bc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_humann2/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-humann2: + build: . + image: mcp-humann2:latest + container_name: mcp-humann2 + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=humann2 + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_humann2/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_humann2/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e5787cc4a7f121c3e7a86599704c4117d3d1c16d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_humann2/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - humann2 + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_humann2/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_humann2/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_humann2/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hyphy/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hyphy/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_hyphy/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv-reports/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv-reports/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4f8266af1a8a5e654f894375d913f122d410ffdf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv-reports/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install igv-reports via conda (e.g., from bioconda) +RUN conda install -c bioconda igv-reports -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/igv-reports_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/igv-reports_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/igv-reports_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv-reports/app/igv-reports_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv-reports/app/igv-reports_server.py new file mode 100644 index 0000000000000000000000000000000000000000..75d05f1707cdef2021fc1c05c81bc9b473e0a299 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv-reports/app/igv-reports_server.py @@ -0,0 +1,385 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, List + +# Configure logging +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') + +# Mock decorator for standalone execution and clarity. +# In a real MCP environment, this would be provided by the MCP framework. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +@mcp.tool() +def create_report( + sites: Path, + fasta: Path, + tracks: Optional[List[Path]] = None, + track_config: Optional[Path] = None, + ideogram: Optional[Path] = None, + template: Optional[Path] = None, + output: Optional[Path] = None, + title: Optional[str] = None, + begin: Optional[int] = None, + end: Optional[int] = None, + sequence: Optional[str] = None, + flanking: Optional[int] = None, + standalone: bool = False, + sort: bool = False, +): + """ + Creates a general purpose igv-report from a VCF, BED, MAF, or GFF file. + """ + # --- Input Validation --- + if not sites.is_file(): + raise FileNotFoundError(f"Input sites file not found: {sites}") + if not fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {fasta}") + if not fasta.with_suffix(fasta.suffix + '.fai').is_file(): + logging.warning(f"FASTA index (.fai) not found for {fasta}. The tool may fail or be slow.") + + # Validate optional file paths + if tracks: + for track in tracks: + if not track.is_file(): + raise FileNotFoundError(f"Track file not found: {track}") + if track_config and not track_config.is_file(): + raise FileNotFoundError(f"Track config file not found: {track_config}") + if ideogram and not ideogram.is_file(): + raise FileNotFoundError(f"Ideogram file not found: {ideogram}") + if template and not template.is_file(): + raise FileNotFoundError(f"Template file not found: {template}") + + # Validate single-locus report parameters + single_locus_params = [begin is not None, end is not None, sequence is not None] + if any(single_locus_params) and not all(single_locus_params): + raise ValueError("For a single-locus report, --begin, --end, and --sequence must all be provided.") + + if flanking is not None and flanking < 0: + raise ValueError("--flanking must be a non-negative integer.") + + # --- Command Construction --- + cmd = ["igv-reports", "create-report", str(sites)] + cmd.extend(["--fasta", str(fasta)]) + + if tracks: + cmd.append("--tracks") + cmd.extend([str(t) for t in tracks]) + if track_config: + cmd.extend(["--track-config", str(track_config)]) + if ideogram: + cmd.extend(["--ideogram", str(ideogram)]) + if template: + cmd.extend(["--template", str(template)]) + if output: + cmd.extend(["--output", str(output)]) + if title: + cmd.extend(["--title", title]) + if begin is not None: + cmd.extend(["--begin", str(begin)]) + if end is not None: + cmd.extend(["--end", str(end)]) + if sequence: + cmd.extend(["--sequence", sequence]) + if flanking is not None: + cmd.extend(["--flanking", str(flanking)]) + if standalone: + cmd.append("--standalone") + if sort: + cmd.append("--sort") + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + encoding='utf-8' + ) + + output_file = output if output else sites.with_suffix(".html") + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file.resolve())] + } + except FileNotFoundError: + raise RuntimeError("igv-reports command not found. Please ensure it is installed and in your PATH.") + except subprocess.CalledProcessError as e: + logging.error(f"igv-reports failed with exit code {e.returncode}:\n{e.stderr}") + raise RuntimeError(f"igv-reports execution failed: {e.stderr}") from e + +@mcp.tool() +def create_vcf_report( + vcf: Path, + fasta: Path, + tracks: Optional[List[Path]] = None, + track_config: Optional[Path] = None, + ideogram: Optional[Path] = None, + template: Optional[Path] = None, + output: Optional[Path] = None, + title: Optional[str] = None, + info_columns: Optional[List[str]] = None, + info_columns_file: Optional[Path] = None, + sample_columns: Optional[List[str]] = None, + sample_columns_file: Optional[Path] = None, + flanking: Optional[int] = None, + standalone: bool = False, + sort: bool = False, +): + """ + Creates a variant report from a VCF file. + """ + # --- Input Validation --- + if not vcf.is_file(): + raise FileNotFoundError(f"Input VCF file not found: {vcf}") + if not fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {fasta}") + if not fasta.with_suffix(fasta.suffix + '.fai').is_file(): + logging.warning(f"FASTA index (.fai) not found for {fasta}. The tool may fail or be slow.") + + if tracks: + for track in tracks: + if not track.is_file(): + raise FileNotFoundError(f"Track file not found: {track}") + if track_config and not track_config.is_file(): + raise FileNotFoundError(f"Track config file not found: {track_config}") + if ideogram and not ideogram.is_file(): + raise FileNotFoundError(f"Ideogram file not found: {ideogram}") + if template and not template.is_file(): + raise FileNotFoundError(f"Template file not found: {template}") + if info_columns_file and not info_columns_file.is_file(): + raise FileNotFoundError(f"Info columns file not found: {info_columns_file}") + if sample_columns_file and not sample_columns_file.is_file(): + raise FileNotFoundError(f"Sample columns file not found: {sample_columns_file}") + + if flanking is not None and flanking < 0: + raise ValueError("--flanking must be a non-negative integer.") + + # --- Command Construction --- + cmd = ["igv-reports", "create-vcf-report", str(vcf)] + cmd.extend(["--fasta", str(fasta)]) + + if tracks: + cmd.append("--tracks") + cmd.extend([str(t) for t in tracks]) + if track_config: + cmd.extend(["--track-config", str(track_config)]) + if ideogram: + cmd.extend(["--ideogram", str(ideogram)]) + if template: + cmd.extend(["--template", str(template)]) + if output: + cmd.extend(["--output", str(output)]) + if title: + cmd.extend(["--title", title]) + if info_columns: + cmd.append("--info-columns") + cmd.extend(info_columns) + if info_columns_file: + cmd.extend(["--info-columns-file", str(info_columns_file)]) + if sample_columns: + cmd.append("--sample-columns") + cmd.extend(sample_columns) + if sample_columns_file: + cmd.extend(["--sample-columns-file", str(sample_columns_file)]) + if flanking is not None: + cmd.extend(["--flanking", str(flanking)]) + if standalone: + cmd.append("--standalone") + if sort: + cmd.append("--sort") + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + encoding='utf-8' + ) + + output_file = output if output else vcf.with_suffix(".html") + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file.resolve())] + } + except FileNotFoundError: + raise RuntimeError("igv-reports command not found. Please ensure it is installed and in your PATH.") + except subprocess.CalledProcessError as e: + logging.error(f"igv-reports failed with exit code {e.returncode}:\n{e.stderr}") + raise RuntimeError(f"igv-reports execution failed: {e.stderr}") from e + +@mcp.tool() +def create_cnv_report( + seg: Path, + fasta: Path, + tracks: Optional[List[Path]] = None, + track_config: Optional[Path] = None, + ideogram: Optional[Path] = None, + template: Optional[Path] = None, + output: Optional[Path] = None, + title: Optional[str] = None, + standalone: bool = False, +): + """ + Creates a CNV report from a SEG file. + """ + # --- Input Validation --- + if not seg.is_file(): + raise FileNotFoundError(f"Input SEG file not found: {seg}") + if not fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {fasta}") + if not fasta.with_suffix(fasta.suffix + '.fai').is_file(): + logging.warning(f"FASTA index (.fai) not found for {fasta}. The tool may fail or be slow.") + + if tracks: + for track in tracks: + if not track.is_file(): + raise FileNotFoundError(f"Track file not found: {track}") + if track_config and not track_config.is_file(): + raise FileNotFoundError(f"Track config file not found: {track_config}") + if ideogram and not ideogram.is_file(): + raise FileNotFoundError(f"Ideogram file not found: {ideogram}") + if template and not template.is_file(): + raise FileNotFoundError(f"Template file not found: {template}") + + # --- Command Construction --- + cmd = ["igv-reports", "create-cnv-report", str(seg)] + cmd.extend(["--fasta", str(fasta)]) + + if tracks: + cmd.append("--tracks") + cmd.extend([str(t) for t in tracks]) + if track_config: + cmd.extend(["--track-config", str(track_config)]) + if ideogram: + cmd.extend(["--ideogram", str(ideogram)]) + if template: + cmd.extend(["--template", str(template)]) + if output: + cmd.extend(["--output", str(output)]) + if title: + cmd.extend(["--title", title]) + if standalone: + cmd.append("--standalone") + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + encoding='utf-8' + ) + + output_file = output if output else seg.with_suffix(".html") + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file.resolve())] + } + except FileNotFoundError: + raise RuntimeError("igv-reports command not found. Please ensure it is installed and in your PATH.") + except subprocess.CalledProcessError as e: + logging.error(f"igv-reports failed with exit code {e.returncode}:\n{e.stderr}") + raise RuntimeError(f"igv-reports execution failed: {e.stderr}") from e + +@mcp.tool() +def create_fusion_report( + bedpe: Path, + fasta: Path, + tracks: Optional[List[Path]] = None, + track_config: Optional[Path] = None, + ideogram: Optional[Path] = None, + template: Optional[Path] = None, + output: Optional[Path] = None, + title: Optional[str] = None, + flanking: Optional[int] = None, + standalone: bool = False, +): + """ + Creates a fusion report from a BEDPE file. + """ + # --- Input Validation --- + if not bedpe.is_file(): + raise FileNotFoundError(f"Input BEDPE file not found: {bedpe}") + if not fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {fasta}") + if not fasta.with_suffix(fasta.suffix + '.fai').is_file(): + logging.warning(f"FASTA index (.fai) not found for {fasta}. The tool may fail or be slow.") + + if tracks: + for track in tracks: + if not track.is_file(): + raise FileNotFoundError(f"Track file not found: {track}") + if track_config and not track_config.is_file(): + raise FileNotFoundError(f"Track config file not found: {track_config}") + if ideogram and not ideogram.is_file(): + raise FileNotFoundError(f"Ideogram file not found: {ideogram}") + if template and not template.is_file(): + raise FileNotFoundError(f"Template file not found: {template}") + + if flanking is not None and flanking < 0: + raise ValueError("--flanking must be a non-negative integer.") + + # --- Command Construction --- + cmd = ["igv-reports", "create-fusion-report", str(bedpe)] + cmd.extend(["--fasta", str(fasta)]) + + if tracks: + cmd.append("--tracks") + cmd.extend([str(t) for t in tracks]) + if track_config: + cmd.extend(["--track-config", str(track_config)]) + if ideogram: + cmd.extend(["--ideogram", str(ideogram)]) + if template: + cmd.extend(["--template", str(template)]) + if output: + cmd.extend(["--output", str(output)]) + if title: + cmd.extend(["--title", title]) + if flanking is not None: + cmd.extend(["--flanking", str(flanking)]) + if standalone: + cmd.append("--standalone") + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + encoding='utf-8' + ) + + output_file = output if output else bedpe.with_suffix(".html") + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file.resolve())] + } + except FileNotFoundError: + raise RuntimeError("igv-reports command not found. Please ensure it is installed and in your PATH.") + except subprocess.CalledProcessError as e: + logging.error(f"igv-reports failed with exit code {e.returncode}:\n{e.stderr}") + raise RuntimeError(f"igv-reports execution failed: {e.stderr}") from e \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv-reports/app/igv-reports_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv-reports/app/igv-reports_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..08e79ea60ec0bfbb55c9d0622502d1a90339e2ab --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv-reports/app/igv-reports_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv-reports/app/igv-reports_server.py') +SERVER_NAME = 'biosci_igv_reports' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv-reports/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv-reports/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv-reports/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv-reports/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv-reports/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d26a8d6f27acb6d00ea569f2067494c56a52a93b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv-reports/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-igv-reports: + build: . + image: mcp-igv-reports:latest + container_name: mcp-igv-reports + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=igv-reports + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv-reports/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv-reports/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..381dd3cad839f9538ceaa36789d14b19189bd6a8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv-reports/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - igv-reports + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv-reports/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv-reports/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv-reports/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4ebb15fcc60ad53ded034507a9613530b7d6d0a3 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install igv via conda (e.g., from bioconda) +RUN conda install -c bioconda igv -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/igv_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/igv_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/igv_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv/app/igv_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv/app/igv_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f3c6f3b892009c52946b1adc36698d1c59eb87c2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv/app/igv_server.py @@ -0,0 +1,317 @@ +import subprocess +from pathlib import Path +from typing import List, Optional + +# MCP-related imports are intentionally omitted as per instructions. +# from mcp import tool as mcp_tool +# +# class mcp: +# @staticmethod +# def tool(func): +# return func + + +@mcp.tool +def to_tdf( + input_file: Path, + output_file: Path, + genome: str, + max_zoom: int = 7, + probe_window: Optional[int] = None, + window_size: Optional[int] = None, + tmp_dir: Optional[Path] = None, + verbose: bool = False, +): + """ + Converts sorted data files to the Tiled Data Format (.tdf) using igvtools. + + Args: + input_file: Path to the input file (e.g., .wig, .cn, .snp, .igv, .gct). + output_file: Path for the output .tdf file. + genome: A genome ID (e.g., 'hg19') or path to a .genome or chromosome sizes file. + max_zoom: Maximum zoom level to pre-compute. + probe_window: The window size for probe-based array data. + window_size: The window size for density computation. + tmp_dir: Path to a temporary directory. + verbose: If True, enables verbose output. + """ + # Input validation + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if max_zoom < 0: + raise ValueError("max_zoom must be a non-negative integer.") + + cmd = ["igvtools", "toTDF"] + + cmd.extend(["-z", str(max_zoom)]) + + if probe_window is not None: + if probe_window <= 0: + raise ValueError("probe_window must be a positive integer.") + cmd.extend(["-p", str(probe_window)]) + + if window_size is not None: + if window_size <= 0: + raise ValueError("window_size must be a positive integer.") + cmd.extend(["-w", str(window_size)]) + + if tmp_dir: + if not tmp_dir.is_dir(): + raise NotADirectoryError(f"Temporary directory not found: {tmp_dir}") + cmd.extend(["--tmpDir", str(tmp_dir)]) + + if verbose: + cmd.extend(["--verbose", "true"]) + + cmd.extend([str(input_file), str(output_file), genome]) + command_executed = " ".join(cmd) + + 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)], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"igvtools toTDF failed with exit code {e.returncode}", + "output_files": [], + } + + +@mcp.tool +def count( + input_file: Path, + output_file: Path, + genome: str, + max_zoom: int = 7, + window_size: int = 25, + ext_factor: Optional[int] = None, + pre_ext_factor: Optional[int] = None, + post_ext_factor: Optional[int] = None, + bases: bool = False, + query: Optional[str] = None, + min_map_quality: int = 0, + include_duplicates: bool = False, + pairs: bool = False, + strands: Optional[str] = None, + tmp_dir: Optional[Path] = None, + verbose: bool = False, +): + """ + Computes coverage from an alignment file using igvtools. + + Args: + input_file: Path to the input alignment file (.bam, .sam, .aligned). + output_file: Path for the output file (.wig or .tdf). + genome: A genome ID (e.g., 'hg19') or path to a .genome or chromosome sizes file. + max_zoom: Maximum zoom level to pre-compute (for .tdf output). + window_size: The window size for coverage calculation. + ext_factor: The read extension factor. + pre_ext_factor: The read pre-extension factor (upstream). + post_ext_factor: The read post-extension factor (downstream). + bases: If True, count bases instead of fragments. + query: Restricts computation to a region, e.g., 'chr1:100-200'. + min_map_quality: Minimum mapping quality for reads to be included. + include_duplicates: If True, include reads marked as duplicates. + pairs: If True, compute coverage from paired reads only. + strands: Specifies which strand to use for paired-end reads ('read', 'first', or 'second'). + tmp_dir: Path to a temporary directory. + verbose: If True, enables verbose output. + """ + # Input validation + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if max_zoom < 0: + raise ValueError("max_zoom must be a non-negative integer.") + if window_size <= 0: + raise ValueError("window_size must be a positive integer.") + if min_map_quality < 0: + raise ValueError("min_map_quality must be a non-negative integer.") + if strands and strands not in ["read", "first", "second"]: + raise ValueError("strands must be one of 'read', 'first', or 'second'.") + + cmd = ["igvtools", "count"] + + cmd.extend(["-z", str(max_zoom)]) + cmd.extend(["-w", str(window_size)]) + cmd.extend(["--minMapQuality", str(min_map_quality)]) + + if ext_factor is not None: + cmd.extend(["-e", str(ext_factor)]) + if pre_ext_factor is not None: + cmd.extend(["--preExtFactor", str(pre_ext_factor)]) + if post_ext_factor is not None: + cmd.extend(["--postExtFactor", str(post_ext_factor)]) + if bases: + cmd.append("--bases") + if query: + cmd.extend(["--query", query]) + if include_duplicates: + cmd.append("--includeDuplicates") + if pairs: + cmd.append("--pairs") + if strands: + cmd.extend(["--strands", strands]) + if tmp_dir: + if not tmp_dir.is_dir(): + raise NotADirectoryError(f"Temporary directory not found: {tmp_dir}") + cmd.extend(["--tmpDir", str(tmp_dir)]) + if verbose: + cmd.extend(["--verbose", "true"]) + + cmd.extend([str(input_file), str(output_file), genome]) + command_executed = " ".join(cmd) + + 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)], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"igvtools count failed with exit code {e.returncode}", + "output_files": [], + } + + +@mcp.tool +def index(input_file: Path): + """ + Creates an index for an alignment file using igvtools. + + Args: + input_file: Path to the alignment file to index (.sam, .bam, .aligned). + """ + # Input validation + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + # Determine expected output index file name + suffix = input_file.suffix.lower() + output_index_file = None + if suffix == ".bam": + output_index_file = input_file.with_suffix(input_file.suffix + ".bai") + elif suffix in [".sam", ".aligned"]: + output_index_file = input_file.with_suffix(input_file.suffix + ".sai") + + cmd = ["igvtools", "index", str(input_file)] + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, encoding="utf-8" + ) + + output_files = [] + if output_index_file and output_index_file.exists(): + output_files.append(str(output_index_file)) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"igvtools index failed with exit code {e.returncode}", + "output_files": [], + } + + +@mcp.tool +def sort( + input_file: Path, + output_file: Path, + max_records: int = 500000, + tmp_dir: Optional[Path] = None, +): + """ + Sorts an alignment file by genomic position using igvtools. + + Args: + input_file: Path to the input alignment file (.sam, .bam, .aligned). + output_file: Path for the sorted output file. + max_records: Maximum number of records to keep in memory. + tmp_dir: Path to a temporary directory. + """ + # Input validation + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if max_records <= 0: + raise ValueError("max_records must be a positive integer.") + + cmd = ["igvtools", "sort"] + + if tmp_dir: + if not tmp_dir.is_dir(): + raise NotADirectoryError(f"Temporary directory not found: {tmp_dir}") + cmd.extend(["--tmpDir", str(tmp_dir)]) + + cmd.extend(["-m", str(max_records)]) + cmd.extend([str(input_file), str(output_file)]) + command_executed = " ".join(cmd) + + 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)], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"igvtools sort failed with exit code {e.returncode}", + "output_files": [], + } + + +@mcp.tool +def version(): + """ + Prints the version number of igvtools. + """ + cmd = ["igvtools", "version"] + command_executed = " ".join(cmd) + + 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"igvtools version failed with exit code {e.returncode}", + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv/app/igv_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv/app/igv_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..57f83502469be232ac611c004948f7a52bf5bea2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv/app/igv_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv/app/igv_server.py') +SERVER_NAME = 'biosci_igv' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..93f2cf9f9f5c536dbc54732b4bdb1dae6af6b8cb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-igv: + build: . + image: mcp-igv:latest + container_name: mcp-igv + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=igv + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3f420d6ff28c3a95cac0a84b5a71f97c23b9393a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - igv + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_igv/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_illumina-interop/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_illumina-interop/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..41c896e2c98d7ab10ce2d4a9215a0670363013f6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_illumina-interop/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install illumina-interop via conda (e.g., from bioconda) +RUN conda install -c bioconda illumina-interop -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/illumina-interop_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/illumina-interop_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/illumina-interop_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_illumina-interop/app/illumina-interop_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_illumina-interop/app/illumina-interop_server.py new file mode 100644 index 0000000000000000000000000000000000000000..586bff81471978e1eed6e5f84333cbd6fdfc9aa4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_illumina-interop/app/illumina-interop_server.py @@ -0,0 +1,402 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, List, Dict, Any, Literal + +# Setup logging +logging.basicConfig(level=logging.INFO) +log = logging.getLogger(__name__) + +# Define a literal type for plot names to enforce valid choices +PlotName = Literal["flowcell", "by_cycle", "by_lane", "qscore_hist", "qscore_heatmap", "sample_qc"] + +# Mock the mcp.tool decorator for standalone execution and clarity +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def interop_dump( + run_folder: Path, + metric_name: Optional[str] = None, + output_file: Optional[Path] = None, + csv: bool = False, + binary: bool = False, + legacy: bool = False, +) -> Dict[str, Any]: + """ + Dumps the binary InterOp files to text, CSV, or binary format. + + Args: + run_folder: Path to the Illumina run folder containing InterOp files. + metric_name: Name of a specific metric to dump (dumps all if not specified). + output_file: Name of the output file (writes to stdout if not specified). + csv: If True, output in CSV format. + binary: If True, output in binary format. + legacy: If True, output in legacy format. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + if not run_folder.is_dir(): + raise FileNotFoundError(f"Input run folder not found: {run_folder}") + + if output_file and not output_file.parent.exists(): + output_file.parent.mkdir(parents=True, exist_ok=True) + + cmd = ["illumina-interop", "dump", str(run_folder)] + + if metric_name: + cmd.append(f"--metric-name={metric_name}") + if output_file: + cmd.append(f"--output-file={str(output_file)}") + if csv: + cmd.append("--csv") + if binary: + cmd.append("--bin") + if legacy: + cmd.append("--legacy") + + command_executed = " ".join(cmd) + log.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, encoding='utf-8' + ) + output_files = [str(output_file)] if output_file else [] + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + log.error(f"Error executing illumina-interop dump: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": "Execution failed", + } + +@mcp.tool +def interop_summary( + run_folder: Path, + csv: bool = False, + column_major: bool = False, +) -> Dict[str, Any]: + """ + Summarizes the InterOp files to stdout or CSV. + + Args: + run_folder: Path to the Illumina run folder containing InterOp files. + csv: If True, output in CSV format. + column_major: If True, output in column major format. + + Returns: + A dictionary containing the command executed, stdout, and stderr. + """ + if not run_folder.is_dir(): + raise FileNotFoundError(f"Input run folder not found: {run_folder}") + + cmd = ["illumina-interop", "summary", str(run_folder)] + + if csv: + cmd.append("--csv") + if column_major: + cmd.append("--column-major") + + command_executed = " ".join(cmd) + log.info(f"Executing command: {command_executed}") + + 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": [], + } + except subprocess.CalledProcessError as e: + log.error(f"Error executing illumina-interop summary: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": "Execution failed", + } + +@mcp.tool +def interop_plot( + run_folder: Path, + plot_name: PlotName, + output_file: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Plots the InterOp data using gnuplot. + + Args: + run_folder: Path to the Illumina run folder containing InterOp files. + plot_name: Name of the plot to generate. + output_file: Name of the output file (writes gnuplot script to stdout if not specified). + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + if not run_folder.is_dir(): + raise FileNotFoundError(f"Input run folder not found: {run_folder}") + + if output_file and not output_file.parent.exists(): + output_file.parent.mkdir(parents=True, exist_ok=True) + + cmd = ["illumina-interop", "plot", str(run_folder), plot_name] + + if output_file: + cmd.append(f"--output-file={str(output_file)}") + + command_executed = " ".join(cmd) + log.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, check=True, encoding='utf-8' + ) + output_files = [str(output_file)] if output_file else [] + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + log.error(f"Error executing illumina-interop plot: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": "Execution failed", + } + +@mcp.tool +def interop_image( + run_folder: Path, + plot_name: PlotName, + output_file: Path, + width: Optional[int] = None, + height: Optional[int] = None, +) -> Dict[str, Any]: + """ + Generates an image of a single plot. + + Args: + run_folder: Path to the Illumina run folder containing InterOp files. + plot_name: Name of the plot to generate. + output_file: Path to the output image file. + width: Width of the image in pixels. + height: Height of the image in pixels. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the output image file path. + """ + if not run_folder.is_dir(): + raise FileNotFoundError(f"Input run folder not found: {run_folder}") + + if not output_file.parent.exists(): + output_file.parent.mkdir(parents=True, exist_ok=True) + + cmd = ["illumina-interop", "image", str(run_folder), plot_name, str(output_file)] + + if width is not None: + if width <= 0: + raise ValueError("Width must be a positive integer.") + cmd.append(f"--width={width}") + if height is not None: + if height <= 0: + raise ValueError("Height must be a positive integer.") + cmd.append(f"--height={height}") + + command_executed = " ".join(cmd) + log.info(f"Executing command: {command_executed}") + + 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)], + } + except subprocess.CalledProcessError as e: + log.error(f"Error executing illumina-interop image: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": "Execution failed", + } + +@mcp.tool +def interop_filter( + run_folder: Path, + output_folder: Optional[Path] = None, + lane: Optional[int] = None, + read: Optional[int] = None, + cycle: Optional[int] = None, + tile: Optional[int] = None, + surface: Optional[int] = None, + swath: Optional[int] = None, + section: Optional[int] = None, +) -> Dict[str, Any]: + """ + Filters the InterOp files by lane, read, cycle, etc. + + Args: + run_folder: Path to the Illumina run folder containing InterOp files. + output_folder: Name of the output folder (defaults to 'InterOp_Filtered'). + lane: Lane number to keep. + read: Read number to keep. + cycle: Cycle number to keep. + tile: Tile number to keep. + surface: Surface number to keep. + swath: Swath number to keep. + section: Section number to keep. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the output folder path. + """ + if not run_folder.is_dir(): + raise FileNotFoundError(f"Input run folder not found: {run_folder}") + + cmd = ["illumina-interop", "filter", str(run_folder)] + + if lane is not None: + cmd.append(f"--lane={lane}") + if read is not None: + cmd.append(f"--read={read}") + if cycle is not None: + cmd.append(f"--cycle={cycle}") + if tile is not None: + cmd.append(f"--tile={tile}") + if surface is not None: + cmd.append(f"--surface={surface}") + if swath is not None: + cmd.append(f"--swath={swath}") + if section is not None: + cmd.append(f"--section={section}") + + # Handle output folder default behavior + final_output_folder = output_folder if output_folder else Path.cwd() / "InterOp_Filtered" + if not final_output_folder.exists(): + final_output_folder.mkdir(parents=True, exist_ok=True) + cmd.append(f"--output-folder={str(final_output_folder)}") + + command_executed = " ".join(cmd) + log.info(f"Executing command: {command_executed}") + + 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(final_output_folder)], + } + except subprocess.CalledProcessError as e: + log.error(f"Error executing illumina-interop filter: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": "Execution failed", + } + +@mcp.tool +def interop_index_summary( + run_folder: Path, + csv: bool = False, +) -> Dict[str, Any]: + """ + Summarizes the index metrics from InterOp files. + + Args: + run_folder: Path to the Illumina run folder containing InterOp files. + csv: If True, output in CSV format. + + Returns: + A dictionary containing the command executed, stdout, and stderr. + """ + if not run_folder.is_dir(): + raise FileNotFoundError(f"Input run folder not found: {run_folder}") + + cmd = ["illumina-interop", "index-summary", str(run_folder)] + + if csv: + cmd.append("--csv") + + command_executed = " ".join(cmd) + log.info(f"Executing command: {command_executed}") + + 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": [], + } + except subprocess.CalledProcessError as e: + log.error(f"Error executing illumina-interop index-summary: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": "Execution failed", + } + +@mcp.tool +def interop_version() -> Dict[str, Any]: + """ + Prints the version of the illumina-interop library. + + Returns: + A dictionary containing the command executed, stdout, and stderr. + """ + cmd = ["illumina-interop", "version"] + command_executed = " ".join(cmd) + log.info(f"Executing command: {command_executed}") + + 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": [], + } + except subprocess.CalledProcessError as e: + log.error(f"Error executing illumina-interop version: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + "error": "Execution failed", + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_illumina-interop/app/illumina-interop_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_illumina-interop/app/illumina-interop_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..029bfd7f8ad80d0d8a34fef320eef0b2dec5a24a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_illumina-interop/app/illumina-interop_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_illumina-interop/app/illumina-interop_server.py') +SERVER_NAME = 'biosci_illumina_interop' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_illumina-interop/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_illumina-interop/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_illumina-interop/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_illumina-interop/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_illumina-interop/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..32824f31b2d8bca5e5901708ae69981b6d3619a2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_illumina-interop/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-illumina-interop: + build: . + image: mcp-illumina-interop:latest + container_name: mcp-illumina-interop + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=illumina-interop + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_illumina-interop/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_illumina-interop/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..afe9a15fc940e95de9d87ef4e093d5e0c00400f0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_illumina-interop/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - illumina-interop + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_illumina-interop/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_illumina-interop/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_illumina-interop/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_infernal/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_infernal/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d28dd788a839b3000c541c1c4f1aaa37ee7fbbab --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_infernal/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install infernal via conda (e.g., from bioconda) +RUN conda install -c bioconda infernal -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/infernal_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/infernal_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/infernal_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_infernal/app/infernal_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_infernal/app/infernal_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d4d6bdf83eb94bc9f5e4128ab1cb28aa25fde1c2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_infernal/app/infernal_server.py @@ -0,0 +1,587 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Literal, Optional + +# Helper function to handle subprocess execution and error reporting +def _run_command(cmd: List[str]): + """Executes a command using subprocess and returns a structured output.""" + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(e.cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Command failed with exit code {e.returncode}", + } + +@mcp.tool() +def cmbuild( + msafile: Path, + cmfile_out: Path, + force: bool = False, + name: Optional[str] = None, + informat: Optional[Literal["stockholm", "afa", "selex", "pfam"]] = None, + outformat: Optional[Literal["stockholm", "afa", "selex", "pfam"]] = None, + refine_output: Optional[Path] = None, + alignment_output: Optional[Path] = None, + use_rf: bool = False, + use_hand: bool = False, + small_memory: bool = False, + weighting_strategy: Literal["none", "pb", "blosum", "given"] = "pb", + gsc_id_threshold: float = 0.62, + entropy_weighting: Literal["none", "set", "ent", "ere"] = "ere", + entropy_set_value: float = 0.0, + prior_strategy: Literal["none", "laplace", "dirichlet"] = "dirichlet", + prior_file: Optional[Path] = None, + fast: bool = False, + null_model_file: Optional[Path] = None, + cpu: int = 1, +) -> dict: + """ + Build a covariance model (CM) from a multiple sequence alignment. + + Args: + msafile: Path to the input multiple sequence alignment file in Stockholm format. + cmfile_out: Path to the output CM file. + force: Force overwrite of the output CM file if it exists. + name: Name the new CM. + informat: Assert that the input msafile is in the specified format. + outformat: Set the format of the output alignment. + refine_output: Refine the alignment, saving the new alignment to this file. + alignment_output: Save the alignment used to build the model to this file. + use_rf: Use reference annotation (#=GC RF) for consensus structure. + use_hand: Use hand-annotated consensus structure from the alignment file. + small_memory: Use a small memory dynamic programming implementation. + weighting_strategy: Set the sequence weighting strategy. + gsc_id_threshold: Set the identity threshold for GSC weights. + entropy_weighting: Set the entropy weighting strategy. + entropy_set_value: Set the entropy weight value when entropy_weighting is 'set'. + prior_strategy: Set the prior strategy. + prior_file: Use a Dirichlet prior from this file. Required if prior_strategy is 'dirichlet'. + fast: Use a heuristic model construction pipeline for faster building. + null_model_file: Read a null model from this file. + cpu: Number of parallel threads to use. + """ + if not msafile.exists(): + raise FileNotFoundError(f"Input MSA file not found: {msafile}") + if cmfile_out.exists() and not force: + raise FileExistsError(f"Output file {cmfile_out} exists. Use force=True to overwrite.") + if sum([use_rf, use_hand, refine_output is not None]) > 1: + raise ValueError("At most one of use_rf, use_hand, or refine_output may be used.") + if gsc_id_threshold < 0.0 or gsc_id_threshold > 1.0: + raise ValueError("gsc_id_threshold must be between 0.0 and 1.0.") + if prior_strategy == "dirichlet" and not prior_file: + raise ValueError("prior_file must be provided when prior_strategy is 'dirichlet'.") + if prior_file and not prior_file.exists(): + raise FileNotFoundError(f"Prior file not found: {prior_file}") + if null_model_file and not null_model_file.exists(): + raise FileNotFoundError(f"Null model file not found: {null_model_file}") + + cmd = ["cmbuild"] + if force: cmd.append("-F") + if name: cmd.extend(["-n", name]) + if informat: cmd.extend(["--informat", informat]) + if outformat: cmd.extend(["--outformat", outformat]) + if refine_output: cmd.extend(["--refine", str(refine_output)]) + if alignment_output: cmd.extend(["-o", str(alignment_output)]) + if use_rf: cmd.append("--rf") + if use_hand: cmd.append("--hand") + if small_memory: cmd.append("--small") + if fast: cmd.append("--fast") + if cpu > 0: cmd.extend(["--cpu", str(cpu)]) + + # Weighting strategy + if weighting_strategy == "none": cmd.append("--wnone") + elif weighting_strategy == "pb": cmd.append("--wpb") + elif weighting_strategy == "blosum": cmd.append("--wblosum") + elif weighting_strategy == "given": cmd.append("--wgiven") + if weighting_strategy == "pb": cmd.extend(["--wid", str(gsc_id_threshold)]) + + # Entropy weighting + if entropy_weighting == "none": cmd.append("--enone") + elif entropy_weighting == "set": cmd.extend(["--eset", str(entropy_set_value)]) + elif entropy_weighting == "ent": cmd.append("--eent") + elif entropy_weighting == "ere": cmd.append("--ere") + + # Prior strategy + if prior_strategy == "none": cmd.append("--pnone") + elif prior_strategy == "laplace": cmd.append("--plaplace") + elif prior_strategy == "dirichlet" and prior_file: + cmd.extend(["--pdirichlet", str(prior_file)]) + + if null_model_file: cmd.extend(["--null", str(null_model_file)]) + + cmd.extend([str(cmfile_out), str(msafile)]) + + result = _run_command(cmd) + + output_files = {"output_cm": str(cmfile_out)} + if refine_output: + output_files["refined_alignment"] = str(refine_output) + if alignment_output: + output_files["output_alignment"] = str(alignment_output) + result["output_files"] = output_files + + return result + +@mcp.tool() +def cmalign( + cmfile: Path, + seqfile: Path, + output_alignment: Optional[Path] = None, + alignment_mode: Literal["global", "local"] = "local", + informat: Optional[str] = None, + outformat: Literal["stockholm", "afa", "selex", "pfam"] = "stockholm", + map_alignment: Optional[Path] = None, + map_consensus_structure: bool = False, + small_memory: bool = False, + sub_scores_only: bool = False, + nonbanded: bool = False, + algorithm: Literal["cyk", "inside"] = "cyk", + optimal_accuracy: bool = False, + sample: bool = False, + num_samples: int = 1, + random_seed: int = 0, + cpu: int = 1, +) -> dict: + """ + Align sequences to a covariance model. + + Args: + cmfile: Path to the input CM file. + seqfile: Path to the sequence file to align. + output_alignment: Path to save the output alignment. If None, prints to stdout. + alignment_mode: Set the alignment mode ('global' or 'local'). + informat: Assert that the input seqfile is in the specified format. + outformat: Set the format for the output alignment. + map_alignment: Map an existing alignment to the CM. + map_consensus_structure: Map the consensus structure to the alignment. + small_memory: Use a small memory dynamic programming implementation. + sub_scores_only: Use substitution scores only, ignoring insertion/deletion scores. + nonbanded: Use non-banded dynamic programming for higher accuracy but slower speed. + algorithm: Use either the 'cyk' or 'inside' algorithm for alignment. + optimal_accuracy: Use optimal accuracy alignment. + sample: Sample an alignment from the posterior distribution. + num_samples: If sample is True, generate this many samples. + random_seed: Set the random number seed. + cpu: Number of parallel threads to use. + """ + if not cmfile.exists(): + raise FileNotFoundError(f"Input CM file not found: {cmfile}") + if not seqfile.exists(): + raise FileNotFoundError(f"Input sequence file not found: {seqfile}") + if map_alignment and not map_alignment.exists(): + raise FileNotFoundError(f"Map alignment file not found: {map_alignment}") + + cmd = ["cmalign"] + if output_alignment: cmd.extend(["-o", str(output_alignment)]) + if alignment_mode == "global": cmd.append("-g") + if alignment_mode == "local": cmd.append("-l") + if informat: cmd.extend(["--informat", informat]) + cmd.extend(["--outformat", outformat]) + if map_alignment: cmd.extend(["--mapali", str(map_alignment)]) + if map_consensus_structure: cmd.append("--mapstr") + if small_memory: cmd.append("--small") + if sub_scores_only: cmd.append("--sub") + if nonbanded: cmd.append("--nonbanded") + if algorithm == "inside": cmd.append("--inside") + if optimal_accuracy: cmd.append("--optacc") + if sample: + cmd.append("--sample") + cmd.extend(["--psample", str(num_samples)]) + if random_seed > 0: cmd.extend(["--seed", str(random_seed)]) + if cpu > 0: cmd.extend(["--cpu", str(cpu)]) + + cmd.extend([str(cmfile), str(seqfile)]) + + result = _run_command(cmd) + + output_files = {} + if output_alignment: + output_files["output_alignment"] = str(output_alignment) + result["output_files"] = output_files + + return result + +@mcp.tool() +def cmsearch( + cmfile: Path, + seqdb: Path, + output_file: Optional[Path] = None, + alignment_output: Optional[Path] = None, + tabular_output: Optional[Path] = None, + e_value_threshold: float = 10.0, + bitscore_threshold: float = 0.0, + report_all_clan_hits: bool = False, + toponly: bool = False, + bottomonly: bool = False, + no_glocal_search: bool = False, + no_qdb: bool = False, + no_hbanded: bool = False, + rfam: bool = False, + max_sensitivity: bool = False, + cpu: int = 1, +) -> dict: + """ + Search a sequence database with a covariance model. + + Args: + cmfile: Path to the input CM file. + seqdb: Path to the sequence database file. + output_file: Path to save the main output. If None, prints to stdout. + alignment_output: Path to save the alignment of all significant hits. + tabular_output: Path to save a tabular summary of top hits. + e_value_threshold: Report hits with an E-value <= this threshold. + bitscore_threshold: Report hits with a bit score >= this threshold. + report_all_clan_hits: Report all hits, including those within overlapping clans. + toponly: Search only the top strand of the DNA sequence database. + bottomonly: Search only the bottom strand of the DNA sequence database. + no_glocal_search: Turn off the glocal search heuristic filter. + no_qdb: Turn off query-dependent banding. + no_hbanded: Turn off HMM-banded dynamic programming. + rfam: Use strict filtering pipeline settings used by Rfam. + max_sensitivity: Turn off all heuristics to maximize sensitivity. + cpu: Number of parallel threads to use. + """ + if not cmfile.exists(): + raise FileNotFoundError(f"Input CM file not found: {cmfile}") + if not seqdb.exists(): + raise FileNotFoundError(f"Sequence database file not found: {seqdb}") + + cmd = ["cmsearch"] + if output_file: cmd.extend(["-o", str(output_file)]) + if alignment_output: cmd.extend(["-A", str(alignment_output)]) + if tabular_output: cmd.extend(["--tblout", str(tabular_output)]) + if e_value_threshold != 10.0: cmd.extend(["-E", str(e_value_threshold)]) + if bitscore_threshold != 0.0: cmd.extend(["-T", str(bitscore_threshold)]) + if report_all_clan_hits: cmd.append("--all-clans") + if toponly: cmd.append("--toponly") + if bottomonly: cmd.append("--bottomonly") + if no_glocal_search: cmd.append("--no-glsearch") + if no_qdb: cmd.append("--no-qdb") + if no_hbanded: cmd.append("--no-hbanded") + if rfam: cmd.append("--rfam") + if max_sensitivity: cmd.append("--max") + if cpu > 0: cmd.extend(["--cpu", str(cpu)]) + + cmd.extend([str(cmfile), str(seqdb)]) + + result = _run_command(cmd) + + output_files = {} + if output_file: + output_files["main_output"] = str(output_file) + if alignment_output: + output_files["alignment_output"] = str(alignment_output) + if tabular_output: + output_files["tabular_output"] = str(tabular_output) + result["output_files"] = output_files + + return result + +@mcp.tool() +def cmscan( + cmdb: Path, + seqfile: Path, + output_file: Optional[Path] = None, + tabular_output: Optional[Path] = None, + e_value_threshold: float = 10.0, + bitscore_threshold: float = 0.0, + glocal: bool = False, + clan_info_file: Optional[Path] = None, + no_overlap_correction: bool = False, + toponly: bool = False, + bottomonly: bool = False, + rfam: bool = False, + max_sensitivity: bool = False, + cpu: int = 1, +) -> dict: + """ + Search sequence(s) against a covariance model database. + + Args: + cmdb: Path to the CM database file (must be pressed with cmpress). + seqfile: Path to the sequence file to search. + output_file: Path to save the main output. If None, prints to stdout. + tabular_output: Path to save a tabular summary of top hits. + e_value_threshold: Report hits with an E-value <= this threshold. + bitscore_threshold: Report hits with a bit score >= this threshold. + glocal: Use glocal alignment mode (local with respect to query, global to target). + clan_info_file: Use clan information from this file for overlap correction. + no_overlap_correction: Turn off all overlap correction. + toponly: Search only the top strand of the DNA sequence. + bottomonly: Search only the bottom strand of the DNA sequence. + rfam: Use strict filtering pipeline settings used by Rfam. + max_sensitivity: Turn off all heuristics to maximize sensitivity. + cpu: Number of parallel threads to use. + """ + if not cmdb.exists(): + raise FileNotFoundError(f"Input CM database not found: {cmdb}") + if not seqfile.exists(): + raise FileNotFoundError(f"Input sequence file not found: {seqfile}") + if clan_info_file and not clan_info_file.exists(): + raise FileNotFoundError(f"Clan info file not found: {clan_info_file}") + + cmd = ["cmscan"] + if output_file: cmd.extend(["-o", str(output_file)]) + if tabular_output: cmd.extend(["--tblout", str(tabular_output)]) + if e_value_threshold != 10.0: cmd.extend(["-E", str(e_value_threshold)]) + if bitscore_threshold != 0.0: cmd.extend(["-T", str(bitscore_threshold)]) + if glocal: cmd.append("--glocal") + if clan_info_file: cmd.extend(["--clanin", str(clan_info_file)]) + if no_overlap_correction: cmd.append("--onone") + if toponly: cmd.append("--toponly") + if bottomonly: cmd.append("--bottomonly") + if rfam: cmd.append("--rfam") + if max_sensitivity: cmd.append("--max") + if cpu > 0: cmd.extend(["--cpu", str(cpu)]) + + cmd.extend([str(cmdb), str(seqfile)]) + + result = _run_command(cmd) + + output_files = {} + if output_file: + output_files["main_output"] = str(output_file) + if tabular_output: + output_files["tabular_output"] = str(tabular_output) + result["output_files"] = output_files + + return result + +@mcp.tool() +def cmpress( + cmfile: Path, + force: bool = False, +) -> dict: + """ + Prepare a CM file for use with cmscan by creating index files. + + Args: + cmfile: Path to the CM file to press. + force: Force overwrite of existing index files. + """ + if not cmfile.exists(): + raise FileNotFoundError(f"Input CM file not found: {cmfile}") + + cmd = ["cmpress"] + if force: cmd.append("-F") + cmd.append(str(cmfile)) + + result = _run_command(cmd) + + base = str(cmfile) + output_files = { + "cm_database": base, + "index_f": f"{base}.i1f", + "index_m": f"{base}.i1m", + "index_p": f"{base}.i1p", + "index_i": f"{base}.i1i", + } + result["output_files"] = output_files + + return result + +@mcp.tool() +def cmcalibrate( + cmfile: Path, + num_sequences: int = 2000, + sequence_length: int = 100, + random_seed: int = 0, + cpu: int = 1, +) -> dict: + """ + Calibrate a CM file to fit exponential tail parameters for E-values. + This modifies the input cmfile in-place. + + Args: + cmfile: Path to the CM file to calibrate. + num_sequences: Number of random sequences to generate for calibration. + sequence_length: Length of random sequences to generate. + random_seed: Set the random number seed. + cpu: Number of parallel threads to use. + """ + if not cmfile.exists(): + raise FileNotFoundError(f"Input CM file not found: {cmfile}") + + cmd = ["cmcalibrate"] + if num_sequences != 2000: cmd.extend(["-N", str(num_sequences)]) + if sequence_length != 100: cmd.extend(["-L", str(sequence_length)]) + if random_seed > 0: cmd.extend(["--seed", str(random_seed)]) + if cpu > 0: cmd.extend(["--cpu", str(cpu)]) + cmd.append(str(cmfile)) + + result = _run_command(cmd) + result["output_files"] = {"calibrated_cm": str(cmfile)} + + return result + +@mcp.tool() +def cmstat( + cmfile: Path, + list_names: bool = False, +) -> dict: + """ + Show summary statistics for a CM file. + + Args: + cmfile: Path to the CM file. + list_names: Show a list of CM names in the file instead of statistics. + """ + if not cmfile.exists(): + raise FileNotFoundError(f"Input CM file not found: {cmfile}") + + cmd = ["cmstat"] + if list_names: cmd.append("-l") + cmd.append(str(cmfile)) + + result = _run_command(cmd) + result["output_files"] = {} + return result + +@mcp.tool() +def cmemit( + cmfile: Path, + num_sequences: int = 1, + output_file: Optional[Path] = None, + aligned: bool = False, + consensus: bool = False, + unaligned: bool = False, + sequence_length: Optional[int] = None, + random_seed: int = 0, +) -> dict: + """ + Sample sequences from a covariance model. + + Args: + cmfile: Path to the CM file. + num_sequences: Number of sequences to sample. + output_file: Path to save the output sequences. If None, prints to stdout. + aligned: Generate aligned sequences. + consensus: Generate the consensus sequence. + unaligned: Generate unaligned sequences. + sequence_length: Generate sequences of a fixed length. + random_seed: Set the random number seed. + """ + if not cmfile.exists(): + raise FileNotFoundError(f"Input CM file not found: {cmfile}") + if sum([aligned, consensus, unaligned]) > 1: + raise ValueError("Only one of 'aligned', 'consensus', or 'unaligned' can be True.") + + cmd = ["cmemit"] + if num_sequences != 1: cmd.extend(["-N", str(num_sequences)]) + if output_file: cmd.extend(["-o", str(output_file)]) + if aligned: cmd.append("-a") + if consensus: cmd.append("-c") + if unaligned: cmd.append("-u") + if sequence_length: cmd.extend(["-L", str(sequence_length)]) + if random_seed > 0: cmd.extend(["--seed", str(random_seed)]) + cmd.append(str(cmfile)) + + result = _run_command(cmd) + + output_files = {} + if output_file: + output_files["emitted_sequences"] = str(output_file) + result["output_files"] = output_files + + return result + +@mcp.tool() +def cmfetch( + cmfile: Path, + keys: List[str], + output_file: Optional[Path] = None, + keys_from_file: bool = False, +) -> dict: + """ + Retrieve one or more CMs from a CM file. + + Args: + cmfile: Path to the CM file (must be indexed with --index first or have a .ssi file). + keys: List of names or accessions of CMs to retrieve. If keys_from_file is True, this should be a single path to a file containing keys. + output_file: Path to save the fetched CM(s). If None, prints to stdout. + keys_from_file: If True, 'keys' argument is treated as a path to a file containing keys. + """ + if not cmfile.exists(): + raise FileNotFoundError(f"Input CM file not found: {cmfile}") + if not Path(f"{cmfile}.ssi").exists(): + raise FileNotFoundError(f"Index file {cmfile}.ssi not found. Run cmfetch_index first.") + if keys_from_file: + if len(keys) != 1 or not Path(keys[0]).exists(): + raise FileNotFoundError(f"Key file not found or multiple paths provided: {keys}") + + cmd = ["cmfetch"] + if output_file: cmd.extend(["-o", str(output_file)]) + if keys_from_file: cmd.append("-f") + + cmd.append(str(cmfile)) + cmd.extend(keys) + + result = _run_command(cmd) + + output_files = {} + if output_file: + output_files["fetched_cm"] = str(output_file) + result["output_files"] = output_files + + return result + +@mcp.tool() +def cmfetch_index(cmfile: Path) -> dict: + """ + Create a binary SSI index for a CM file for use with cmfetch. + + Args: + cmfile: Path to the CM file to index. + """ + if not cmfile.exists(): + raise FileNotFoundError(f"Input CM file not found: {cmfile}") + + cmd = ["cmfetch", "--index", str(cmfile)] + result = _run_command(cmd) + result["output_files"] = {"ssi_index": f"{cmfile}.ssi"} + return result + +@mcp.tool() +def cmconvert( + cmfile: Path, + output_file: Optional[Path] = None, + outformat: Optional[str] = None, +) -> dict: + """ + Convert a CM file to a different format version. + + Args: + cmfile: Path to the input CM file. + output_file: Path to save the converted CM file. If None, prints to stdout. + outformat: The output format to convert to (e.g., '1.1'). + """ + if not cmfile.exists(): + raise FileNotFoundError(f"Input CM file not found: {cmfile}") + + cmd = ["cmconvert"] + if output_file: cmd.extend(["-o", str(output_file)]) + if outformat: cmd.extend(["--outfmt", outformat]) + cmd.append(str(cmfile)) + + result = _run_command(cmd) + + output_files = {} + if output_file: + output_files["converted_cm"] = str(output_file) + result["output_files"] = output_files + + return result \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_infernal/app/infernal_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_infernal/app/infernal_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0e6b0e48b83e1c15425ee93ea3d8cd6474b972b9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_infernal/app/infernal_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_infernal/app/infernal_server.py') +SERVER_NAME = 'biosci_infernal' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_infernal/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_infernal/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_infernal/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_infernal/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_infernal/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c6ded46c289b6320b59c14c8436e850705e0e4f7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_infernal/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-infernal: + build: . + image: mcp-infernal:latest + container_name: mcp-infernal + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=infernal + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_infernal/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_infernal/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8aede6ab663f5e590c4e7c529b989fff4e48a7c7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_infernal/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - infernal + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_infernal/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_infernal/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_infernal/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_insilicoseq/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_insilicoseq/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d1b7081a6afa7e0a7f9622dc5810dd6c55b9ba9e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_insilicoseq/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install insilicoseq via conda (e.g., from bioconda) +RUN conda install -c bioconda insilicoseq -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/insilicoseq_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/insilicoseq_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/insilicoseq_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_insilicoseq/app/insilicoseq_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_insilicoseq/app/insilicoseq_server.py new file mode 100644 index 0000000000000000000000000000000000000000..34ac457f4caed2c426ff5e7fd9f0380f65c439fc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_insilicoseq/app/insilicoseq_server.py @@ -0,0 +1,237 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# @mcp.tool() - This decorator is commented out as per the instructions. +def generate( + output: str, + genomes: Optional[List[Path]] = None, + ncbi: Optional[str] = None, + ncbi_n_genomes: int = 10, + n_reads: str = "1m", + model: str = "miseq", + abundance: Optional[str] = None, + coverage: Optional[str] = None, + draft: Optional[Path] = None, + gc_model: Optional[Path] = None, + mode: Optional[str] = "kde", + seed: Optional[int] = None, + cpus: int = 1, + compress: bool = False, + perfect: bool = False, + quiet: bool = False, +) -> dict: + """ + Generate simulated Illumina reads from reference genomes. + + This tool simulates sequencing reads, primarily for metagenomic samples, + but can also be used for single genomes. It supports various error models, + GC bias, and abundance distributions. + + Args: + output (str): Prefix for the output files. + genomes (Optional[List[Path]]): List of FASTA files containing reference genomes. + Mutually exclusive with 'ncbi'. + ncbi (Optional[str]): Download random genomes from NCBI. Provide a kingdom + (e.g., 'bacteria', 'viruses', 'archaea'). + Mutually exclusive with 'genomes'. + ncbi_n_genomes (int): Number of genomes to download from NCBI if 'ncbi' is used. + n_reads (str): Total number of reads to generate. Suffixes 'k', 'm', 'g' are supported (e.g., '10k', '1m'). + model (str): Error model to use. Can be a built-in model ('miseq', 'hiseq', 'novaseq') + or a path to a custom '.npz' model file. + abundance (Optional[str]): Abundance distribution. Can be a distribution name + ('uniform', 'lognormal', 'halfnormal', 'zero_inflated_lognormal') + or a path to an abundance file. Mutually exclusive with 'coverage'. + coverage (Optional[str]): Coverage distribution. Can be a distribution name or a path + to a coverage file. Mutually exclusive with 'abundance'. + draft (Optional[Path]): Path to a file indicating which sequences are draft quality. + gc_model (Optional[Path]): Path to a custom GC bias model file. + mode (Optional[str]): Sequencing simulation mode. Defaults to 'kde'. + seed (Optional[int]): Random seed for reproducibility. + cpus (int): Number of CPUs to use for simulation. + compress (bool): If True, compress the output FASTQ files with gzip. + perfect (bool): If True, generate perfect reads without sequencing errors. + quiet (bool): If True, suppress progress and informational messages. + + Returns: + dict: A dictionary containing the executed command, stdout, stderr, + and a list of generated output files. + """ + # Input validation + if not ((genomes is not None) ^ (ncbi is not None)): + raise ValueError("Either 'genomes' or 'ncbi' must be provided, but not both.") + + if abundance is not None and coverage is not None: + raise ValueError("'abundance' and 'coverage' are mutually exclusive.") + + if cpus <= 0: + raise ValueError("'cpus' must be a positive integer.") + + if ncbi_n_genomes <= 0: + raise ValueError("'ncbi_n_genomes' must be a positive integer.") + + cmd = ["iss", "generate", "--output", output] + + if genomes: + for genome_file in genomes: + if not genome_file.is_file(): + raise FileNotFoundError(f"Genome file not found: {genome_file}") + cmd.extend(["--genomes", str(genome_file)]) + elif ncbi: + cmd.extend(["--ncbi", ncbi, "--n_genomes", str(ncbi_n_genomes)]) + + cmd.extend(["--n_reads", n_reads]) + + if model.endswith(".npz"): + model_path = Path(model) + if not model_path.is_file(): + raise FileNotFoundError(f"Custom model file not found: {model_path}") + cmd.extend(["--model", model]) + + if abundance: + try: + abundance_path = Path(abundance) + if not abundance_path.is_file(): + # It's a distribution name, not a file + pass + except (TypeError, ValueError): + pass # It's a distribution name + cmd.extend(["--abundance", abundance]) + + if coverage: + try: + coverage_path = Path(coverage) + if not coverage_path.is_file(): + # It's a distribution name, not a file + pass + except (TypeError, ValueError): + pass # It's a distribution name + cmd.extend(["--coverage", coverage]) + + if draft: + if not draft.is_file(): + raise FileNotFoundError(f"Draft file not found: {draft}") + cmd.extend(["--draft", str(draft)]) + + if gc_model: + if not gc_model.is_file(): + raise FileNotFoundError(f"GC model file not found: {gc_model}") + cmd.extend(["--gc_model", str(gc_model)]) + + if mode: + cmd.extend(["--mode", mode]) + + if seed is not None: + cmd.extend(["--seed", str(seed)]) + + cmd.extend(["--cpus", str(cpus)]) + + if compress: + cmd.append("--compress") + if perfect: + cmd.append("--perfect") + if quiet: + cmd.append("--quiet") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"InSilicoSeq generate failed with exit code {e.returncode}", + "output_files": [] + } + + # Define output files + ext = ".fastq.gz" if compress else ".fastq" + output_files = [ + f"{output}_R1{ext}", + f"{output}_R2{ext}", + f"{output}_abundance.txt", + ] + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + + +# @mcp.tool() - This decorator is commented out as per the instructions. +def model( + bam: Path, + output: str, + cpus: int = 1, + quiet: bool = False, +) -> dict: + """ + Create a sequencing error model from an aligned BAM file. + + This tool analyzes a BAM file containing reads aligned to a reference genome + to build a statistical model of sequencing errors, which can then be used + by the 'generate' tool. + + Args: + bam (Path): Path to the input sorted and indexed BAM file. + output (str): Prefix for the output model file. A '.npz' extension will be added. + cpus (int): Number of CPUs to use for model creation. + quiet (bool): If True, suppress progress and informational messages. + + Returns: + dict: A dictionary containing the executed command, stdout, stderr, + and the path to the generated model file. + """ + # Input validation + if not bam.is_file(): + raise FileNotFoundError(f"BAM file not found: {bam}") + + # Check for BAM index file + bai_file_1 = bam.with_suffix(".bam.bai") + bai_file_2 = bam.with_suffix(".bai") + if not (bai_file_1.is_file() or bai_file_2.is_file()): + raise FileNotFoundError( + f"BAM index file (.bai) not found for {bam}. Please index the BAM file." + ) + + if cpus <= 0: + raise ValueError("'cpus' must be a positive integer.") + + cmd = ["iss", "model", "--bam", str(bam), "--output", output] + cmd.extend(["--cpus", str(cpus)]) + + if quiet: + cmd.append("--quiet") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"InSilicoSeq model failed with exit code {e.returncode}", + "output_files": [] + } + + output_model_file = f"{output}.npz" + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_model_file], + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_insilicoseq/app/insilicoseq_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_insilicoseq/app/insilicoseq_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c65259203954c5c7af3f86f11412ddcf34b8eb8b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_insilicoseq/app/insilicoseq_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_insilicoseq/app/insilicoseq_server.py') +SERVER_NAME = 'biosci_insilicoseq' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_insilicoseq/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_insilicoseq/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_insilicoseq/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_insilicoseq/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_insilicoseq/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..eb79cea3b04e786ce93b5d14a7cefdb4d2f38c36 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_insilicoseq/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-insilicoseq: + build: . + image: mcp-insilicoseq:latest + container_name: mcp-insilicoseq + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=insilicoseq + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_insilicoseq/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_insilicoseq/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6fe4420616b68a726f5134e0090beaceb4fe1686 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_insilicoseq/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - insilicoseq + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_insilicoseq/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_insilicoseq/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_insilicoseq/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_intarna/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_intarna/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3ddc187860d0f99c303e059198f662efff2d4793 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_intarna/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install intarna via conda (e.g., from bioconda) +RUN conda install -c bioconda intarna -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/intarna_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/intarna_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/intarna_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_intarna/app/intarna_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_intarna/app/intarna_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5e469a82f1b22c9332adf45934b459937e4feeea --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_intarna/app/intarna_server.py @@ -0,0 +1,310 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, Dict + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided by the framework. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +@mcp.tool() +def intarna( + query: Path, + target: Path, + # OUTPUT + n_best: int = 100, + out: Optional[Path] = None, + out_mode: str = "C", + out_overlap: str = "N", + out_csv_cols: Optional[str] = None, + out_max_e: Optional[float] = None, + out_min_pu1: float = 0.0, + out_min_pu2: float = 0.0, + out_best: int = 1, + out_sub_opt: Optional[str] = None, + out_per_tar: int = 0, + out_per_qry: int = 0, + out_no_lp: bool = False, + # INTERACTION + q_acc: str = "W", + q_acc_file: Optional[Path] = None, + q_acc_w: int = 150, + q_acc_l: int = 100, + q_acc_constr: Optional[str] = None, + q_int_len_max: int = 150, + q_int_loop: int = 16, + q_max_bp: int = 200, + q_region: Optional[str] = None, + q_idx_pos: Optional[str] = None, + q_idx_file: Optional[Path] = None, + t_acc: str = "W", + t_acc_file: Optional[Path] = None, + t_acc_w: int = 150, + t_acc_l: int = 100, + t_acc_constr: Optional[str] = None, + t_int_len_max: int = 150, + t_int_loop: int = 16, + t_max_bp: int = 200, + t_region: Optional[str] = None, + t_idx_pos: Optional[str] = None, + t_idx_file: Optional[Path] = None, + interaction_span: Optional[str] = None, + interaction_type: str = "I", + energy: str = "V", + temperature: float = 37.0, + no_gu_end: bool = False, + no_closing_gu: bool = False, + max_loop: int = 16, + max_bp: int = 200, + no_lpi: bool = False, + lp: bool = False, + # SEED + seed_bp: int = 2, + seed_max_up: int = 0, + seed_q_max_up: int = 0, + seed_t_max_up: int = 0, + seed_u_left: int = 0, + seed_u_right: int = 0, + seed_q_region: Optional[str] = None, + seed_t_region: Optional[str] = None, + seed_constraint: Optional[str] = None, + seed_ref: Optional[str] = None, + seed_s1: float = 1.0, + seed_s2: float = 1.0, + no_seed: bool = False, + # MISC + verbose: bool = False, + threads: int = 0, +) -> Dict: + """ + Predicts RNA-RNA interactions using IntaRNA. + + This tool wraps the IntaRNA command-line interface to predict interactions + between a query and a target RNA sequence. + + Args: + query: Path to the query sequence(s) in FASTA format. + target: Path to the target sequence(s) in FASTA format. + n_best: Number of best interactions to report. + out: Path to the output file. If not provided, a temporary file is created. + out_mode: Output format ('c', 'C', 'd', 'D', 's'). + out_overlap: Overlap handling for suboptimal interactions ('N', 'Q', 'T'). + out_csv_cols: Comma-separated list of column IDs for CSV output. + out_max_e: Report only interactions with energy at most this value. + out_min_pu1: Report only interactions with accessibility Pu1 at least this value. + out_min_pu2: Report only interactions with accessibility Pu2 at least this value. + out_best: Number of best interactions to report per query-target-pair. + out_sub_opt: Energy range of suboptimal interactions, e.g., 'f(E_opt)=E_opt+2.5'. + out_per_tar: Number of best interactions to report per target. + out_per_qry: Number of best interactions to report per query. + out_no_lp: Suppress calculation of interaction probability for full length sequences. + q_acc: Accessibility computation for query ('W', 'C', 'S', 'N', 'R'). + q_acc_file: File to read query accessibility from (if q_acc='R'). + q_acc_w: Window size for query accessibility computation. + q_acc_l: Maximal loop length for query accessibility computation. + q_acc_constr: RNAplfold constraints for query accessibility computation. + q_int_len_max: Maximal interaction length for query. + q_int_loop: Maximal loop length in query interaction. + q_max_bp: Maximal number of base pairs in an interaction for query. + q_region: Subregion of query to consider, e.g., '10-50'. + q_idx_pos: Comma-separated list of query positions to consider. + q_idx_file: File with query positions to consider. + t_acc: Accessibility computation for target ('W', 'C', 'S', 'N', 'R'). + t_acc_file: File to read target accessibility from (if t_acc='R'). + t_acc_w: Window size for target accessibility computation. + t_acc_l: Maximal loop length for target accessibility computation. + t_acc_constr: RNAplfold constraints for target accessibility computation. + t_int_len_max: Maximal interaction length for target. + t_int_loop: Maximal loop length in target interaction. + t_max_bp: Maximal number of base pairs in an interaction for target. + t_region: Subregion of target to consider, e.g., '10-50'. + t_idx_pos: Comma-separated list of target positions to consider. + t_idx_file: File with target positions to consider. + interaction_span: Maximal distance between interaction sites, e.g., 'i-j' or 'i+j'. + interaction_type: Type of interaction to predict ('H', 'I', 'B'). + energy: Energy computation model ('V', 'S'). + temperature: Temperature in Celsius for energy computation. + no_gu_end: Disallow GU pairs at the end of helices. + no_closing_gu: Disallow GU pairs at the ends of loops. + max_loop: Maximal number of unpaired bases in a loop. + max_bp: Maximal number of base pairs in the interaction. + no_lpi: Suppress penalization of lonely base pairs. + lp: Enable calculation of interaction probability for full length sequences (slow). + seed_bp: Minimal number of base pairs in the seed. + seed_max_up: Maximal number of unpaired bases in the seed. + seed_q_max_up: Maximal number of unpaired bases in the query part of the seed. + seed_t_max_up: Maximal number of unpaired bases in the target part of the seed. + seed_u_left: Maximal number of unpaired bases in the left part of the seed. + seed_u_right: Maximal number of unpaired bases in the right part of the seed. + seed_q_region: Subregion of query for seed prediction. + seed_t_region: Subregion of target for seed prediction. + seed_constraint: Seed constraint to apply, e.g., 'E:-10'. + seed_ref: Reference seed for constraint evaluation, e.g., '10-20:30-40'. + seed_s1: Sensitivity weight for query accessibility. + seed_s2: Sensitivity weight for target accessibility. + no_seed: Disable seed constraint. + verbose: Be verbose. + threads: Maximal number of threads for parallel computation. + + Returns: + A dictionary containing the executed command, stdout, stderr, and output file paths. + """ + # Input validation + if not query.is_file(): + raise FileNotFoundError(f"Query file not found: {query}") + if not target.is_file(): + raise FileNotFoundError(f"Target file not found: {target}") + + # Validate choice parameters + valid_out_modes = ['c', 'C', 'd', 'D', 's'] + if out_mode not in valid_out_modes: + raise ValueError(f"Invalid out_mode '{out_mode}'. Must be one of {valid_out_modes}") + + valid_out_overlaps = ['N', 'Q', 'T'] + if out_overlap not in valid_out_overlaps: + raise ValueError(f"Invalid out_overlap '{out_overlap}'. Must be one of {valid_out_overlaps}") + + valid_acc_modes = ['W', 'C', 'S', 'N', 'R'] + if q_acc not in valid_acc_modes: + raise ValueError(f"Invalid q_acc '{q_acc}'. Must be one of {valid_acc_modes}") + if t_acc not in valid_acc_modes: + raise ValueError(f"Invalid t_acc '{t_acc}'. Must be one of {valid_acc_modes}") + + if q_acc == 'R' and (q_acc_file is None or not q_acc_file.is_file()): + raise ValueError("q_acc_file must be provided and exist when q_acc is 'R'") + if t_acc == 'R' and (t_acc_file is None or not t_acc_file.is_file()): + raise ValueError("t_acc_file must be provided and exist when t_acc is 'R'") + + if q_idx_file and not q_idx_file.is_file(): + raise FileNotFoundError(f"Query index file not found: {q_idx_file}") + if t_idx_file and not t_idx_file.is_file(): + raise FileNotFoundError(f"Target index file not found: {t_idx_file}") + + valid_interaction_types = ['H', 'I', 'B'] + if interaction_type not in valid_interaction_types: + raise ValueError(f"Invalid interaction_type '{interaction_type}'. Must be one of {valid_interaction_types}") + + valid_energy_models = ['V', 'S'] + if energy not in valid_energy_models: + raise ValueError(f"Invalid energy model '{energy}'. Must be one of {valid_energy_models}") + + # Command construction + cmd = ["IntaRNA", f"--query={query}", f"--target={target}"] + + # Output handling + output_files = {} + if out: + output_path = out + else: + tmp_out = tempfile.NamedTemporaryFile(delete=False, mode='w', suffix=".csv") + tmp_out.close() + output_path = Path(tmp_out.name) + + output_files["predictions"] = str(output_path) + cmd.append(f"--out={output_path}") + + # Add optional parameters if they differ from the default + if n_best != 100: cmd.append(f"--nBest={n_best}") + if out_mode != "C": cmd.append(f"--outMode={out_mode}") + if out_overlap != "N": cmd.append(f"--outOverlap={out_overlap}") + if out_csv_cols is not None: cmd.append(f'--outCsvCols="{out_csv_cols}"') + if out_max_e is not None: cmd.append(f"--outMaxE={out_max_e}") + if out_min_pu1 != 0.0: cmd.append(f"--outMinPu1={out_min_pu1}") + if out_min_pu2 != 0.0: cmd.append(f"--outMinPu2={out_min_pu2}") + if out_best != 1: cmd.append(f"--outBest={out_best}") + if out_sub_opt is not None: cmd.append(f'--outSubOpt="{out_sub_opt}"') + if out_per_tar != 0: cmd.append(f"--outPerTar={out_per_tar}") + if out_per_qry != 0: cmd.append(f"--outPerQry={out_per_qry}") + if out_no_lp: cmd.append("--outNoLP") + + # Interaction parameters + if q_acc != "W": cmd.append(f"--qAcc={q_acc}") + if q_acc_file: cmd.append(f"--qAccFile={q_acc_file}") + if q_acc_w != 150: cmd.append(f"--qAccW={q_acc_w}") + if q_acc_l != 100: cmd.append(f"--qAccL={q_acc_l}") + if q_acc_constr: cmd.append(f'--qAccConstr="{q_acc_constr}"') + if q_int_len_max != 150: cmd.append(f"--qIntLenMax={q_int_len_max}") + if q_int_loop != 16: cmd.append(f"--qIntLoop={q_int_loop}") + if q_max_bp != 200: cmd.append(f"--qMaxBP={q_max_bp}") + if q_region: cmd.append(f"--qRegion={q_region}") + if q_idx_pos: cmd.append(f"--qIdxPos={q_idx_pos}") + if q_idx_file: cmd.append(f"--qIdxFile={q_idx_file}") + + if t_acc != "W": cmd.append(f"--tAcc={t_acc}") + if t_acc_file: cmd.append(f"--tAccFile={t_acc_file}") + if t_acc_w != 150: cmd.append(f"--tAccW={t_acc_w}") + if t_acc_l != 100: cmd.append(f"--tAccL={t_acc_l}") + if t_acc_constr: cmd.append(f'--tAccConstr="{t_acc_constr}"') + if t_int_len_max != 150: cmd.append(f"--tIntLenMax={t_int_len_max}") + if t_int_loop != 16: cmd.append(f"--tIntLoop={t_int_loop}") + if t_max_bp != 200: cmd.append(f"--tMaxBP={t_max_bp}") + if t_region: cmd.append(f"--tRegion={t_region}") + if t_idx_pos: cmd.append(f"--tIdxPos={t_idx_pos}") + if t_idx_file: cmd.append(f"--tIdxFile={t_idx_file}") + + if interaction_span: cmd.append(f"--interactionSpan={interaction_span}") + if interaction_type != "I": cmd.append(f"--interactionType={interaction_type}") + if energy != "V": cmd.append(f"--energy={energy}") + if temperature != 37.0: cmd.append(f"--temperature={temperature}") + if no_gu_end: cmd.append("--noGUend") + if no_closing_gu: cmd.append("--noClosingGU") + if max_loop != 16: cmd.append(f"--maxLoop={max_loop}") + if max_bp != 200: cmd.append(f"--maxBP={max_bp}") + if no_lpi: cmd.append("--noLPI") + if lp: cmd.append("--lp") + + # Seed parameters + if seed_bp != 2: cmd.append(f"--seedBP={seed_bp}") + if seed_max_up != 0: cmd.append(f"--seedMaxUP={seed_max_up}") + if seed_q_max_up != 0: cmd.append(f"--seedQMaxUP={seed_q_max_up}") + if seed_t_max_up != 0: cmd.append(f"--seedTMaxUP={seed_t_max_up}") + if seed_u_left != 0: cmd.append(f"--seedULeft={seed_u_left}") + if seed_u_right != 0: cmd.append(f"--seedURight={seed_u_right}") + if seed_q_region: cmd.append(f"--seedQRegion={seed_q_region}") + if seed_t_region: cmd.append(f"--seedTRegion={seed_t_region}") + if seed_constraint: cmd.append(f'--seedConstraint="{seed_constraint}"') + if seed_ref: cmd.append(f"--seedRef={seed_ref}") + if seed_s1 != 1.0: cmd.append(f"--seedS1={seed_s1}") + if seed_s2 != 1.0: cmd.append(f"--seedS2={seed_s2}") + if no_seed: cmd.append("--noSeed") + + # Misc parameters + if verbose: cmd.append("--verbose") + if threads != 0: cmd.append(f"--threads={threads}") + + # Subprocess execution + try: + command_str = " ".join(map(str, cmd)) + result = subprocess.run( + command_str, + shell=True, + capture_output=True, + text=True, + check=True + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + if not out and output_path.exists(): + output_path.unlink() + return { + "error": "IntaRNA execution failed", + "command_executed": " ".join(map(str, cmd)), + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode + } + except FileNotFoundError: + return { + "error": "IntaRNA executable not found in PATH.", + "command_executed": " ".join(map(str, cmd)), + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_intarna/app/intarna_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_intarna/app/intarna_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..65a487d20a2f55345f6d8864ec96a9454a176848 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_intarna/app/intarna_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_intarna/app/intarna_server.py') +SERVER_NAME = 'biosci_intarna' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_intarna/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_intarna/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_intarna/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_intarna/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_intarna/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..19d358cc3aca89575326009f64ef9deb40dec94e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_intarna/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-intarna: + build: . + image: mcp-intarna:latest + container_name: mcp-intarna + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=intarna + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_intarna/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_intarna/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c555c6076e1b547beff2356ff99d5e5f8c1a7ca8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_intarna/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - intarna + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_intarna/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_intarna/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_intarna/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_involucro/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_involucro/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..00298cf566da4b5de7370c4d0b6149ad2bf032ce --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_involucro/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install involucro via conda (e.g., from bioconda) +RUN conda install -c bioconda involucro -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/involucro_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/involucro_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/involucro_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_involucro/app/involucro_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_involucro/app/involucro_server.py new file mode 100644 index 0000000000000000000000000000000000000000..51b21ecf944df1bd4ae9761bb4f5fccb8efc9ed0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_involucro/app/involucro_server.py @@ -0,0 +1,154 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + + +@mcp.tool() +def involucro_execute( + control_file: str = "invfile.lua", + eval_script: Optional[str] = None, + docker_host: str = "unix:///var/run/docker.sock", + set_vars: Optional[List[str]] = None, + verbosity: int = 1, + working_dir: str = ".", + wrap_task: Optional[str] = None, + tasks: Optional[List[str]] = None, +) -> Dict[str, Any]: + """ + Execute involucro to run tasks defined in a Lua control file or a direct script. + Involucro is a tool for automating Docker-based workflows. + + Args: + control_file: Set the control file (default "invfile.lua"). + eval_script: Evaluate the given script directly, not evaluating the control file. + docker_host: Set the URL of the Docker instance (default "unix:///var/run/docker.sock"). + set_vars: List of KEY=VALUE pairs to make VAR[KEY] available in the Lua script. + verbosity: Set verbosity: 3 logs everything, 2 shows standard output, 1 is default. + working_dir: Set working directory, base for all operations. + wrap_task: Execute encoded wrap task. + tasks: Specific tasks to execute (positional arguments). + """ + cmd = ["involucro"] + + # Docker Host + cmd.extend(["-H", docker_host]) + + # Verbosity + if verbosity not in [1, 2, 3]: + # Defaulting to 1 if invalid input provided + verbosity = 1 + cmd.extend(["-v", str(verbosity)]) + + # Working Directory + work_path = Path(working_dir) + if not work_path.exists(): + return {"error": f"Working directory '{working_dir}' does not exist."} + cmd.extend(["-w", str(work_path)]) + + # Control File vs Eval Script + if eval_script: + cmd.extend(["-e", eval_script]) + else: + cf_path = Path(control_file) + # Only validate if it's not the default or if user explicitly set it + if control_file != "invfile.lua" or cf_path.exists(): + if not cf_path.exists(): + return {"error": f"Control file '{control_file}' not found."} + cmd.extend(["-f", str(cf_path)]) + + # Set Variables + if set_vars: + for var in set_vars: + if "=" not in var: + return {"error": f"Variable '{var}' must be in KEY=VALUE format."} + cmd.extend(["-set", var]) + + # Wrap Task + if wrap_task: + cmd.extend(["-wrap", wrap_task]) + + # Positional Tasks + if tasks: + cmd.extend(tasks) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "failed" + } + + +@mcp.tool() +def involucro_list_tasks( + control_file: str = "invfile.lua", + working_dir: str = ".", + docker_host: str = "unix:///var/run/docker.sock", +) -> Dict[str, Any]: + """ + Show available tasks defined in the involucro control file and then exit. + + Args: + control_file: Set the control file (default "invfile.lua"). + working_dir: Set working directory. + docker_host: Set the URL of the Docker instance. + """ + cmd = ["involucro", "-tasks"] + + cmd.extend(["-H", docker_host]) + + work_path = Path(working_dir) + if work_path.exists(): + cmd.extend(["-w", str(work_path)]) + + cf_path = Path(control_file) + if cf_path.exists(): + cmd.extend(["-f", str(cf_path)]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "available_tasks": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to list tasks. Ensure the control file exists and is valid.", + "status": "failed" + } + + +@mcp.tool() +def involucro_version() -> Dict[str, Any]: + """ + Show the version of involucro and exit. + """ + cmd = ["involucro", "-version"] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "version_info": result.stdout.strip(), + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "status": "failed" + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_involucro/app/involucro_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_involucro/app/involucro_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8a08431468d96ce1c60440cd76786f0faab658a4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_involucro/app/involucro_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_involucro/app/involucro_server.py') +SERVER_NAME = 'biosci_involucro' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_involucro/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_involucro/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_involucro/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_involucro/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_involucro/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..908cb469ca0371e077f49f4996b2c55640adc87e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_involucro/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-involucro: + build: . + image: mcp-involucro:latest + container_name: mcp-involucro + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=involucro + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_involucro/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_involucro/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3df240193f1a112c7e50dcab2bff62f2a2c078f4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_involucro/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - involucro + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_involucro/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_involucro/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_involucro/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iow/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iow/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..699480338aaa62c52b977276664b04ea089856da --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iow/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install iow via conda (e.g., from bioconda) +RUN conda install -c bioconda iow -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/iow_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/iow_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/iow_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iow/app/iow_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iow/app/iow_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ffd3da70ee3baa1cd0817f5e5ef4780873833021 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iow/app/iow_server.py @@ -0,0 +1,96 @@ +import subprocess +from pathlib import Path +from typing import Literal, Dict + +# @mcp.tool() is a placeholder for the MCP decorator. +# The actual MCP framework would provide this. +# For this exercise, we'll define a dummy decorator to make the code runnable. +def tool_decorator_dummy(*args, **kwargs): + def decorator(func): + return func + return decorator + +mcp = type('mcp', (), {'tool': tool_decorator_dummy}) + + +@mcp.tool() +def placement( + placements: Path, + output: Path, + method: Literal["fully-resolved", "multifurcating"], +) -> Dict: + """ + Handles fragment insertions from a jplace file into a tree using the 'bp' command. + + This tool supports two methods for inserting fragments: + - 'fully-resolved': The edge placed against is broken N times, where N is the number of fragments on the edge. + - 'multifurcating': A new node is constructed as the average of the distal length for the N fragments, + and a separate multifurcation node is added which encompasses the placed fragments. + Note: The 'multifurcating' method requires the 'iow-gpl' package. + + Args: + placements (Path): Path to the input jplace formatted data file. + output (Path): Path where the resulting newick file will be written. + method (Literal["fully-resolved", "multifurcating"]): The method to use for fragment insertion. + + Returns: + Dict: A dictionary containing the execution details and output file path. + """ + # 1. Input Validation + if not placements.is_file(): + raise FileNotFoundError(f"Input placements file not found: {placements}") + + # The 'method' parameter is validated by the Literal type hint at static analysis time. + # A runtime check is included for robustness. + if method not in ["fully-resolved", "multifurcating"]: + raise ValueError(f"Invalid method '{method}'. Must be 'fully-resolved' or 'multifurcating'.") + + # Ensure the output directory exists + try: + output.parent.mkdir(parents=True, exist_ok=True) + except Exception as e: + raise IOError(f"Could not create output directory {output.parent}: {e}") + + # 2. Command Construction + cmd = [ + "bp", "placement", + "--placements", str(placements), + "--output", str(output), + "--method", method, + ] + command_executed = " ".join(cmd) + + # 3. Subprocess Execution and Error Handling + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + encoding='utf-8' + ) + + # 4. Structured Result Return + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"output_newick": str(output)} + } + except FileNotFoundError: + # This error is caught if the 'bp' command is not found in the system's PATH. + error_message = "Error: 'bp' command not found. Make sure the 'iow' package is installed and its bin directory is in the system's PATH." + return { + "command_executed": command_executed, + "stdout": "", + "stderr": error_message, + "output_files": {} + } + except subprocess.CalledProcessError as e: + # This error is caught if the tool returns a non-zero exit code. + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": {} + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iow/app/iow_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iow/app/iow_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d798e99e2c44b177169314ebff065619fc7abdc8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iow/app/iow_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iow/app/iow_server.py') +SERVER_NAME = 'biosci_iow' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iow/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iow/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iow/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iow/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iow/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..6344efa4829bddca1fb42cc9fe17879837337f8e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iow/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-iow: + build: . + image: mcp-iow:latest + container_name: mcp-iow + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=iow + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iow/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iow/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c3713b5ea0dc47a5b42a80767a15a281bebdfb59 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iow/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - iow + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iow/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iow/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iow/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipyrad/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipyrad/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5236eebe1d864c12b08ae081475cf4ca6463f409 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipyrad/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install ipyrad via conda (e.g., from bioconda) +RUN conda install -c bioconda ipyrad -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/ipyrad_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/ipyrad_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/ipyrad_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipyrad/app/ipyrad_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipyrad/app/ipyrad_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8660813ad3a9eabcc975f658fdbfe88fb10e4815 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipyrad/app/ipyrad_server.py @@ -0,0 +1,243 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, List + +# Set up logging for better debugging in a server environment +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') + +# MCP decorator is assumed to be provided by the execution environment. +# This is a placeholder for the actual decorator. +class mcp: + @staticmethod + def tool(func): + return func + +@mcp.tool +def ipyrad_new_params( + name: str, + force: bool = False, + output_dir: Optional[Path] = None +) -> dict: + """ + Creates a new ipyrad parameters file (params-.txt). + + This corresponds to the command `ipyrad -n -p new`. + + Args: + name: The project name for the analysis. + force: If True, overwrite an existing params file with the same name (-f). + output_dir: Directory where the params file will be created. Defaults to the current working directory. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the created params file. + """ + # Input validation + if not name or not name.strip(): + raise ValueError("Project name must be a non-empty string.") + + cmd = ["ipyrad", "-n", name, "-p", "new"] + if force: + cmd.append("-f") + + # Determine the working directory for the command + work_dir = output_dir if output_dir else Path.cwd() + if output_dir: + output_dir.mkdir(parents=True, exist_ok=True) + + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed} in {work_dir}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + cwd=work_dir, + ) + + output_file = work_dir / f"params-{name}.txt" + if not output_file.exists(): + raise FileNotFoundError( + f"ipyrad command ran successfully but the expected output file was not found: {output_file}\n" + f"STDOUT: {result.stdout}\nSTDERR: {result.stderr}" + ) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_file)] + } + + except FileNotFoundError: + err_msg = "Error: 'ipyrad' command not found. Make sure ipyrad is installed and in your system's PATH." + logging.error(err_msg) + return { + "command_executed": command_executed, + "stdout": "", + "stderr": err_msg, + "output_files": [] + } + except subprocess.CalledProcessError as e: + logging.error(f"ipyrad failed with exit code {e.returncode}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + +@mcp.tool +def ipyrad_run_analysis( + name: str, + params: Path, + steps: str, + cores: int = 1, + threads: int = 1, + force: bool = False, + debug: bool = False, + custom_map: Optional[Path] = None, +) -> dict: + """ + Runs the ipyrad analysis pipeline for one or more steps. + + This corresponds to the command `ipyrad -n -p -s -r ...`. + + Args: + name: The project name for the analysis (must match the name in the params file). + params: Path to the ipyrad parameters file (e.g., 'params-myproject.txt'). + steps: A string of digits representing the steps to run (e.g., '123' or '34567'). + cores: Number of cores to use for parallel jobs (-c). + threads: Number of threads per core for parallel jobs (-t). + force: If True, force overwrite of existing data for the specified steps (-f). + debug: If True, print debug messages to the terminal (-d). + custom_map: Path to a file with ipyrad -n and -p info for many jobs (-m). + + Returns: + A dictionary containing the command executed, stdout, stderr, and the path to the main output directory. + """ + # Input validation + if not name or not name.strip(): + raise ValueError("Project name must be a non-empty string.") + if not params.is_file(): + raise FileNotFoundError(f"Parameters file not found at: {params}") + if not steps or not steps.isdigit() or any(c not in "1234567" for c in steps): + raise ValueError("Steps must be a string containing only digits from 1 to 7 (e.g., '123').") + if cores < 1: + raise ValueError("Number of cores must be a positive integer.") + if threads < 1: + raise ValueError("Number of threads must be a positive integer.") + if custom_map and not custom_map.is_file(): + raise FileNotFoundError(f"Custom map file not found at: {custom_map}") + + cmd = [ + "ipyrad", + "-n", name, + "-p", str(params.resolve()), + "-s", steps, + "-c", str(cores), + "-t", str(threads), + "-r" # The -r flag is essential to execute the run + ] + + if force: + cmd.append("-f") + if debug: + cmd.append("-d") + if custom_map: + cmd.extend(["-m", str(custom_map.resolve())]) + + # ipyrad creates its output directory relative to the current working directory. + # It's best practice to run it from the directory containing the params file. + work_dir = params.parent + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed} in {work_dir}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + cwd=work_dir, + ) + + # The primary output is a directory named after the project + output_directory = work_dir / name + output_files = [str(output_directory)] if output_directory.is_dir() else [] + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + + except FileNotFoundError: + err_msg = "Error: 'ipyrad' command not found. Make sure ipyrad is installed and in your system's PATH." + logging.error(err_msg) + return { + "command_executed": command_executed, + "stdout": "", + "stderr": err_msg, + "output_files": [] + } + except subprocess.CalledProcessError as e: + logging.error(f"ipyrad failed with exit code {e.returncode}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + +@mcp.tool +def ipyrad_version() -> dict: + """ + Gets the installed version of ipyrad. + + This corresponds to the command `ipyrad -v`. + + Returns: + A dictionary containing the command executed, stdout, stderr, and the parsed version string. + """ + cmd = ["ipyrad", "-v"] + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + # The version is usually the only thing in stdout, e.g., "ipyrad 0.9.87" + version_string = result.stdout.strip().split()[-1] + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "version": version_string + } + except FileNotFoundError: + err_msg = "Error: 'ipyrad' command not found. Make sure ipyrad is installed and in your system's PATH." + logging.error(err_msg) + return { + "command_executed": command_executed, + "stdout": "", + "stderr": err_msg, + "version": None + } + except (subprocess.CalledProcessError, IndexError) as e: + stderr = e.stderr if hasattr(e, 'stderr') else str(e) + stdout = e.stdout if hasattr(e, 'stdout') else "" + logging.error(f"ipyrad -v failed: {stderr}") + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "version": None + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipyrad/app/ipyrad_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipyrad/app/ipyrad_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f88d02eeff7526b1bb9c72f5026e0702a4f8dd16 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipyrad/app/ipyrad_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipyrad/app/ipyrad_server.py') +SERVER_NAME = 'biosci_ipyrad' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipyrad/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipyrad/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipyrad/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipyrad/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipyrad/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..48be8956727034a48aecd5dd60fa915f08cde466 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipyrad/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-ipyrad: + build: . + image: mcp-ipyrad:latest + container_name: mcp-ipyrad + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=ipyrad + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipyrad/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipyrad/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..104c5fae4ae2884880d9269acc6df2dfb115fc74 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipyrad/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - ipyrad + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipyrad/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipyrad/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipyrad/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipython-cluster-helper/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipython-cluster-helper/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9b18187e520a44623297eb5b58cb3eac46852d2f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipython-cluster-helper/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install ipython-cluster-helper via conda (e.g., from bioconda) +RUN conda install -c bioconda ipython-cluster-helper -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/ipython-cluster-helper_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/ipython-cluster-helper_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/ipython-cluster-helper_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipython-cluster-helper/app/ipython-cluster-helper_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipython-cluster-helper/app/ipython-cluster-helper_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7dd32acae5ffc4a4773f6dee609062052a5b9f95 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipython-cluster-helper/app/ipython-cluster-helper_server.py @@ -0,0 +1,434 @@ +import subprocess +import shlex +from pathlib import Path +from typing import Optional, List, Literal + +# MCP decorator is not defined in this context, but the code is written +# as if it were, following the user's request. +# from mcp import mcp + +class MCPPlaceholder: + def tool(self): + def decorator(func): + return func + return decorator + +mcp = MCPPlaceholder() + +@mcp.tool() +def start( + queue: str, + num_cores: Optional[int] = None, + profile: Optional[str] = None, + timeout: Optional[int] = None, + retries: Optional[int] = None, + scheduler: Optional[Literal["lsf", "sge", "slurm", "torque", "pbspro"]] = None, + resources: Optional[List[str]] = None, + engine: Optional[Literal["ipython", "torque", "slurm", "sge", "lsf", "pbspro"]] = None, + extra_args: Optional[str] = None, +): + """ + Starts an IPython cluster. + + Args: + queue: The queue to submit jobs to. + num_cores: The number of cores to start. + profile: The IPython profile to use. + timeout: The timeout in seconds to wait for the cluster to start. + retries: The number of times to retry starting the cluster. + scheduler: The type of scheduler to use. + resources: Extra scheduler resource flags. Can be specified multiple times. + engine: The engine to use. + extra_args: Extra arguments to pass to the ipcluster engines. + """ + # Input validation + if num_cores is not None and num_cores <= 0: + raise ValueError("num_cores must be a positive integer.") + if timeout is not None and timeout <= 0: + raise ValueError("timeout must be a positive integer.") + if retries is not None and retries < 0: + raise ValueError("retries must be a non-negative integer.") + + command = ["ipython-cluster-helper", "start", "-q", queue] + + if num_cores is not None: + command.extend(["-n", str(num_cores)]) + if profile: + command.extend(["-p", profile]) + if timeout is not None: + command.extend(["-t", str(timeout)]) + if retries is not None: + command.extend(["-r", str(retries)]) + if scheduler: + command.extend(["--scheduler", scheduler]) + if resources: + for resource in resources: + command.extend(["--resources", resource]) + if engine: + command.extend(["--engine", engine]) + if extra_args: + command.extend(["--extra-args", extra_args]) + + command_str = shlex.join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: ipython-cluster-helper not found. Is it installed and in your PATH?", + "error": "Tool not found", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Process failed with exit code {e.returncode}", + "output_files": [] + } + +@mcp.tool() +def stop( + profile: Optional[str] = None, + timeout: Optional[int] = None, +): + """ + Stops an IPython cluster. + + Args: + profile: The IPython profile to use. + timeout: The timeout in seconds to wait for the cluster to stop. + """ + # Input validation + if timeout is not None and timeout <= 0: + raise ValueError("timeout must be a positive integer.") + + command = ["ipython-cluster-helper", "stop"] + + if profile: + command.extend(["-p", profile]) + if timeout is not None: + command.extend(["-t", str(timeout)]) + + command_str = shlex.join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: ipython-cluster-helper not found. Is it installed and in your PATH?", + "error": "Tool not found", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Process failed with exit code {e.returncode}", + "output_files": [] + } + +@mcp.tool() +def update( + queue: str, + num_cores: int, + profile: Optional[str] = None, + timeout: Optional[int] = None, +): + """ + Updates an IPython cluster. + + Args: + queue: The queue to submit jobs to. + num_cores: The number of cores to start. + profile: The IPython profile to use. + timeout: The timeout in seconds to wait for the cluster to start. + """ + # Input validation + if num_cores <= 0: + raise ValueError("num_cores must be a positive integer.") + if timeout is not None and timeout <= 0: + raise ValueError("timeout must be a positive integer.") + + command = ["ipython-cluster-helper", "update", "-q", queue, "-n", str(num_cores)] + + if profile: + command.extend(["-p", profile]) + if timeout is not None: + command.extend(["-t", str(timeout)]) + + command_str = shlex.join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: ipython-cluster-helper not found. Is it installed and in your PATH?", + "error": "Tool not found", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Process failed with exit code {e.returncode}", + "output_files": [] + } + +@mcp.tool() +def info( + profile: Optional[str] = None, + queue: Optional[str] = None, +): + """ + Gets information on an IPython cluster. + + Args: + profile: The IPython profile to use. + queue: The queue to submit jobs to. + """ + command = ["ipython-cluster-helper", "info"] + + if profile: + command.extend(["-p", profile]) + if queue: + command.extend(["-q", queue]) + + command_str = shlex.join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: ipython-cluster-helper not found. Is it installed and in your PATH?", + "error": "Tool not found", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Process failed with exit code {e.returncode}", + "output_files": [] + } + +@mcp.tool() +def clean( + profile: Optional[str] = None, +): + """ + Cleans a cluster's log and pid files. + + Args: + profile: The IPython profile to use. + """ + command = ["ipython-cluster-helper", "clean"] + + if profile: + command.extend(["-p", profile]) + + command_str = shlex.join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: ipython-cluster-helper not found. Is it installed and in your PATH?", + "error": "Tool not found", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Process failed with exit code {e.returncode}", + "output_files": [] + } + +@mcp.tool() +def log( + profile: Optional[str] = None, +): + """ + Tails the log of a cluster. + + Args: + profile: The IPython profile to use. + """ + command = ["ipython-cluster-helper", "log"] + + if profile: + command.extend(["-p", profile]) + + command_str = shlex.join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: ipython-cluster-helper not found. Is it installed and in your PATH?", + "error": "Tool not found", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Process failed with exit code {e.returncode}", + "output_files": [] + } + +@mcp.tool() +def test( + queue: str, + num_cores: Optional[int] = None, + profile: Optional[str] = None, + scheduler: Optional[Literal["lsf", "sge", "slurm", "torque", "pbspro"]] = None, + engine: Optional[Literal["ipython", "torque", "slurm", "sge", "lsf", "pbspro"]] = None, + retries: Optional[int] = None, +): + """ + Tests an IPython cluster. + + Args: + queue: The queue to submit jobs to. + num_cores: The number of cores to start. + profile: The IPython profile to use. + scheduler: The type of scheduler to use. + engine: The engine to use. + retries: The number of times to retry starting the cluster. + """ + # Input validation + if num_cores is not None and num_cores <= 0: + raise ValueError("num_cores must be a positive integer.") + if retries is not None and retries < 0: + raise ValueError("retries must be a non-negative integer.") + + command = ["ipython-cluster-helper", "test", "-q", queue] + + if num_cores is not None: + command.extend(["-n", str(num_cores)]) + if profile: + command.extend(["-p", profile]) + if scheduler: + command.extend(["--scheduler", scheduler]) + if engine: + command.extend(["--engine", engine]) + if retries is not None: + command.extend(["--retries", str(retries)]) + + command_str = shlex.join(command) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: ipython-cluster-helper not found. Is it installed and in your PATH?", + "error": "Tool not found", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Process failed with exit code {e.returncode}", + "output_files": [] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipython-cluster-helper/app/ipython-cluster-helper_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipython-cluster-helper/app/ipython-cluster-helper_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c2e439d1a0f5c0dffe4fbe8765ed3b404ae45e0c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipython-cluster-helper/app/ipython-cluster-helper_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipython-cluster-helper/app/ipython-cluster-helper_server.py') +SERVER_NAME = 'biosci_ipython_cluster_helper' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipython-cluster-helper/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipython-cluster-helper/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipython-cluster-helper/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipython-cluster-helper/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipython-cluster-helper/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..3e61a4b48ffa9a2d6a43e3f2ac8fa971ff76c75d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipython-cluster-helper/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-ipython-cluster-helper: + build: . + image: mcp-ipython-cluster-helper:latest + container_name: mcp-ipython-cluster-helper + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=ipython-cluster-helper + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipython-cluster-helper/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipython-cluster-helper/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..54859e08ce535db7e3a52c09ea7e6c21f89dc37c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipython-cluster-helper/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - ipython-cluster-helper + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipython-cluster-helper/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipython-cluster-helper/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ipython-cluster-helper/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iqtree/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iqtree/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6a02a813c9e10e4053a1507608171eb1dcc735f2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iqtree/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install iqtree via conda (e.g., from bioconda) +RUN conda install -c bioconda iqtree -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/iqtree_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/iqtree_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/iqtree_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iqtree/app/iqtree_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iqtree/app/iqtree_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c4e65a40c5097b81d66a98808c025418837f374c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iqtree/app/iqtree_server.py @@ -0,0 +1,198 @@ +import subprocess +import logging +import tempfile +from pathlib import Path +from typing import Optional, List + +# Assume @mcp.tool is defined in the execution environment. +# For local testing, you can use a dummy decorator: +# def mcp_tool(): +# def decorator(f): +# return f +# return decorator + +# Set up logging +logging.basicConfig(level=logging.INFO) +logger = logging.getLogger(__name__) + +@mcp.tool() +def iqtree_build_tree( + alignment: Path, + prefix: Optional[str] = None, + sequence_type: Optional[str] = None, + model: Optional[str] = None, + partition: Optional[Path] = None, + starting_tree: Optional[Path] = None, + constraint_tree: Optional[Path] = None, + ufboot: Optional[int] = None, + alrt: Optional[int] = None, + bootstrap: Optional[int] = None, + bnni: bool = False, + threads: Optional[int] = None, + seed: Optional[int] = None, + mem: Optional[str] = None, + redo: bool = False, + safe: bool = False, + verbose: bool = False, + fast: bool = False, + nstop: Optional[int] = None, + ninit: Optional[int] = None, + allnni: bool = False, +) -> dict: + """ + Performs phylogenetic tree inference using IQ-TREE 2. + + This tool wraps the 'iqtree2' command-line tool to build a phylogenetic tree + from a multiple sequence alignment. It supports advanced features like automatic + model selection (ModelFinder), partitioned analysis, and various branch support + assessments including Ultrafast Bootstrap (UFBoot), SH-aLRT, and standard + non-parametric bootstrap. + + Args: + alignment: Path to the input alignment file (e.g., PHYLIP, FASTA). + prefix: Prefix for all output files. If not set, it's derived from the alignment file name. + sequence_type: Type of sequence data. Can be 'DNA', 'AA', 'CODON', 'BIN', or 'MORPH'. + model: Substitution model name (e.g., 'GTR+I+G'). Use 'MF' or 'MFP' for ModelFinder. + partition: Path to a partition file for partitioned analysis (e.g., NEXUS, RAxML format). + starting_tree: Path to a user-defined starting tree file in Newick format. + constraint_tree: Path to a constraint tree to guide the tree search. + ufboot: Number of replicates for Ultrafast Bootstrap (e.g., 1000). + alrt: Number of replicates for SH-like approximate likelihood ratio test (SH-aLRT) (e.g., 1000). + bootstrap: Number of replicates for standard non-parametric bootstrap (e.g., 100). + bnni: If True, apply nearest-neighbor interchange (NNI) optimization to UFBoot trees. Requires 'ufboot'. + threads: Number of threads to use. 'AUTO' is also a valid option for IQ-TREE. + seed: Random number seed for reproducibility. + mem: Maximum memory to use (e.g., '2G', '500M'). + redo: If True, overwrite existing result files. + safe: If True, use safe likelihood kernel to avoid numerical underflow. + verbose: If True, run in verbose mode for more detailed logs. + fast: If True, use a fast search algorithm. + nstop: Number of unsuccessful iterations to stop the tree search. + ninit: Number of initial parsimony trees to build. + allnni: If True, perform a more thorough NNI search on initial trees. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output file paths. + """ + # 1. Input Validation + if not alignment.is_file(): + raise FileNotFoundError(f"Alignment file not found at: {alignment}") + + if partition and not partition.is_file(): + raise FileNotFoundError(f"Partition file not found at: {partition}") + + if starting_tree and not starting_tree.is_file(): + raise FileNotFoundError(f"Starting tree file not found at: {starting_tree}") + + if constraint_tree and not constraint_tree.is_file(): + raise FileNotFoundError(f"Constraint tree file not found at: {constraint_tree}") + + if sequence_type and sequence_type.upper() not in ['DNA', 'AA', 'CODON', 'BIN', 'MORPH']: + raise ValueError(f"Invalid sequence_type: {sequence_type}. Must be one of 'DNA', 'AA', 'CODON', 'BIN', 'MORPH'.") + + if bnni and not ufboot: + raise ValueError("'bnni' can only be used when 'ufboot' is specified.") + + if ufboot is not None and ufboot <= 0: + raise ValueError("'ufboot' must be a positive integer.") + if alrt is not None and alrt <= 0: + raise ValueError("'alrt' must be a positive integer.") + if bootstrap is not None and bootstrap <= 0: + raise ValueError("'bootstrap' must be a positive integer.") + + # 2. Command Construction + # Using 'iqtree2' as it is the standard for recent versions. + cmd = ["iqtree2", "-s", str(alignment)] + + if prefix: + cmd.extend(["-pre", prefix]) + if sequence_type: + cmd.extend(["-st", sequence_type.upper()]) + if model: + cmd.extend(["-m", model]) + if partition: + cmd.extend(["-p", str(partition)]) + if starting_tree: + cmd.extend(["-t", str(starting_tree)]) + if constraint_tree: + cmd.extend(["-c", str(constraint_tree)]) + if ufboot: + cmd.extend(["-B", str(ufboot)]) + if alrt: + cmd.extend(["--alrt", str(alrt)]) + if bootstrap: + cmd.extend(["-b", str(bootstrap)]) + if bnni: + cmd.append("--bnni") + if threads: + cmd.extend(["-T", str(threads)]) + if seed: + cmd.extend(["--seed", str(seed)]) + if mem: + cmd.extend(["--mem", mem]) + if nstop: + cmd.extend(["--nstop", str(nstop)]) + if ninit: + cmd.extend(["--ninit", str(ninit)]) + if redo: + cmd.append("--redo") + if safe: + cmd.append("--safe") + if verbose: + cmd.append("-v") + if fast: + cmd.append("--fast") + if allnni: + cmd.append("--allnni") + + # 3. Subprocess Execution + command_str = " ".join(cmd) + logger.info(f"Executing command: {command_str}") + + try: + with tempfile.TemporaryDirectory() as tmpdir: + # Run IQ-TREE in a temporary directory to isolate outputs + result = subprocess.run( + cmd, + cwd=tmpdir, + check=True, + capture_output=True, + text=True + ) + + # 4. Collect Output Files + # Determine the prefix used by IQ-TREE to find output files + output_prefix_str = prefix if prefix else str(alignment.name) + # The prefix might contain directory parts, so we only glob for the basename + glob_pattern = f"{Path(output_prefix_str).name}.*" + + # Since we ran in tmpdir, we need to copy files out or report their temp path + # For MCP, it's better to move them to a predictable output location or just list them + # Here, we list them from the temp dir. The MCP runner should handle artifact collection. + output_files = [str(p) for p in Path(tmpdir).glob(glob_pattern)] + + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + + except FileNotFoundError: + logger.error("iqtree2 not found. Please ensure it is installed and in your PATH.") + return { + "command_executed": command_str, + "stdout": "", + "stderr": "Error: iqtree2 executable not found. Please ensure it is installed and in your system's PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + logger.error(f"IQ-TREE execution failed with exit code {e.returncode}") + logger.error(f"STDOUT: {e.stdout}") + logger.error(f"STDERR: {e.stderr}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iqtree/app/iqtree_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iqtree/app/iqtree_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..eef230fac5b195a9dc6284afe8668e6d7e74f7a5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iqtree/app/iqtree_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iqtree/app/iqtree_server.py') +SERVER_NAME = 'biosci_iqtree' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iqtree/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iqtree/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iqtree/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iqtree/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iqtree/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..37f222d8466073ce05435fa6112910a02ba15258 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iqtree/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-iqtree: + build: . + image: mcp-iqtree:latest + container_name: mcp-iqtree + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=iqtree + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iqtree/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iqtree/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..db3f10315f91197de1d0de7a4ec595892fc27e4b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iqtree/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - iqtree + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iqtree/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iqtree/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_iqtree/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_itsxpress/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_itsxpress/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..69fbb3f2b4f0e34d6cb8adf20339db91bc0adb4f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_itsxpress/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install itsxpress via conda (e.g., from bioconda) +RUN conda install -c bioconda itsxpress -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/itsxpress_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/itsxpress_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/itsxpress_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_itsxpress/app/itsxpress_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_itsxpress/app/itsxpress_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9f9414148177efcf0053ee9c110a61edb8b82067 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_itsxpress/app/itsxpress_server.py @@ -0,0 +1,150 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Literal + +# The mcp.tool decorator is omitted as per the instructions. +# In a real MCP environment, it would be: +# @mcp.tool() +def itsxpress( + fastq: Path, + outfile: Path, + region: Literal["ITS1", "ITS2", "ALL"], + taxa: Literal[ + "Alveolata", "Amoebozoa", "Bacillariophyta", "Bryophyta", "Chlorophyta", + "Eustigmatophyceae", "Euglenozoa", "Fungi", "Haptophyceae", "Marchantiophyta", + "Metazoa", "Oomycota", "Parabasalia", "Phaeophyceae", "Raphidophyceae", + "Rhizaria", "Rhodophyta", "Synurophyceae", "Tracheophyta", "All" + ] = "Fungi", + single_end: bool = False, + fastq2: Optional[Path] = None, + outfile2: Optional[Path] = None, + log: Optional[Path] = None, + tempdir: Optional[Path] = None, + keeptemp: bool = False, + cluster_id: float = 1.0, + threads: int = 1, + reversed_primers: bool = False, + allow_staggered_reads: bool = True, +) -> dict: + """ + Rapidly trims the Internally Transcribed Spacer (ITS) region from FASTQ files. + + ITSxpress takes FASTQ data, de-replicates the sequences, identifies the start + and stop sites using HMMSearch, and returns the trimmed sequences. It can + process single-end or paired-end reads and can target the ITS1, ITS2, or the + entire ITS region. + + Args: + fastq: Input FASTQ file (e.g., .fastq, .fq, .fastq.gz, .fq.gz). + outfile: Path for the trimmed output FASTQ file. + region: The ITS region to trim {'ITS1', 'ITS2', 'ALL'}. + taxa: The taxonomic group sequenced. Defaults to "Fungi". + single_end: Flag to specify that the input is single-ended. Defaults to False. + fastq2: Input FASTQ file for read 2 (for paired-end data). + outfile2: Path for the trimmed output FASTQ file for read 2. If used, + reads are returned as unmerged pairs. + log: Path for the log file. Defaults to 'ITSxpress.log' in the CWD. + tempdir: Specify a directory for temporary files. + keeptemp: If True, intermediate files will be kept. Defaults to False. + cluster_id: The percent identity for clustering reads [0.99-1.0]. + Set to 1.0 for exact de-replication. Defaults to 1.0. + threads: Number of processor threads to use. Defaults to 1. + reversed_primers: Set if primers are in reverse orientation. Trimmed reads + will be flipped to the forward orientation. Defaults to False. + allow_staggered_reads: Allow merging of staggered reads via Vsearch. + Defaults to True. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list + of output file paths. + """ + # 1. Input Validation + if not fastq.exists(): + raise FileNotFoundError(f"Input file not found: {fastq}") + if fastq2 and not fastq2.exists(): + raise FileNotFoundError(f"Input read 2 file not found: {fastq2}") + + if single_end and fastq2: + raise ValueError("The --fastq2 parameter cannot be used when --single_end is True.") + if not single_end and not fastq2: + raise ValueError("For paired-end data (--single_end is False), the --fastq2 parameter is required.") + if outfile2 and not fastq2: + raise ValueError("The --outfile2 parameter requires --fastq2 to be specified.") + + if not (0.99 <= cluster_id <= 1.0): + raise ValueError(f"cluster_id must be between 0.99 and 1.0, but was {cluster_id}.") + if threads < 1: + raise ValueError(f"threads must be a positive integer, but was {threads}.") + + # 2. Command Construction + cmd = [ + "itsxpress", + "--fastq", str(fastq), + "--outfile", str(outfile), + "--region", region, + "--taxa", taxa, + "--cluster_id", str(cluster_id), + "--threads", str(threads), + ] + + if single_end: + cmd.append("--single_end") + elif fastq2: + cmd.extend(["--fastq2", str(fastq2)]) + + if outfile2: + cmd.extend(["--outfile2", str(outfile2)]) + + if log: + cmd.extend(["--log", str(log)]) + + if tempdir: + cmd.extend(["--tempdir", str(tempdir)]) + + if keeptemp: + cmd.append("--keeptemp") + + if reversed_primers: + cmd.append("--reversed_primers") + + if allow_staggered_reads: + cmd.append("--allow_staggered_reads") + + # 3. Subprocess Execution + command_str = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except FileNotFoundError: + raise RuntimeError("itsxpress command not found. Please ensure it is installed and in your PATH.") + except subprocess.CalledProcessError as e: + # Return a structured error dictionary if the command fails + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + "error": "ITSxpress execution failed." + } + + # 4. Output File Collection + output_files = [str(outfile)] + if outfile2: + output_files.append(str(outfile2)) + + # The tool creates 'ITSxpress.log' by default if --log is not specified + log_path = log if log else Path("ITSxpress.log") + if log_path.exists(): + output_files.append(str(log_path)) + + # 5. Structured Result Return + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": sorted(list(set(output_files))) # Ensure unique paths + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_itsxpress/app/itsxpress_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_itsxpress/app/itsxpress_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..ed6e77750c0304b69e476cf9f54456cf8207b0b7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_itsxpress/app/itsxpress_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_itsxpress/app/itsxpress_server.py') +SERVER_NAME = 'biosci_itsxpress' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_itsxpress/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_itsxpress/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_itsxpress/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_itsxpress/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_itsxpress/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..eebb6c5d4aeda79f5d46a5862a22da254508fc6a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_itsxpress/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-itsxpress: + build: . + image: mcp-itsxpress:latest + container_name: mcp-itsxpress + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=itsxpress + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_itsxpress/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_itsxpress/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c248caddd57439045da1bb2cccecfa689d565c1a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_itsxpress/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - itsxpress + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_itsxpress/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_itsxpress/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_itsxpress/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ivar/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ivar/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6b38b27f5e3c24b53aef7f525064603a39633b94 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ivar/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install ivar via conda (e.g., from bioconda) +RUN conda install -c bioconda ivar -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/ivar_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/ivar_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/ivar_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ivar/app/ivar_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ivar/app/ivar_server.py new file mode 100644 index 0000000000000000000000000000000000000000..60a0fee3e5f23bc1239ad07490c2d5eb3daf46db --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ivar/app/ivar_server.py @@ -0,0 +1,459 @@ +import subprocess +from pathlib import Path +from typing import Optional, List + +# MCP decorator is a placeholder for the final environment. +# It is not defined here, so this code is not directly executable +# without the MCP framework. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +@mcp.tool() +def ivar_trim( + bam_file: Path, + bed_file: Path, + output_prefix: str, + include_mismatches: bool = False, + min_length: int = 30, + min_quality: int = 20, + window_size: int = 5, +) -> dict: + """ + Trims reads in a BAM file based on primer locations and quality. + This is useful for removing primer sequences from reads in amplicon-based sequencing. + """ + # --- Input Validation --- + if not bam_file.is_file(): + raise FileNotFoundError(f"Input BAM file not found: {bam_file}") + if not bed_file.is_file(): + raise FileNotFoundError(f"Input BED file not found: {bed_file}") + if not output_prefix: + raise ValueError("Output prefix cannot be empty.") + if min_length < 0: + raise ValueError("min_length must be a non-negative integer.") + if not (0 <= min_quality <= 40): + raise ValueError("min_quality must be between 0 and 40.") + if window_size <= 0: + raise ValueError("window_size must be a positive integer.") + + output_bam = Path(f"{output_prefix}.trimmed.bam") + + # --- Command Construction --- + cmd = [ + "ivar", "trim", + "-i", str(bam_file), + "-b", str(bed_file), + "-p", output_prefix, + "-m", str(min_length), + "-q", str(min_quality), + "-s", str(window_size), + ] + if include_mismatches: + cmd.append("-e") + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_bam)], + } + except FileNotFoundError: + raise RuntimeError("ivar command not found. Please ensure it is in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"ivar trim exited with non-zero status: {e.returncode}", + "output_files": [], + } + +@mcp.tool() +def ivar_variants( + bam_file: Path, + output_prefix: str, + reference_fasta: Path, + gff3_file: Path, + min_depth: int = 10, + min_mapq: int = 20, + min_frequency: float = 0.03, + ambiguous_char: str = 'N', + bed_file: Optional[Path] = None, +) -> dict: + """ + Calls variants (SNPs and indels) from a sorted and trimmed BAM file. + """ + # --- Input Validation --- + if not bam_file.is_file(): + raise FileNotFoundError(f"Input BAM file not found: {bam_file}") + if not reference_fasta.is_file(): + raise FileNotFoundError(f"Reference FASTA file not found: {reference_fasta}") + if not gff3_file.is_file(): + raise FileNotFoundError(f"GFF3 file not found: {gff3_file}") + if bed_file and not bed_file.is_file(): + raise FileNotFoundError(f"Optional BED file not found: {bed_file}") + if not output_prefix: + raise ValueError("Output prefix cannot be empty.") + if min_depth < 1: + raise ValueError("min_depth must be at least 1.") + if min_mapq < 0: + raise ValueError("min_mapq must be a non-negative integer.") + if not (0.0 <= min_frequency <= 1.0): + raise ValueError("min_frequency must be between 0.0 and 1.0.") + if len(ambiguous_char) != 1: + raise ValueError("ambiguous_char must be a single character.") + + output_tsv = Path(f"{output_prefix}.tsv") + output_vcf = Path(f"{output_prefix}.vcf") + + # --- Command Construction --- + cmd = [ + "ivar", "variants", + "-p", output_prefix, + "-r", str(reference_fasta), + "-g", str(gff3_file), + "-m", str(min_depth), + "-q", str(min_mapq), + "-t", str(min_frequency), + "-n", ambiguous_char, + ] + if bed_file: + cmd.extend(["-b", str(bed_file)]) + + cmd.append(str(bam_file)) # Positional argument + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_tsv), str(output_vcf)], + } + except FileNotFoundError: + raise RuntimeError("ivar command not found. Please ensure it is in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"ivar variants exited with non-zero status: {e.returncode}", + "output_files": [], + } + +@mcp.tool() +def ivar_filtervariants( + output_prefix: str, + vcf_file: Optional[Path] = None, + tsv_file: Optional[Path] = None, + bed_file: Optional[Path] = None, + min_quality: int = 20, + gatk_pass: bool = False, +) -> dict: + """ + Filters variants from a VCF file based on a TSV file from 'ivar variants'. + """ + # --- Input Validation --- + if not output_prefix: + raise ValueError("Output prefix cannot be empty.") + + actual_vcf = vcf_file if vcf_file else Path(f"{output_prefix}.vcf") + actual_tsv = tsv_file if tsv_file else Path(f"{output_prefix}.tsv") + + if not actual_vcf.is_file(): + raise FileNotFoundError(f"Input VCF file not found: {actual_vcf}") + if not actual_tsv.is_file(): + raise FileNotFoundError(f"Input TSV file not found: {actual_tsv}") + if bed_file and not bed_file.is_file(): + raise FileNotFoundError(f"Optional BED file not found: {bed_file}") + if min_quality < 0: + raise ValueError("min_quality must be a non-negative integer.") + + output_pass_vcf = Path(f"{output_prefix}.pass.vcf") + output_pass_tsv = Path(f"{output_prefix}.pass.tsv") + + # --- Command Construction --- + cmd = [ + "ivar", "filtervariants", + "-p", output_prefix, + "-q", str(min_quality), + ] + if vcf_file: + cmd.extend(["-v", str(vcf_file)]) + if tsv_file: + cmd.extend(["-t", str(tsv_file)]) + if bed_file: + cmd.extend(["-f", str(bed_file)]) + if gatk_pass: + cmd.append("-g") + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_pass_vcf), str(output_pass_tsv)], + } + except FileNotFoundError: + raise RuntimeError("ivar command not found. Please ensure it is in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"ivar filtervariants exited with non-zero status: {e.returncode}", + "output_files": [], + } + +@mcp.tool() +def ivar_consensus( + bam_file: Path, + output_prefix: str, + min_depth: int = 10, + min_frequency: float = 0.0, + min_mapq: int = 20, + ambiguous_char: str = 'N', + fasta_id: str = 'consensus', + keep_indels: bool = False, +) -> dict: + """ + Generates a consensus sequence from a sorted and trimmed BAM file. + """ + # --- Input Validation --- + if not bam_file.is_file(): + raise FileNotFoundError(f"Input BAM file not found: {bam_file}") + if not output_prefix: + raise ValueError("Output prefix cannot be empty.") + if min_depth < 1: + raise ValueError("min_depth must be at least 1.") + if not (0.0 <= min_frequency <= 1.0): + raise ValueError("min_frequency must be between 0.0 and 1.0.") + if min_mapq < 0: + raise ValueError("min_mapq must be a non-negative integer.") + if len(ambiguous_char) != 1: + raise ValueError("ambiguous_char must be a single character.") + + output_fasta = Path(f"{output_prefix}.fa") + + # --- Command Construction --- + cmd = [ + "ivar", "consensus", + "-p", output_prefix, + "-m", str(min_depth), + "-t", str(min_frequency), + "-q", str(min_mapq), + "-n", ambiguous_char, + "-i", fasta_id, + ] + if keep_indels: + cmd.append("-k") + + cmd.append(str(bam_file)) # Positional argument + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_fasta)], + } + except FileNotFoundError: + raise RuntimeError("ivar command not found. Please ensure it is in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"ivar consensus exited with non-zero status: {e.returncode}", + "output_files": [], + } + +@mcp.tool() +def ivar_getmasked( + tsv_file: Path, + bed_file: Path, + fasta_file: Path, + output_prefix: str, + min_frequency: int = 0, +) -> dict: + """ + Identifies primer sites and masks them in the consensus sequence. + """ + # --- Input Validation --- + if not tsv_file.is_file(): + raise FileNotFoundError(f"Input TSV file not found: {tsv_file}") + if not bed_file.is_file(): + raise FileNotFoundError(f"Input BED file not found: {bed_file}") + if not fasta_file.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {fasta_file}") + if not output_prefix: + raise ValueError("Output prefix cannot be empty.") + if min_frequency < 0: + raise ValueError("min_frequency must be a non-negative integer.") + + output_fasta = Path(f"{output_prefix}.masked.fa") + + # --- Command Construction --- + cmd = [ + "ivar", "getmasked", + "-i", str(tsv_file), + "-b", str(bed_file), + "-f", str(fasta_file), + "-p", output_prefix, + "-m", str(min_frequency), + ] + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_fasta)], + } + except FileNotFoundError: + raise RuntimeError("ivar command not found. Please ensure it is in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"ivar getmasked exited with non-zero status: {e.returncode}", + "output_files": [], + } + +@mcp.tool() +def ivar_removereads( + bam_file: Path, + bed_file: Path, + output_prefix: str, +) -> dict: + """ + Removes reads from a BAM file that overlap with positions in a BED file. + """ + # --- Input Validation --- + if not bam_file.is_file(): + raise FileNotFoundError(f"Input BAM file not found: {bam_file}") + if not bed_file.is_file(): + raise FileNotFoundError(f"Input BED file not found: {bed_file}") + if not output_prefix: + raise ValueError("Output prefix cannot be empty.") + + output_bam = Path(f"{output_prefix}.bam") + + # --- Command Construction --- + cmd = [ + "ivar", "removereads", + "-i", str(bam_file), + "-t", str(bed_file), + "-p", output_prefix, + ] + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_bam)], + } + except FileNotFoundError: + raise RuntimeError("ivar command not found. Please ensure it is in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"ivar removereads exited with non-zero status: {e.returncode}", + "output_files": [], + } + +@mcp.tool() +def ivar_ampliconstats( + bam_file: Path, + bed_file: Path, +) -> dict: + """ + Calculates statistics for amplicons from a BAM file. + """ + # --- Input Validation --- + if not bam_file.is_file(): + raise FileNotFoundError(f"Input BAM file not found: {bam_file}") + if not bed_file.is_file(): + raise FileNotFoundError(f"Input BED file not found: {bed_file}") + + # --- Command Construction --- + cmd = [ + "ivar", "ampliconstats", + "-b", str(bed_file), + str(bam_file), # Positional argument + ] + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], # This command outputs to stdout + } + except FileNotFoundError: + raise RuntimeError("ivar command not found. Please ensure it is in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"ivar ampliconstats exited with non-zero status: {e.returncode}", + "output_files": [], + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ivar/app/ivar_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ivar/app/ivar_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..91fbf5712f7863b6d2a5f6909fcc123e28fde253 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ivar/app/ivar_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ivar/app/ivar_server.py') +SERVER_NAME = 'biosci_ivar' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ivar/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ivar/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ivar/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ivar/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ivar/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..2c9de720f34b4d5e7d6dc8d43eca9a8dc1a38b6c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ivar/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-ivar: + build: . + image: mcp-ivar:latest + container_name: mcp-ivar + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=ivar + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ivar/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ivar/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..6d284eeb26cefed8699ad767ff567bc3470213ec --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ivar/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - ivar + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ivar/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ivar/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_ivar/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jalview/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jalview/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3a0a6e97f91d3f81dcfd55fd8092b370b84aedef --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jalview/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install jalview via conda (e.g., from bioconda) +RUN conda install -c bioconda jalview -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/jalview_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/jalview_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/jalview_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jalview/app/jalview_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jalview/app/jalview_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3314226abdb6958f09378d0bd0509ec6545404fe --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jalview/app/jalview_server.py @@ -0,0 +1,350 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, Dict, List, Literal + +# MCP decorator is assumed to be available in the execution environment. +# We define a placeholder for static analysis and clarity. +class mcp: + @staticmethod + def tool(func): + return func + +# Configure logging +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') + +def _run_jalview_command(cmd: List[str]) -> Dict: + """ + Internal helper function to execute a Jalview command and handle outputs. + """ + command_executed = " ".join(cmd) + logging.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + } + except FileNotFoundError: + error_msg = "jalview executable not found. Please ensure it is installed and in the system's PATH." + logging.error(error_msg) + raise RuntimeError(error_msg) + except subprocess.CalledProcessError as e: + logging.error(f"Jalview execution failed with return code {e.returncode}") + logging.error(f"Stdout: {e.stdout}") + logging.error(f"Stderr: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Jalview process failed.", + "return_code": e.returncode + } + +@mcp.tool +def jalview_render( + input_file: Path, + output_file: Path, + output_format: Optional[str] = None, + annotations_file: Optional[Path] = None, + features_file: Optional[Path] = None, + tree_file: Optional[Path] = None, + colour_scheme: Optional[str] = None, + show_full_id: bool = True, + show_annotations: bool = True, + show_conservation: bool = True, + show_quality: bool = True, + show_consensus: bool = True, + wrap_width: Optional[int] = None, + font_name: Optional[str] = None, + font_size: Optional[int] = None, + no_decorations: bool = False, + java_properties: Optional[Dict[str, str]] = None, +) -> Dict: + """ + Runs Jalview in headless mode to render or convert sequence alignments. + + This tool is ideal for converting alignment files into images (PNG, SVG, PDF) + or other sequence formats (FASTA, Clustal) without a graphical interface. + + Args: + input_file: Path to the input sequence alignment file (e.g., FASTA, Clustal). + output_file: Path to the desired output file. + output_format: The format for the output file (e.g., 'png', 'svg', 'pdf', 'fasta'). + If not specified, Jalview may infer it from the output file extension. + annotations_file: Path to a Jalview annotations file to apply. + features_file: Path to a Jalview features file to load. + tree_file: Path to a tree file (e.g., Newick) to associate with the alignment. + colour_scheme: Name of the colour scheme to apply (e.g., 'Clustal', 'Zappo', 'Taylor'). + show_full_id: If true, show the full sequence ID. + show_annotations: If true, show annotation rows. + show_conservation: If true, show the conservation analysis row. + show_quality: If true, show the alignment quality analysis row. + show_consensus: If true, show the consensus sequence row. + wrap_width: Wrap the alignment at the specified number of columns. + font_name: Name of the font to use for rendering. + font_size: Font size to use for rendering. + no_decorations: If true, hides window decorations in the output image. + java_properties: A dictionary of Java system properties to pass to Jalview (e.g., {"jalview.headless.bgcolor": "white"}). + + Returns: + A dictionary containing the execution command, stdout, stderr, and the output file path. + """ + # --- Input Validation --- + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if annotations_file and not annotations_file.is_file(): + raise FileNotFoundError(f"Annotations file not found: {annotations_file}") + if features_file and not features_file.is_file(): + raise FileNotFoundError(f"Features file not found: {features_file}") + if tree_file and not tree_file.is_file(): + raise FileNotFoundError(f"Tree file not found: {tree_file}") + if wrap_width is not None and wrap_width <= 0: + raise ValueError("wrap_width must be a positive integer.") + if font_size is not None and font_size <= 0: + raise ValueError("font_size must be a positive integer.") + + # Ensure output directory exists + output_file.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd = ["jalview", "-nogui"] + + if java_properties: + for key, value in java_properties.items(): + cmd.append(f"-D{key}={value}") + + cmd.extend(["-open", str(input_file)]) + cmd.extend(["-output", str(output_file)]) + + if output_format: + cmd.extend(["-format", output_format]) + if annotations_file: + cmd.extend(["-annotations", str(annotations_file)]) + if features_file: + cmd.extend(["-features", str(features_file)]) + if tree_file: + cmd.extend(["-tree", str(tree_file)]) + if colour_scheme: + cmd.extend(["-colour", colour_scheme]) + if wrap_width: + cmd.extend(["-wrap", str(wrap_width)]) + if font_name: + cmd.extend(["-font", font_name]) + if font_size: + cmd.extend(["-fontSize", str(font_size)]) + if no_decorations: + cmd.append("-nodecorations") + + # Handle boolean show/hide flags + cmd.extend(["-showFullId", str(show_full_id).lower()]) + cmd.extend(["-hideAnnotations", str(not show_annotations).lower()]) + cmd.extend(["-showConservation", str(show_conservation).lower()]) + cmd.extend(["-showQuality", str(show_quality).lower()]) + cmd.extend(["-showConsensus", str(show_consensus).lower()]) + + # --- Subprocess Execution --- + result = _run_jalview_command(cmd) + if "error" not in result: + result["output_files"] = {"image_or_alignment": str(output_file)} + + return result + +@mcp.tool +def jalview_align( + input_file: Path, + output_file: Path, + aligner: Literal['tcoffee', 'muscle', 'clustalw', 'mafft', 'probcons'], + output_format: Optional[str] = None, + java_properties: Optional[Dict[str, str]] = None, +) -> Dict: + """ + Performs multiple sequence alignment using a specified web service via Jalview. + + Args: + input_file: Path to the input file with unaligned sequences (e.g., FASTA). + output_file: Path for the resulting alignment file. + aligner: The alignment program to use. Must be one of 'tcoffee', 'muscle', 'clustalw', 'mafft', 'probcons'. + output_format: The format for the output alignment file (e.g., 'fasta', 'clustal'). + java_properties: A dictionary of Java system properties to pass to Jalview. + + Returns: + A dictionary containing the execution command, stdout, stderr, and the output file path. + """ + # --- Input Validation --- + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd = ["jalview", "-nogui"] + + if java_properties: + for key, value in java_properties.items(): + cmd.append(f"-D{key}={value}") + + cmd.extend(["-open", str(input_file)]) + # The 'default' keyword tells Jalview to use the default web service endpoint + cmd.extend([f"-{aligner}", "default"]) + cmd.extend(["-output", str(output_file)]) + + if output_format: + cmd.extend(["-format", output_format]) + + # --- Subprocess Execution --- + result = _run_jalview_command(cmd) + if "error" not in result: + result["output_files"] = {"alignment": str(output_file)} + + return result + +@mcp.tool +def jalview_predict_structure( + input_file: Path, + output_file: Path, + output_format: Optional[str] = None, + java_properties: Optional[Dict[str, str]] = None, +) -> Dict: + """ + Runs JNet secondary structure prediction on a sequence alignment. + + Args: + input_file: Path to the input sequence alignment file. + output_file: Path for the output file (e.g., an image or a project file). + output_format: The format for the output file (e.g., 'png', 'svg', 'jalview'). + java_properties: A dictionary of Java system properties to pass to Jalview. + + Returns: + A dictionary containing the execution command, stdout, stderr, and the output file path. + """ + # --- Input Validation --- + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd = ["jalview", "-nogui"] + + if java_properties: + for key, value in java_properties.items(): + cmd.append(f"-D{key}={value}") + + cmd.extend(["-open", str(input_file)]) + cmd.append("-jnet") + cmd.extend(["-output", str(output_file)]) + + if output_format: + cmd.extend(["-format", output_format]) + + # --- Subprocess Execution --- + result = _run_jalview_command(cmd) + if "error" not in result: + result["output_files"] = {"prediction_output": str(output_file)} + + return result + +@mcp.tool +def jalview_calculate_trees( + input_file: Path, + output_file: Path, + tree_type: Literal['neighbourjoining', 'averagelinkage'] = 'neighbourjoining', + output_format: Optional[str] = None, + java_properties: Optional[Dict[str, str]] = None, +) -> Dict: + """ + Calculates a phylogenetic tree from a sequence alignment. + + Args: + input_file: Path to the input sequence alignment file. + output_file: Path for the output file (e.g., a Newick tree file or an image). + tree_type: The tree calculation method. Defaults to 'neighbourjoining'. + output_format: The format for the output file (e.g., 'newick', 'png', 'svg'). + java_properties: A dictionary of Java system properties to pass to Jalview. + + Returns: + A dictionary containing the execution command, stdout, stderr, and the output file path. + """ + # --- Input Validation --- + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd = ["jalview", "-nogui"] + + if java_properties: + for key, value in java_properties.items(): + cmd.append(f"-D{key}={value}") + + cmd.extend(["-open", str(input_file)]) + cmd.extend(["-trees", tree_type]) + cmd.extend(["-output", str(output_file)]) + + if output_format: + cmd.extend(["-format", output_format]) + + # --- Subprocess Execution --- + result = _run_jalview_command(cmd) + if "error" not in result: + result["output_files"] = {"tree_output": str(output_file)} + + return result + +@mcp.tool +def jalview_analyze( + input_file: Path, + output_file: Path, + analysis_type: Literal['pca', 'varsc'], + output_format: Optional[str] = None, + java_properties: Optional[Dict[str, str]] = None, +) -> Dict: + """ + Performs analysis such as PCA or sequence variant analysis on an alignment. + + Args: + input_file: Path to the input sequence alignment file. + output_file: Path for the output file (e.g., an image of the PCA plot). + analysis_type: The type of analysis to perform ('pca' or 'varsc'). + output_format: The format for the output file (e.g., 'png', 'svg'). + java_properties: A dictionary of Java system properties to pass to Jalview. + + Returns: + A dictionary containing the execution command, stdout, stderr, and the output file path. + """ + # --- Input Validation --- + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd = ["jalview", "-nogui"] + + if java_properties: + for key, value in java_properties.items(): + cmd.append(f"-D{key}={value}") + + cmd.extend(["-open", str(input_file)]) + cmd.append(f"-{analysis_type}") + cmd.extend(["-output", str(output_file)]) + + if output_format: + cmd.extend(["-format", output_format]) + + # --- Subprocess Execution --- + result = _run_jalview_command(cmd) + if "error" not in result: + result["output_files"] = {"analysis_output": str(output_file)} + + return result \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jalview/app/jalview_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jalview/app/jalview_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9f1503b7d9189fc1cb28ac98822b35ea9e2c21bb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jalview/app/jalview_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jalview/app/jalview_server.py') +SERVER_NAME = 'biosci_jalview' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jalview/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jalview/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jalview/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jalview/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jalview/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..52f0de4ba52b657e5dd7775a7d0ce7a88d1a5fd5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jalview/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-jalview: + build: . + image: mcp-jalview:latest + container_name: mcp-jalview + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=jalview + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jalview/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jalview/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..861be25c11bbfcdc0218188cec843b18493bf3dc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jalview/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - jalview + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jalview/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jalview/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jalview/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_java-jdk/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_java-jdk/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c0060c346e4817572532973e52ef1b76763cc483 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_java-jdk/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install java-jdk via conda (e.g., from bioconda) +RUN conda install -c bioconda java-jdk -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/java-jdk_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/java-jdk_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/java-jdk_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_java-jdk/app/java-jdk_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_java-jdk/app/java-jdk_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5c8acb0b2e626b7d58e048ce952437a667b1cc04 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_java-jdk/app/java-jdk_server.py @@ -0,0 +1,260 @@ +import subprocess +import shlex +from pathlib import Path +from typing import Optional, List, Dict, Literal + +# MCP-compliant tool definitions for the java-jdk tool + +@mcp.tool() +def java_execute_jar( + jar_file: Path, + args: Optional[List[str]] = None, + use_32bit_datamodel: bool = False, + use_64bit_datamodel: bool = False, + select_server_vm: bool = False, + class_path: Optional[List[Path]] = None, + system_properties: Optional[Dict[str, str]] = None, + verbose_output: Optional[Literal["class", "gc", "jni"]] = None, + show_version_and_continue: bool = False, + require_version: Optional[str] = None, + jre_restrict_search: Optional[bool] = None, + enable_assertions: Optional[str] = None, + disable_assertions: Optional[str] = None, + enable_system_assertions: bool = False, + disable_system_assertions: bool = False, + agent_library: Optional[str] = None, + agent_path: Optional[str] = None, + java_agent: Optional[str] = None, + splash_screen_image: Optional[Path] = None, +): + """ + Executes a Java application packaged as a JAR file. + + This corresponds to the `java -jar jarfile [args...]` command. + + Args: + jar_file: Path to the executable JAR file. + args: A list of arguments to pass to the Java application's main method. + use_32bit_datamodel: Use a 32-bit data model if available (-d32). + use_64bit_datamodel: Use a 64-bit data model if available (-d64). + select_server_vm: Select the "server" VM (-server). + class_path: A list of directories, JAR archives, and ZIP archives to search for class files (-cp, -classpath). + system_properties: A dictionary of system properties to set (-D=). + verbose_output: Enable verbose output for 'class', 'gc', or 'jni'. + show_version_and_continue: Print product version and continue execution (-showversion). + require_version: Require a specific Java version to run (-version:). Deprecated. + jre_restrict_search: If True, include user private JREs in version search (-jre-restrict-search). If False, exclude them (-no-jre-restrict-search). Deprecated. + enable_assertions: Enable assertions. Provide an empty string for `-ea` or a string like `:` for granularity. + disable_assertions: Disable assertions. Provide an empty string for `-da` or a string like `:` for granularity. + enable_system_assertions: Enable system assertions (-esa). + disable_system_assertions: Disable system assertions (-dsa). + agent_library: Load a native agent library by name, e.g., 'hprof' or 'jdwp=help' (-agentlib:[=]). + agent_path: Load a native agent library by full pathname (-agentpath:[=]). + java_agent: Load a Java programming language agent (-javaagent:[=]). + splash_screen_image: Show a splash screen with the specified image (-splash:). + """ + # Input validation + if not jar_file.is_file(): + raise FileNotFoundError(f"JAR file not found: {jar_file}") + if use_32bit_datamodel and use_64bit_datamodel: + raise ValueError("Cannot specify both -d32 and -d64 options.") + if splash_screen_image and not splash_screen_image.is_file(): + raise FileNotFoundError(f"Splash screen image not found: {splash_screen_image}") + if class_path: + for p in class_path: + if not p.exists(): + raise FileNotFoundError(f"Classpath entry not found: {p}") + + cmd = ["java"] + + # Options + if use_32bit_datamodel: cmd.append("-d32") + if use_64bit_datamodel: cmd.append("-d64") + if select_server_vm: cmd.append("-server") + if class_path: cmd.extend(["-cp", ":".join(map(str, class_path))]) + if system_properties: + for key, value in system_properties.items(): + cmd.append(f"-D{key}={value}") + if verbose_output: cmd.append(f"-verbose:{verbose_output}") + if show_version_and_continue: cmd.append("-showversion") + if require_version: cmd.append(f"-version:{require_version}") + if jre_restrict_search is not None: + cmd.append("-jre-restrict-search" if jre_restrict_search else "-no-jre-restrict-search") + if enable_assertions is not None: cmd.append(f"-ea{enable_assertions}") + if disable_assertions is not None: cmd.append(f"-da{disable_assertions}") + if enable_system_assertions: cmd.append("-esa") + if disable_system_assertions: cmd.append("-dsa") + if agent_library: cmd.append(f"-agentlib:{agent_library}") + if agent_path: cmd.append(f"-agentpath:{agent_path}") + if java_agent: cmd.append(f"-javaagent:{java_agent}") + if splash_screen_image: cmd.append(f"-splash:{str(splash_screen_image)}") + + # Main execution command + cmd.extend(["-jar", str(jar_file)]) + + # Application arguments + if args: cmd.extend(args) + + command_executed = shlex.join(cmd) + + try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Java execution failed", + "return_code": e.returncode + } + +@mcp.tool() +def java_execute_class( + class_name: str, + class_path: List[Path], + args: Optional[List[str]] = None, + use_32bit_datamodel: bool = False, + use_64bit_datamodel: bool = False, + select_server_vm: bool = False, + system_properties: Optional[Dict[str, str]] = None, + verbose_output: Optional[Literal["class", "gc", "jni"]] = None, + show_version_and_continue: bool = False, + require_version: Optional[str] = None, + jre_restrict_search: Optional[bool] = None, + enable_assertions: Optional[str] = None, + disable_assertions: Optional[str] = None, + enable_system_assertions: bool = False, + disable_system_assertions: bool = False, + agent_library: Optional[str] = None, + agent_path: Optional[str] = None, + java_agent: Optional[str] = None, + splash_screen_image: Optional[Path] = None, +): + """ + Executes a Java class file. + + This corresponds to the `java [options] class [args...]` command. + + Args: + class_name: The fully qualified name of the class to execute. + class_path: A list of directories, JAR archives, and ZIP archives to search for class files (-cp, -classpath). This is required. + args: A list of arguments to pass to the Java application's main method. + use_32bit_datamodel: Use a 32-bit data model if available (-d32). + use_64bit_datamodel: Use a 64-bit data model if available (-d64). + select_server_vm: Select the "server" VM (-server). + system_properties: A dictionary of system properties to set (-D=). + verbose_output: Enable verbose output for 'class', 'gc', or 'jni'. + show_version_and_continue: Print product version and continue execution (-showversion). + require_version: Require a specific Java version to run (-version:). Deprecated. + jre_restrict_search: If True, include user private JREs in version search (-jre-restrict-search). If False, exclude them (-no-jre-restrict-search). Deprecated. + enable_assertions: Enable assertions. Provide an empty string for `-ea` or a string like `:` for granularity. + disable_assertions: Disable assertions. Provide an empty string for `-da` or a string like `:` for granularity. + enable_system_assertions: Enable system assertions (-esa). + disable_system_assertions: Disable system assertions (-dsa). + agent_library: Load a native agent library by name, e.g., 'hprof' or 'jdwp=help' (-agentlib:[=]). + agent_path: Load a native agent library by full pathname (-agentpath:[=]). + java_agent: Load a Java programming language agent (-javaagent:[=]). + splash_screen_image: Show a splash screen with the specified image (-splash:). + """ + # Input validation + if not class_path: + raise ValueError("A non-empty class_path must be provided to execute a class.") + for p in class_path: + if not p.exists(): + raise FileNotFoundError(f"Classpath entry not found: {p}") + if use_32bit_datamodel and use_64bit_datamodel: + raise ValueError("Cannot specify both -d32 and -d64 options.") + if splash_screen_image and not splash_screen_image.is_file(): + raise FileNotFoundError(f"Splash screen image not found: {splash_screen_image}") + + cmd = ["java"] + + # Options + if use_32bit_datamodel: cmd.append("-d32") + if use_64bit_datamodel: cmd.append("-d64") + if select_server_vm: cmd.append("-server") + if system_properties: + for key, value in system_properties.items(): + cmd.append(f"-D{key}={value}") + if verbose_output: cmd.append(f"-verbose:{verbose_output}") + if show_version_and_continue: cmd.append("-showversion") + if require_version: cmd.append(f"-version:{require_version}") + if jre_restrict_search is not None: + cmd.append("-jre-restrict-search" if jre_restrict_search else "-no-jre-restrict-search") + if enable_assertions is not None: cmd.append(f"-ea{enable_assertions}") + if disable_assertions is not None: cmd.append(f"-da{disable_assertions}") + if enable_system_assertions: cmd.append("-esa") + if disable_system_assertions: cmd.append("-dsa") + if agent_library: cmd.append(f"-agentlib:{agent_library}") + if agent_path: cmd.append(f"-agentpath:{agent_path}") + if java_agent: cmd.append(f"-javaagent:{java_agent}") + if splash_screen_image: cmd.append(f"-splash:{str(splash_screen_image)}") + + # Classpath is required for this mode + cmd.extend(["-classpath", ":".join(map(str, class_path))]) + + # Main execution command + cmd.append(class_name) + + # Application arguments + if args: cmd.extend(args) + + command_executed = shlex.join(cmd) + + try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Java execution failed", + "return_code": e.returncode + } + +@mcp.tool() +def java_show_info( + version: bool = False, + non_standard_options_help: bool = False +): + """ + Shows Java version information or help for non-standard options. + + Args: + version: If True, print the product version and exit (`java -version`). + non_standard_options_help: If True, print help on non-standard options (`java -X`). + """ + if not (version ^ non_standard_options_help): + raise ValueError("Exactly one of 'version' or 'non_standard_options_help' must be True.") + + cmd = ["java"] + if version: + cmd.append("-version") + else: # non_standard_options_help is True + cmd.append("-X") + + command_executed = shlex.join(cmd) + try: + # Note: `java -version` often prints to stderr, and `java -X` can have a non-zero exit code + # on some versions while still printing help. We don't use check=True here. + result = subprocess.run(cmd, capture_output=True, text=True) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "return_code": result.returncode + } + except FileNotFoundError: + raise RuntimeError("Java executable not found. Please ensure it is in your PATH.") \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_java-jdk/app/java-jdk_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_java-jdk/app/java-jdk_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0ee17b23b1b83c5cd5b181687e066d54271b1d62 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_java-jdk/app/java-jdk_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_java-jdk/app/java-jdk_server.py') +SERVER_NAME = 'biosci_java_jdk' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_java-jdk/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_java-jdk/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_java-jdk/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_java-jdk/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_java-jdk/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..cc8a826c3123b37e12dfbdadac00a5fddbeee745 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_java-jdk/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-java-jdk: + build: . + image: mcp-java-jdk:latest + container_name: mcp-java-jdk + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=java-jdk + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_java-jdk/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_java-jdk/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4b0dd85c23da221fca5aed00095b2724c58934ad --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_java-jdk/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - java-jdk + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_java-jdk/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_java-jdk/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_java-jdk/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jbrowse2/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jbrowse2/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..7a3826bf0adfcca3c8625066a29f80a16e150c0c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jbrowse2/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install jbrowse2 via conda (e.g., from bioconda) +RUN conda install -c bioconda jbrowse2 -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/jbrowse2_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/jbrowse2_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/jbrowse2_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jbrowse2/app/jbrowse2_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jbrowse2/app/jbrowse2_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9da668771368fb4b802fd6a9fba924a9c2a661ea --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jbrowse2/app/jbrowse2_server.py @@ -0,0 +1,729 @@ +import subprocess +import json +from pathlib import Path +from typing import Optional, List, Dict + +# NOTE: @mcp.tool is a placeholder for the actual decorator. +# The execution environment is expected to provide the 'mcp' object. + +@mcp.tool() +def jbrowse_create( + local_path: Path, + force: bool = False, + tag: str = "latest", +) -> Dict: + """ + Creates a new JBrowse 2 instance. + + Args: + local_path: Path to the directory to create the JBrowse 2 instance in. + force: Overwrite existing files in the destination directory. + tag: The version of JBrowse 2 to install (e.g., '1.0.0', 'latest'). + + Returns: + A dictionary containing the command executed, stdout, stderr, and output directory. + """ + command = ["jbrowse", "create", str(local_path)] + + if force: + command.append("--force") + if tag: + command.extend(["--tag", tag]) + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {"jbrowse_instance": str(local_path)} + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"JBrowse 2 create failed with exit code {e.returncode}", + "output_files": {} + } + +@mcp.tool() +def jbrowse_add_assembly( + fasta: Path, + assembly_type: str = "indexedFasta", + name: Optional[str] = None, + alias: Optional[List[str]] = None, + fai_location: Optional[Path] = None, + gzi_location: Optional[Path] = None, + two_bit_location: Optional[Path] = None, + chrom_sizes_location: Optional[Path] = None, + ref_name_aliases: Optional[Path] = None, + target: Optional[Path] = None, + skip_check: bool = False, + overwrite: bool = False, + load: str = "inPlace", +) -> Dict: + """ + Adds an assembly to the JBrowse 2 configuration. + + Args: + fasta: Path to the FASTA file for the assembly. + assembly_type: The type of assembly. + name: Name of the assembly. + alias: Alternative names for the assembly. + fai_location: Path to the FASTA index file (.fai). + gzi_location: Path to the bgzip index file (.gzi). + two_bit_location: Path to a 2bit file for the assembly. + chrom_sizes_location: Path to a chrom.sizes file for the assembly. + ref_name_aliases: Path to a file containing reference name aliases. + target: Path to the JBrowse 2 configuration file or directory. + skip_check: Skip checking for the existence of the FASTA file. + overwrite: Overwrite any existing assembly with the same name. + load: Method for loading the assembly data ('copy', 'symlink', 'move', 'inPlace'). + + Returns: + A dictionary containing the command executed, stdout, and stderr. + """ + if not skip_check and not fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {fasta}") + + load_choices = ['copy', 'symlink', 'move', 'inPlace'] + if load not in load_choices: + raise ValueError(f"Invalid load option '{load}'. Must be one of {load_choices}") + + assembly_type_choices = ['indexedFasta', 'bgzipFasta', 'twoBit', 'chromSizes', 'custom'] + if assembly_type not in assembly_type_choices: + raise ValueError(f"Invalid assembly_type '{assembly_type}'. Must be one of {assembly_type_choices}") + + command = ["jbrowse", "add-assembly", str(fasta)] + command.extend(["--type", assembly_type]) + command.extend(["--load", load]) + + if name: + command.extend(["--name", name]) + if alias: + command.extend(["--alias", ",".join(alias)]) + if fai_location: + if not fai_location.is_file(): raise FileNotFoundError(f"FASTA index not found: {fai_location}") + command.extend(["--faiLocation", str(fai_location)]) + if gzi_location: + if not gzi_location.is_file(): raise FileNotFoundError(f"GZIP index not found: {gzi_location}") + command.extend(["--gziLocation", str(gzi_location)]) + if two_bit_location: + if not two_bit_location.is_file(): raise FileNotFoundError(f"2bit file not found: {two_bit_location}") + command.extend(["--twoBitLocation", str(two_bit_location)]) + if chrom_sizes_location: + if not chrom_sizes_location.is_file(): raise FileNotFoundError(f"chrom.sizes file not found: {chrom_sizes_location}") + command.extend(["--chromSizesLocation", str(chrom_sizes_location)]) + if ref_name_aliases: + if not ref_name_aliases.is_file(): raise FileNotFoundError(f"Ref name aliases file not found: {ref_name_aliases}") + command.extend(["--refNameAliases", str(ref_name_aliases)]) + if target: + command.extend(["--target", str(target)]) + if skip_check: + command.append("--skipCheck") + if overwrite: + command.append("--overwrite") + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {} + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"JBrowse 2 add-assembly failed with exit code {e.returncode}", + "output_files": {} + } + +@mcp.tool() +def jbrowse_add_track( + track_file: Path, + track_id: Optional[str] = None, + name: Optional[str] = None, + description: Optional[str] = None, + assembly_names: Optional[List[str]] = None, + track_type: Optional[str] = None, + category: Optional[str] = None, + config: Optional[Dict] = None, + target: Optional[Path] = None, + sub_dir: Optional[str] = None, + skip_check: bool = False, + overwrite: bool = False, + load: str = "inPlace", + index_file: Optional[Path] = None, +) -> Dict: + """ + Adds a track to the JBrowse 2 configuration. + + Args: + track_file: Path to the track data file (e.g., BAM, CRAM, VCF, GFF). + track_id: A unique identifier for the track. + name: The name of the track. + description: A description for the track. + assembly_names: Comma-separated list of assembly names to associate with the track. + track_type: The type of track to add. + category: The category for the track. + config: JSON string of configuration options for the track. + target: Path to the JBrowse 2 configuration file or directory. + sub_dir: Subdirectory within the JBrowse 2 data directory to place files. + skip_check: Skip checking for the existence of the track file. + overwrite: Overwrite any existing track with the same ID. + load: Method for loading the track data ('copy', 'symlink', 'move', 'inPlace'). + index_file: Path to an index file for the track data. + + Returns: + A dictionary containing the command executed, stdout, and stderr. + """ + if not skip_check and not track_file.is_file(): + raise FileNotFoundError(f"Input track file not found: {track_file}") + + load_choices = ['copy', 'symlink', 'move', 'inPlace'] + if load not in load_choices: + raise ValueError(f"Invalid load option '{load}'. Must be one of {load_choices}") + + command = ["jbrowse", "add-track", str(track_file)] + command.extend(["--load", load]) + + if track_id: + command.extend(["--trackId", track_id]) + if name: + command.extend(["--name", name]) + if description: + command.extend(["--description", description]) + if assembly_names: + command.extend(["--assemblyNames", ",".join(assembly_names)]) + if track_type: + command.extend(["--type", track_type]) + if category: + command.extend(["--category", category]) + if config: + command.extend(["--config", json.dumps(config)]) + if target: + command.extend(["--target", str(target)]) + if sub_dir: + command.extend(["--subDir", sub_dir]) + if skip_check: + command.append("--skipCheck") + if overwrite: + command.append("--overwrite") + if index_file: + if not index_file.is_file(): raise FileNotFoundError(f"Index file not found: {index_file}") + command.extend(["--indexFile", str(index_file)]) + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {} + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"JBrowse 2 add-track failed with exit code {e.returncode}", + "output_files": {} + } + +@mcp.tool() +def jbrowse_add_connection( + connection_url: str, + connection_id: Optional[str] = None, + connection_type: Optional[str] = None, + assembly_name: Optional[str] = None, + name: Optional[str] = None, + config: Optional[Dict] = None, + target: Optional[Path] = None, + skip_check: bool = False, + overwrite: bool = False, +) -> Dict: + """ + Adds a connection to a remote resource, like a track hub. + + Args: + connection_url: URL of the connection. + connection_id: A unique identifier for the connection. + connection_type: The type of connection (e.g., 'JBrowse1Connection'). + assembly_name: The assembly to associate the connection with. + name: The name of the connection. + config: JSON string of configuration options. + target: Path to the JBrowse 2 configuration file or directory. + skip_check: Skip checking for the existence of the connection. + overwrite: Overwrite any existing connection with the same ID. + + Returns: + A dictionary containing the command executed, stdout, and stderr. + """ + command = ["jbrowse", "add-connection", connection_url] + + if connection_id: + command.extend(["--connectionId", connection_id]) + if connection_type: + command.extend(["--type", connection_type]) + if assembly_name: + command.extend(["--assemblyName", assembly_name]) + if name: + command.extend(["--name", name]) + if config: + command.extend(["--config", json.dumps(config)]) + if target: + command.extend(["--target", str(target)]) + if skip_check: + command.append("--skipCheck") + if overwrite: + command.append("--overwrite") + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {} + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"JBrowse 2 add-connection failed with exit code {e.returncode}", + "output_files": {} + } + +@mcp.tool() +def jbrowse_add_track_json( + track_json: Path, + target: Optional[Path] = None, + update: bool = False, +) -> Dict: + """ + Adds a track configuration directly from a JSON file. + + Args: + track_json: Path to the track JSON file. + target: Path to the JBrowse 2 configuration file or directory. + update: Update an existing track if it has the same trackId. + + Returns: + A dictionary containing the command executed, stdout, and stderr. + """ + if not track_json.is_file(): + raise FileNotFoundError(f"Input JSON file not found: {track_json}") + + command = ["jbrowse", "add-track-json", str(track_json)] + + if target: + command.extend(["--target", str(target)]) + if update: + command.append("--update") + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {} + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"JBrowse 2 add-track-json failed with exit code {e.returncode}", + "output_files": {} + } + +@mcp.tool() +def jbrowse_text_index( + tracks: Optional[List[str]] = None, + assemblies: Optional[List[str]] = None, + individual: bool = False, + attributes: List[str] = ["Name", "ID"], + exclude: Optional[List[str]] = None, + target: Optional[Path] = None, + force: bool = False, + quiet: bool = False, +) -> Dict: + """ + Creates a text index for searching features in JBrowse 2. + + Args: + tracks: A list of track IDs to index. + assemblies: A list of assembly names to index tracks from. + individual: Index tracks individually rather than aggregating. + attributes: A list of feature attributes to index. + exclude: A list of attributes to exclude from indexing. + target: Path to the JBrowse 2 configuration file or directory. + force: Force re-indexing of all tracks. + quiet: Hide the progress bar. + + Returns: + A dictionary containing the command executed, stdout, and stderr. + """ + command = ["jbrowse", "text-index"] + + if tracks: + command.extend(["--tracks", ",".join(tracks)]) + if assemblies: + command.extend(["--assemblies", ",".join(assemblies)]) + if individual: + command.append("--individual") + if attributes: + command.extend(["--attributes", ",".join(attributes)]) + if exclude: + command.extend(["--exclude", ",".join(exclude)]) + if target: + command.extend(["--target", str(target)]) + if force: + command.append("--force") + if quiet: + command.append("--quiet") + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {} + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"JBrowse 2 text-index failed with exit code {e.returncode}", + "output_files": {} + } + +@mcp.tool() +def jbrowse_set_default_session( + session: Optional[Dict] = None, + view: Optional[str] = None, + tracks: Optional[List[str]] = None, + name: str = "Default Session", + target: Optional[Path] = None, +) -> Dict: + """ + Sets the default session for a JBrowse 2 instance. + + Args: + session: A dictionary representing the session to set as default. + view: The view type to set as default (e.g., 'LinearGenomeView'). + tracks: A list of track IDs to open in the default session. + name: The name for the default session. + target: Path to the JBrowse 2 configuration file or directory. + + Returns: + A dictionary containing the command executed, stdout, and stderr. + """ + command = ["jbrowse", "set-default-session"] + command.extend(["--name", name]) + + if session: + command.extend(["--session", json.dumps(session)]) + if view: + command.extend(["--view", view]) + if tracks: + command.extend(["--tracks", ",".join(tracks)]) + if target: + command.extend(["--target", str(target)]) + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {} + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"JBrowse 2 set-default-session failed with exit code {e.returncode}", + "output_files": {} + } + +@mcp.tool() +def jbrowse_upgrade( + local_path: Optional[Path] = None, + tag: str = "latest", + list_versions: bool = False, +) -> Dict: + """ + Upgrades a JBrowse 2 instance to the latest or a specified version. + + Args: + local_path: Path to the JBrowse 2 instance to upgrade. Defaults to current dir. + tag: The version of JBrowse 2 to upgrade to. + list_versions: List available versions of JBrowse 2 instead of upgrading. + + Returns: + A dictionary containing the command executed, stdout, and stderr. + """ + command = ["jbrowse", "upgrade"] + + if local_path: + command.append(str(local_path)) + if tag: + command.extend(["--tag", tag]) + if list_versions: + command.append("--list") + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {} + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"JBrowse 2 upgrade failed with exit code {e.returncode}", + "output_files": {} + } + +@mcp.tool() +def jbrowse_sort_gff( + input_gff: Path, + output_gff: Path, +) -> Dict: + """ + Sorts a GFF3 file. This is a simple wrapper around a gff3sort script. + + Args: + input_gff: The input GFF3 file to sort. + output_gff: The path for the sorted output GFF3 file. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output file path. + """ + if not input_gff.is_file(): + raise FileNotFoundError(f"Input GFF file not found: {input_gff}") + + command = ["jbrowse", "sort-gff", str(input_gff), "--out", str(output_gff)] + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {"sorted_gff": str(output_gff)} + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"JBrowse 2 sort-gff failed with exit code {e.returncode}", + "output_files": {} + } + +@mcp.tool() +def jbrowse_make_paf( + input_maf: Path, + output_paf: Path, +) -> Dict: + """ + Converts a MAF (Multiple Alignment Format) file to a PAF (Pairwise mApping Format) file. + + Args: + input_maf: The input MAF file. + output_paf: The path for the output PAF file. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output file path. + """ + if not input_maf.is_file(): + raise FileNotFoundError(f"Input MAF file not found: {input_maf}") + + command = ["jbrowse", "make-paf", str(input_maf), "--out", str(output_paf)] + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {"output_paf": str(output_paf)} + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"JBrowse 2 make-paf failed with exit code {e.returncode}", + "output_files": {} + } + +@mcp.tool() +def jbrowse_admin_server( + port: int = 8999, + body_size_limit: str = "100mb", + root: Optional[Path] = None, +) -> Dict: + """ + Starts a small admin server for JBrowse 2 configuration. + Note: This is a long-running process. Execution may need to be managed (e.g., with a timeout). + + Args: + port: The port to run the server on. + body_size_limit: Maximum body size for requests (e.g., '10mb', '1gb'). + root: Path to the JBrowse 2 installation directory. + + Returns: + A dictionary containing the command executed, stdout, and stderr. + """ + command = ["jbrowse", "admin-server"] + command.extend(["--port", str(port)]) + command.extend(["--body_size_limit", body_size_limit]) + + if root: + if not root.is_dir(): raise NotADirectoryError(f"Root path is not a directory: {root}") + command.extend(["--root", str(root)]) + + try: + # This command starts a server, so it might not exit. + # A timeout might be appropriate in a real-world scenario. + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + timeout=30 # Example timeout + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {} + } + except subprocess.TimeoutExpired as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout.decode() if e.stdout else "", + "stderr": e.stderr.decode() if e.stderr else "", + "error": "JBrowse 2 admin-server started but timed out.", + "output_files": {} + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"JBrowse 2 admin-server failed with exit code {e.returncode}", + "output_files": {} + } + +@mcp.tool() +def jbrowse_set_up( + tag: str = "latest", + force: bool = False, + out_dir: Path = Path("jbrowse"), +) -> Dict: + """ + Downloads and installs the latest JBrowse Web code. + + Args: + tag: The version of JBrowse 2 to install. + force: Overwrite existing files. + out_dir: Path to install JBrowse 2 in. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output directory. + """ + command = ["jbrowse", "set-up"] + command.extend(["--tag", tag]) + command.extend(["--out", str(out_dir)]) + + if force: + command.append("--force") + + try: + process = subprocess.run( + command, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": {"jbrowse_web_dir": str(out_dir)} + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"JBrowse 2 set-up failed with exit code {e.returncode}", + "output_files": {} + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jbrowse2/app/jbrowse2_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jbrowse2/app/jbrowse2_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4c2af9bc27476af0d4e18e88381d106c88d0cb0c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jbrowse2/app/jbrowse2_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jbrowse2/app/jbrowse2_server.py') +SERVER_NAME = 'biosci_jbrowse2' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jbrowse2/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jbrowse2/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jbrowse2/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jbrowse2/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jbrowse2/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..601600b1816ff2d0f15e5faa4188bc9a6d3753be --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jbrowse2/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-jbrowse2: + build: . + image: mcp-jbrowse2:latest + container_name: mcp-jbrowse2 + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=jbrowse2 + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jbrowse2/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jbrowse2/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f0dae3d588d40473568d88c2624f6ee9e0d5b97b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jbrowse2/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - jbrowse2 + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jbrowse2/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jbrowse2/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jbrowse2/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jcvi/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jcvi/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5cdf3e9e231da1c3b813bc122b6156c45fbe7283 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jcvi/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install jcvi via conda (e.g., from bioconda) +RUN conda install -c bioconda jcvi -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/jcvi_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/jcvi_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/jcvi_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jcvi/app/jcvi_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jcvi/app/jcvi_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b085b7c86c725ad5523220a8440cd72ea7f896b1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jcvi/app/jcvi_server.py @@ -0,0 +1,476 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Literal, Optional +import logging +import shlex + +# Setup basic logging +logging.basicConfig(level=logging.INFO) + +# MCP decorator is assumed to be provided by the execution environment. +# This is a placeholder for development and linting. +class mcp: + """Placeholder for the MCP decorator.""" + def tool(func): + return func + +# Helper function to run commands and handle outputs +def _run_command(cmd: List[str], output_path: Optional[Path] = None): + """Executes a command, captures output, and handles errors.""" + command_str = shlex.join(cmd) + logging.info(f"Executing command: {command_str}") + + try: + if output_path: + with open(output_path, "w") as f: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + stdout=f + ) + # Read back a snippet of stdout for the return dict if needed + stdout_capture = f"Output written to {output_path}" + else: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True + ) + stdout_capture = result.stdout + + return { + "command_executed": command_str, + "stdout": stdout_capture, + "stderr": result.stderr, + "output_files": [str(output_path)] if output_path else [] + } + except FileNotFoundError: + raise RuntimeError(f"Command '{cmd[0]}' not found. Ensure 'python' is in the system's PATH.") + except subprocess.CalledProcessError as e: + logging.error(f"Command failed with exit code {e.returncode}") + logging.error(f"Stderr: {e.stderr}") + logging.error(f"Stdout: {e.stdout}") + raise e + + +@mcp.tool +def jcvi_formats_fasta_clean( + input_fasta: Path, + output_fasta: Path +): + """Removes irregular characters in FASTA sequences.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "clean", str(input_fasta)] + return _run_command(cmd, output_path=output_fasta) + +@mcp.tool +def jcvi_formats_fasta_diff( + fasta1: Path, + fasta2: Path +): + """Checks if two FASTA files contain the same record information.""" + if not fasta1.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {fasta1}") + if not fasta2.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {fasta2}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "diff", str(fasta1), str(fasta2)] + return _run_command(cmd) + +@mcp.tool +def jcvi_formats_fasta_extract( + fasta_file: Path, + ids_file: Path, + output_fasta: Path +): + """Given a FASTA file and a file with sequence IDs, retrieves the sequences.""" + if not fasta_file.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {fasta_file}") + if not ids_file.is_file(): + raise FileNotFoundError(f"IDs file not found: {ids_file}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "extract", str(fasta_file), str(ids_file)] + return _run_command(cmd, output_path=output_fasta) + +@mcp.tool +def jcvi_formats_fasta_fastq( + fasta_file: Path, + qual_file: Path, + output_fastq: Path +): + """Combines FASTA and QUAL files to create a FASTQ file.""" + if not fasta_file.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {fasta_file}") + if not qual_file.is_file(): + raise FileNotFoundError(f"Input QUAL file not found: {qual_file}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "fastq", str(fasta_file), str(qual_file)] + return _run_command(cmd, output_path=output_fastq) + +@mcp.tool +def jcvi_formats_fasta_filter( + fasta_file: Path, + output_fasta: Path, + min_size: int = 0, + max_size: int = 0 +): + """Filters FASTA records by sequence size.""" + if not fasta_file.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {fasta_file}") + if min_size < 0: + raise ValueError("min_size must be non-negative.") + if max_size < 0: + raise ValueError("max_size must be non-negative.") + + cmd = ["python", "-m", "jcvi.formats.fasta", "filter", f"--min_size={min_size}", f"--max_size={max_size}", str(fasta_file)] + return _run_command(cmd, output_path=output_fasta) + +@mcp.tool +def jcvi_formats_fasta_format( + input_fasta: Path, + output_fasta: Path, + mapping_file: Optional[Path] = None +): + """Trims accession ID to the first space or switches ID based on a mapping file.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "format", str(input_fasta)] + if mapping_file: + if not mapping_file.is_file(): + raise FileNotFoundError(f"Mapping file not found: {mapping_file}") + cmd.append(str(mapping_file)) + + return _run_command(cmd, output_path=output_fasta) + +@mcp.tool +def jcvi_formats_fasta_fromtab( + tab_file: Path, + output_fasta: Path +): + """Converts a 2-column (ID, sequence) tab-separated file to FASTA format.""" + if not tab_file.is_file(): + raise FileNotFoundError(f"Input tab file not found: {tab_file}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "fromtab", str(tab_file)] + return _run_command(cmd, output_path=output_fasta) + +@mcp.tool +def jcvi_formats_fasta_gaps( + input_fasta: Path, + output_report: Path +): + """Prints out a list of gap sizes within sequences.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "gaps", str(input_fasta)] + return _run_command(cmd, output_path=output_report) + +@mcp.tool +def jcvi_formats_fasta_gc( + input_fasta: Path, + output_plot: Path +): + """Plots G+C content distribution. Assumes output is an image or data file.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + + # The tool might generate a specific filename, e.g., input_fasta.gc.pdf + # We will run it and then move the expected output to the desired location. + # For simplicity here, we assume it writes to stdout or can be directed. + cmd = ["python", "-m", "jcvi.formats.fasta", "gc", str(input_fasta), f"--outfile={output_plot}"] + return _run_command(cmd, output_path=None) # Command handles output file + +@mcp.tool +def jcvi_formats_fasta_identical( + fasta1: Path, + fasta2: Path +): + """Given 2 FASTA files, finds all exactly identical records.""" + if not fasta1.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {fasta1}") + if not fasta2.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {fasta2}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "identical", str(fasta1), str(fasta2)] + return _run_command(cmd) + +@mcp.tool +def jcvi_formats_fasta_ids( + input_fasta: Path, + output_ids: Path +): + """Generates a list of headers from a FASTA file.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "ids", str(input_fasta)] + return _run_command(cmd, output_path=output_ids) + +@mcp.tool +def jcvi_formats_fasta_info( + input_fasta: Path +): + """Runs `sequence_info` on FASTA files and prints a report.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "info", str(input_fasta)] + return _run_command(cmd) + +@mcp.tool +def jcvi_formats_fasta_ispcr( + primers_file: Path, + output_query: Path +): + """Reformats paired primers into isPcr query format.""" + if not primers_file.is_file(): + raise FileNotFoundError(f"Primers file not found: {primers_file}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "ispcr", str(primers_file)] + return _run_command(cmd, output_path=output_query) + +@mcp.tool +def jcvi_formats_fasta_join( + input_fastas: List[Path], + output_fasta: Path +): + """Concatenates a list of sequences and adds gaps in between.""" + cmd = ["python", "-m", "jcvi.formats.fasta", "join"] + for fasta_file in input_fastas: + if not fasta_file.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {fasta_file}") + cmd.append(str(fasta_file)) + + return _run_command(cmd, output_path=output_fasta) + +@mcp.tool +def jcvi_formats_fasta_longestorf( + cds_fasta: Path, + output_fasta: Path +): + """Finds the longest ORF for each sequence in a CDS FASTA file.""" + if not cds_fasta.is_file(): + raise FileNotFoundError(f"Input CDS FASTA file not found: {cds_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "longestorf", str(cds_fasta)] + return _run_command(cmd, output_path=output_fasta) + +@mcp.tool +def jcvi_formats_fasta_pair( + input_fasta: Path, + output_pairs_prefix: str +): + """Sorts paired reads to .pairs, and the rest to .fragments.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "pair", str(input_fasta), f"--prefix={output_pairs_prefix}"] + result = _run_command(cmd) + result["output_files"] = [f"{output_pairs_prefix}.pairs", f"{output_pairs_prefix}.fragments"] + return result + +@mcp.tool +def jcvi_formats_fasta_pairinplace( + fragment_fasta: Path, + output_fasta: Path +): + """Starting from fragment.fasta, finds if adjacent records can form pairs.""" + if not fragment_fasta.is_file(): + raise FileNotFoundError(f"Input fragment FASTA file not found: {fragment_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "pairinplace", str(fragment_fasta)] + return _run_command(cmd, output_path=output_fasta) + +@mcp.tool +def jcvi_formats_fasta_pool( + input_fastas: List[Path], + output_fasta: Path +): + """Pools multiple FASTA files together and adds a prefix to each record ID.""" + cmd = ["python", "-m", "jcvi.formats.fasta", "pool", str(output_fasta)] + for fasta_file in input_fastas: + if not fasta_file.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {fasta_file}") + cmd.append(str(fasta_file)) + + # This tool's argument order might be different, assuming output first. + # Re-running without output redirection as the tool might handle it directly. + command_str = shlex.join(cmd) + try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True) + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(output_fasta)] + } + except subprocess.CalledProcessError as e: + logging.error(f"Command failed: {e.stderr}") + raise e + +@mcp.tool +def jcvi_formats_fasta_qual( + input_fasta: Path, + output_qual: Path +): + """Generates a dummy .qual file based on a FASTA file.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "qual", str(input_fasta)] + return _run_command(cmd, output_path=output_qual) + +@mcp.tool +def jcvi_formats_fasta_random( + input_fasta: Path, + output_fasta: Path, + num_records: int = 100 +): + """Randomly samples a specified number of records from a FASTA file.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + if num_records <= 0: + raise ValueError("Number of records must be positive.") + + cmd = ["python", "-m", "jcvi.formats.fasta", "random", str(input_fasta), str(num_records)] + return _run_command(cmd, output_path=output_fasta) + +@mcp.tool +def jcvi_formats_fasta_sequin( + input_fasta: Path, + output_gapped_fasta: Path +): + """Generates a gapped FASTA file for sequin submission.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "sequin", str(input_fasta)] + return _run_command(cmd, output_path=output_gapped_fasta) + +@mcp.tool +def jcvi_formats_fasta_simulate( + output_fasta: Path, + num_records: int = 100, + seq_len: int = 1000 +): + """Simulates a random FASTA file for testing purposes.""" + if num_records <= 0 or seq_len <= 0: + raise ValueError("Number of records and sequence length must be positive.") + + cmd = ["python", "-m", "jcvi.formats.fasta", "simulate", f"--records={num_records}", f"--len={seq_len}"] + return _run_command(cmd, output_path=output_fasta) + +@mcp.tool +def jcvi_formats_fasta_some( + input_fasta: Path, + ids_file: Path, + output_fasta: Path, + exclude: bool = False +): + """Includes or excludes a list of records from a FASTA file.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + if not ids_file.is_file(): + raise FileNotFoundError(f"IDs file not found: {ids_file}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "some", str(input_fasta), str(ids_file)] + if exclude: + cmd.append("--exclude") + + return _run_command(cmd, output_path=output_fasta) + +@mcp.tool +def jcvi_formats_fasta_sort( + input_fasta: Path, + output_fasta: Path, + sort_by: Literal["id", "size", "length"] = "id", + reverse: bool = False +): + """Sorts the records in a FASTA file by IDs, sizes, etc.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "sort", str(input_fasta), f"--by={sort_by}"] + if reverse: + cmd.append("--reverse") + + return _run_command(cmd, output_path=output_fasta) + +@mcp.tool +def jcvi_formats_fasta_summary( + input_fasta: Path +): + """Reports the real number of bases and N's in a FASTA file.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "summary", str(input_fasta)] + return _run_command(cmd) + +@mcp.tool +def jcvi_formats_fasta_tidy( + input_fasta: Path, + output_fasta: Path +): + """Normalizes gap sizes and removes small components in a FASTA file.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "tidy", str(input_fasta)] + return _run_command(cmd, output_path=output_fasta) + +@mcp.tool +def jcvi_formats_fasta_translate( + cds_fasta: Path, + output_protein_fasta: Path +): + """Translates CDS sequences to proteins.""" + if not cds_fasta.is_file(): + raise FileNotFoundError(f"Input CDS FASTA file not found: {cds_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "translate", str(cds_fasta)] + return _run_command(cmd, output_path=output_protein_fasta) + +@mcp.tool +def jcvi_formats_fasta_trim( + screened_fasta: Path, + output_fasta: Path +): + """Given a cross_match screened FASTA, trims the sequences.""" + if not screened_fasta.is_file(): + raise FileNotFoundError(f"Input screened FASTA file not found: {screened_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "trim", str(screened_fasta)] + return _run_command(cmd, output_path=output_fasta) + +@mcp.tool +def jcvi_formats_fasta_trimsplit( + input_fasta: Path, + output_fasta: Path +): + """Splits sequences at lower-cased letters.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "trimsplit", str(input_fasta)] + return _run_command(cmd, output_path=output_fasta) + +@mcp.tool +def jcvi_formats_fasta_uniq( + input_fasta: Path, + output_fasta: Path +): + """Removes records that are identical.""" + if not input_fasta.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + + cmd = ["python", "-m", "jcvi.formats.fasta", "uniq", str(input_fasta)] + return _run_command(cmd, output_path=output_fasta) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jcvi/app/jcvi_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jcvi/app/jcvi_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..85663e51f53bff85c2d9a2f0d341f8d8f7ef221d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jcvi/app/jcvi_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jcvi/app/jcvi_server.py') +SERVER_NAME = 'biosci_jcvi' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jcvi/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jcvi/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jcvi/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jcvi/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jcvi/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..6e160923c70e4e72a482f3c4f8e18716284b2f73 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jcvi/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-jcvi: + build: . + image: mcp-jcvi:latest + container_name: mcp-jcvi + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=jcvi + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jcvi/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jcvi/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d88f90b31d41086e601dcd6f87d684a7be368762 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jcvi/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - jcvi + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jcvi/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jcvi/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jcvi/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jellyfish/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jellyfish/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d9b71cfe93a8e960fcdc83a1afd86dc78ff90e19 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jellyfish/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install jellyfish via conda (e.g., from bioconda) +RUN conda install -c bioconda jellyfish -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/jellyfish_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/jellyfish_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/jellyfish_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jellyfish/app/jellyfish_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jellyfish/app/jellyfish_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f1d5c5c778cbadfcf9d83bca5a63f5edf992c1f9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jellyfish/app/jellyfish_server.py @@ -0,0 +1,509 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any + +# Helper function to run jellyfish commands +def _run_jellyfish_command( + command: List[str], + input_files: Optional[List[Path]] = None, + output_files: Optional[List[Path]] = None, + check_input_exists: bool = True, + check_output_parent_exists: bool = True, +) -> Dict[str, Any]: + """ + Executes a jellyfish command and handles output/errors. + + Args: + command: A list of strings representing the command and its arguments. + input_files: A list of input file paths to check for existence. + output_files: A list of output file paths whose parent directories should be checked. + check_input_exists: If True, checks if input_files exist. + check_output_parent_exists: If True, checks if parent directories for output_files exist. + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + + Raises: + ValueError: If input files do not exist or output directories are invalid. + subprocess.CalledProcessError: If the command returns a non-zero exit code. + """ + full_command = ["jellyfish"] + command + + # Input file validation + if check_input_exists and input_files: + for f in input_files: + if not f.is_file(): + raise ValueError(f"Input file not found: {f}") + + # Output file directory validation + if check_output_parent_exists and output_files: + for f in output_files: + if f.parent and not f.parent.is_dir(): + f.parent.mkdir(parents=True, exist_ok=True) + + try: + process = subprocess.run( + [str(arg) for arg in full_command], + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join([str(arg) for arg in full_command]), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(f) for f in output_files] if output_files else [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join([str(arg) for arg in full_command]), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Command failed with exit code {e.returncode}", + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": " ".join([str(arg) for arg in full_command]), + "stdout": "", + "stderr": "jellyfish command not found. Is it installed and in PATH?", + "error": "jellyfish executable not found", + "output_files": [], + } + + +@mcp.tool() +def jellyfish_count( + kmer_length: int, + hash_size_bytes: int, + output_database: Path, + input_files: List[Path], + threads: int = 1, + canonical: bool = False, + low_qual_threshold: int = 0, + min_qual_char: str = "!", + num_reprobes: int = 100, + num_buckets: int = 0, + max_counter_value: int = 1000000000, + verbose: bool = False, + mer_len_dna: Optional[int] = None, # This parameter is ambiguous, often -m is kmer_length. + # Keeping it as optional for now if it has a different meaning. +) -> Dict[str, Any]: + """ + Counts k-mers in DNA sequences from FASTA/FASTQ files. + + Args: + kmer_length: The length of k-mers to count (e.g., 21). + hash_size_bytes: The size of the hash table in bytes (e.g., 100M). + output_database: Path to the output Jellyfish database file (.jf). + input_files: List of input FASTA/FASTQ files. + threads: Number of threads to use for counting. + canonical: Count canonical k-mers (lexicographically smallest of k-mer and its reverse complement). + low_qual_threshold: Bases with quality below this threshold are ignored. + min_qual_char: Minimum quality character (ASCII-33 offset). + num_reprobes: Number of reprobes for hash table. + num_buckets: Number of buckets for hash table. + max_counter_value: Maximum value of a counter. + verbose: Enable verbose output. + mer_len_dna: An ambiguous parameter, often -m is kmer_length. If it has a different meaning, specify. + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not (1 <= kmer_length <= 32): # Common k-mer length range for Jellyfish 2.x + raise ValueError("kmer_length must be between 1 and 32.") + if hash_size_bytes <= 0: + raise ValueError("hash_size_bytes must be a positive integer.") + if threads <= 0: + raise ValueError("threads must be a positive integer.") + if low_qual_threshold < 0: + raise ValueError("low_qual_threshold cannot be negative.") + if not input_files: + raise ValueError("At least one input file is required.") + + command = [ + "count", + "-m", str(kmer_length), + "-s", str(hash_size_bytes), + "-o", str(output_database), + "-t", str(threads), + ] + if canonical: + command.append("-C") + if low_qual_threshold > 0: + command.extend(["-q", str(low_qual_threshold)]) + if min_qual_char != "!": + command.extend(["-Q", min_qual_char]) + if num_reprobes != 100: + command.extend(["-r", str(num_reprobes)]) + if num_buckets > 0: + command.extend(["-b", str(num_buckets)]) + if max_counter_value != 1000000000: + command.extend(["-M", str(max_counter_value)]) + if verbose: + command.append("-v") + if mer_len_dna is not None: + # This is a guess, as -m is usually kmer_length. + # If it's a different option, it needs clarification. + command.extend(["--mer-len-dna", str(mer_len_dna)]) + + command.extend([str(f) for f in input_files]) + + return _run_jellyfish_command( + command, input_files=input_files, output_files=[output_database] + ) + + +@mcp.tool() +def jellyfish_bc( + input_database: Path, + output_database: Path, + threads: int = 1, +) -> Dict[str, Any]: + """ + Builds a canonical k-mer database from an existing Jellyfish database. + This command takes a non-canonical k-mer database and converts it to a canonical one. + + Args: + input_database: Path to the input Jellyfish database file (.jf). + output_database: Path to the output canonical Jellyfish database file (.jf). + threads: Number of threads to use. + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if threads <= 0: + raise ValueError("threads must be a positive integer.") + + command = [ + "bc", + "-o", str(output_database), + "-t", str(threads), + str(input_database), + ] + + return _run_jellyfish_command( + command, input_files=[input_database], output_files=[output_database] + ) + + +@mcp.tool() +def jellyfish_info( + input_database: Path, + verbose: bool = False, +) -> Dict[str, Any]: + """ + Displays information about a Jellyfish k-mer database. + + Args: + input_database: Path to the input Jellyfish database file (.jf). + verbose: Enable verbose output. + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + command = ["info", str(input_database)] + if verbose: + command.append("-v") + + return _run_jellyfish_command(command, input_files=[input_database], output_files=[]) + + +@mcp.tool() +def jellyfish_stats( + input_database: Path, + output_file: Optional[Path] = None, + verbose: bool = False, +) -> Dict[str, Any]: + """ + Computes and displays statistics on a Jellyfish k-mer database. + + Args: + input_database: Path to the input Jellyfish database file (.jf). + output_file: Optional path to write statistics to. If None, prints to stdout. + verbose: Enable verbose output. + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + command = ["stats", str(input_database)] + if output_file: + command.extend([">", str(output_file)]) # Redirection is shell-specific, better to capture stdout + if verbose: + command.append("-v") + + # If output_file is provided, we'll capture stdout and write it to the file. + # This avoids shell redirection issues with subprocess. + result = _run_jellyfish_command(command, input_files=[input_database], output_files=[]) + + if output_file and "stdout" in result and result["stdout"]: + try: + output_file.parent.mkdir(parents=True, exist_ok=True) + with open(output_file, "w") as f: + f.write(result["stdout"]) + result["output_files"].append(str(output_file)) + result["stdout"] = f"Statistics written to {output_file}" + except IOError as e: + result["stderr"] += f"\nError writing stats to file {output_file}: {e}" + result["error"] = "File write error" + + return result + + +@mcp.tool() +def jellyfish_histo( + input_database: Path, + output_file: Optional[Path] = None, + max_count_limit: Optional[int] = None, + verbose: bool = False, +) -> Dict[str, Any]: + """ + Generates a histogram of k-mer counts from a Jellyfish database. + + Args: + input_database: Path to the input Jellyfish database file (.jf). + output_file: Optional path to write the histogram to. If None, prints to stdout. + max_count_limit: Limit the histogram to k-mers with counts up to this value. + verbose: Enable verbose output. + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + command = ["histo", str(input_database)] + if max_count_limit is not None: + if max_count_limit <= 0: + raise ValueError("max_count_limit must be a positive integer.") + command.extend(["-l", str(max_count_limit)]) + if verbose: + command.append("-v") + + result = _run_jellyfish_command(command, input_files=[input_database], output_files=[]) + + if output_file and "stdout" in result and result["stdout"]: + try: + output_file.parent.mkdir(parents=True, exist_ok=True) + with open(output_file, "w") as f: + f.write(result["stdout"]) + result["output_files"].append(str(output_file)) + result["stdout"] = f"Histogram written to {output_file}" + except IOError as e: + result["stderr"] += f"\nError writing histogram to file {output_file}: {e}" + result["error"] = "File write error" + + return result + + +@mcp.tool() +def jellyfish_dump( + input_database: Path, + output_file: Optional[Path] = None, + lower_count: int = 1, + upper_count: Optional[int] = None, + with_counts: bool = False, + text_output: bool = False, + fasta_output: bool = False, # Jellyfish dump can output FASTA, but default is kmer count text + verbose: bool = False, +) -> Dict[str, Any]: + """ + Dumps k-mers and their counts from a Jellyfish database to a human-readable format. + + Args: + input_database: Path to the input Jellyfish database file (.jf). + output_file: Optional path to write the dumped k-mers to. If None, prints to stdout. + lower_count: Only dump k-mers with counts greater than or equal to this value. + upper_count: Only dump k-mers with counts less than or equal to this value. + with_counts: Output k-mers with their counts (default is just k-mers). + text_output: Output in plain text format (k-mer count). + fasta_output: Output in FASTA format (k-mer as sequence, count as header). + verbose: Enable verbose output. + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if lower_count < 1: + raise ValueError("lower_count must be a positive integer.") + if upper_count is not None and upper_count < lower_count: + raise ValueError("upper_count cannot be less than lower_count.") + + command = ["dump", str(input_database)] + if lower_count != 1: + command.extend(["-L", str(lower_count)]) + if upper_count is not None: + command.extend(["-U", str(upper_count)]) + if with_counts: + command.append("-c") + if text_output: + command.append("-t") + if fasta_output: + command.append("-F") # Assuming -F for FASTA output, common in k-mer tools + if verbose: + command.append("-v") + + result = _run_jellyfish_command(command, input_files=[input_database], output_files=[]) + + if output_file and "stdout" in result and result["stdout"]: + try: + output_file.parent.mkdir(parents=True, exist_ok=True) + with open(output_file, "w") as f: + f.write(result["stdout"]) + result["output_files"].append(str(output_file)) + result["stdout"] = f"Dumped k-mers written to {output_file}" + except IOError as e: + result["stderr"] += f"\nError writing dumped k-mers to file {output_file}: {e}" + result["error"] = "File write error" + + return result + + +@mcp.tool() +def jellyfish_merge( + output_database: Path, + input_databases: List[Path], + threads: int = 1, + verbose: bool = False, +) -> Dict[str, Any]: + """ + Merges multiple Jellyfish k-mer databases into a single database. + + Args: + output_database: Path to the output merged Jellyfish database file (.jf). + input_databases: List of input Jellyfish database files (.jf) to merge. + threads: Number of threads to use for merging. + verbose: Enable verbose output. + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not input_databases or len(input_databases) < 2: + raise ValueError("At least two input databases are required for merging.") + if threads <= 0: + raise ValueError("threads must be a positive integer.") + + command = [ + "merge", + "-o", str(output_database), + "-t", str(threads), + ] + if verbose: + command.append("-v") + command.extend([str(f) for f in input_databases]) + + return _run_jellyfish_command( + command, input_files=input_databases, output_files=[output_database] + ) + + +@mcp.tool() +def jellyfish_query( + input_database: Path, + kmer_sequences: List[str], + canonical: bool = False, + verbose: bool = False, +) -> Dict[str, Any]: + """ + Queries a Jellyfish k-mer database for the counts of specific k-mers. + + Args: + input_database: Path to the input Jellyfish database file (.jf). + kmer_sequences: List of k-mer sequences to query. + canonical: Query for canonical k-mers (lexicographically smallest of k-mer and its reverse complement). + verbose: Enable verbose output. + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not kmer_sequences: + raise ValueError("At least one k-mer sequence must be provided for querying.") + + command = ["query", str(input_database)] + if canonical: + command.append("-C") + if verbose: + command.append("-v") + command.extend(kmer_sequences) + + return _run_jellyfish_command(command, input_files=[input_database], output_files=[]) + + +@mcp.tool() +def jellyfish_cite() -> Dict[str, Any]: + """ + Displays the citation information for Jellyfish. + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + command = ["cite"] + return _run_jellyfish_command(command, output_files=[]) + + +@mcp.tool() +def jellyfish_mem( + kmer_length: int, + hash_size_bytes: int, + num_threads: int = 1, +) -> Dict[str, Any]: + """ + Estimates memory usage for a Jellyfish k-mer counting operation. + + Args: + kmer_length: The length of k-mers. + hash_size_bytes: The size of the hash table in bytes. + num_threads: Number of threads to consider for memory estimation. + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not (1 <= kmer_length <= 32): + raise ValueError("kmer_length must be between 1 and 32.") + if hash_size_bytes <= 0: + raise ValueError("hash_size_bytes must be a positive integer.") + if num_threads <= 0: + raise ValueError("num_threads must be a positive integer.") + + command = [ + "mem", + "-m", str(kmer_length), + "-s", str(hash_size_bytes), + "-t", str(num_threads), + ] + + return _run_jellyfish_command(command, output_files=[]) + + +@mcp.tool() +def jellyfish_jf( + action: str, + input_file: Path, + output_file: Optional[Path] = None, + extra_args: Optional[List[str]] = None, +) -> Dict[str, Any]: + """ + Performs generic operations on Jellyfish database files (.jf). + Note: The 'jf' subcommand is not well-documented in the provided help. + This function provides a generic interface, assuming 'jf' is a utility for .jf files. + Specific actions and their parameters are inferred or left to 'extra_args'. + + Args: + action: The specific action to perform (e.g., "check", "repair", "convert"). This is an inferred parameter. + input_file: Path to the input Jellyfish database file (.jf). + output_file: Optional path for an output file, if the action produces one. + extra_args: A list of additional arguments specific to the chosen action. + + Returns: + A dictionary containing command_executed, stdout, stderr, and output_files. + """ + if not action: + raise ValueError("An action must be specified for 'jellyfish jf'.") + + command = ["jf", action, str(input_file)] + if output_file: + command.append(str(output_file)) + if extra_args: + command.extend(extra_args) + + output_files_list = [output_file] if output_file else [] + return _run_jellyfish_command( + command, input_files=[input_file], output_files=output_files_list + ) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jellyfish/app/jellyfish_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jellyfish/app/jellyfish_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3f631026276c8442e195213459fba9af95be3961 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jellyfish/app/jellyfish_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jellyfish/app/jellyfish_server.py') +SERVER_NAME = 'biosci_jellyfish' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jellyfish/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jellyfish/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jellyfish/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jellyfish/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jellyfish/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..a31683e36448a10c513086382f472eba77a939dd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jellyfish/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-jellyfish: + build: . + image: mcp-jellyfish:latest + container_name: mcp-jellyfish + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=jellyfish + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jellyfish/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jellyfish/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..ed4410e9f384b8f7343b8b358f775cee61e2a506 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jellyfish/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - jellyfish + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jellyfish/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jellyfish/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jellyfish/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jq/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jq/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5f7c58ac4f72acf1b3c16e620be9372a73ac94c8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jq/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install jq via conda (e.g., from bioconda) +RUN conda install -c bioconda jq -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/jq_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/jq_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/jq_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jq/app/jq_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jq/app/jq_server.py new file mode 100644 index 0000000000000000000000000000000000000000..782eba6ff6c9c0d8fb32010e51275e9626475e44 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jq/app/jq_server.py @@ -0,0 +1,165 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Tuple + +@mcp.tool() +def jq_process_json( + jq_filter: str, + input_files: Optional[List[Path]] = None, + compact_output: bool = False, + null_input: bool = False, + exit_status_from_output: bool = False, + slurp_input: bool = False, + raw_output: bool = False, + raw_input: bool = False, + colorize_json: bool = False, + monochrome_json: bool = False, + sort_keys: bool = False, + use_tabs_for_indentation: bool = False, + args: Optional[List[Tuple[str, str]]] = None, + argjsons: Optional[List[Tuple[str, str]]] = None, + slurpfiles: Optional[List[Tuple[str, Path]]] = None, +) -> dict: + """ + Processes JSON inputs using a jq filter, producing the filter's results as JSON on standard output. + + jq is a lightweight and flexible command-line JSON processor. It takes a filter + as its first argument and then a series of JSON files, which are then processed + and the results are printed to standard output. + + Args: + jq_filter: The jq filter to apply to the JSON text inputs. + The simplest filter is '.', which is the identity filter, + copying jq's input to its output unmodified (except for formatting). + input_files: Optional list of JSON input files. If not provided, jq reads from stdin. + compact_output: Produce compact instead of pretty-printed output. + null_input: Use `null` as the single input value. + exit_status_from_output: Set the exit status code based on the output. + (0 if the output is true or non-empty, 1 if the output is false or empty, + 4 if there is any error). + slurp_input: Read all inputs into an array; apply filter to it. + raw_output: Output raw strings, not JSON texts. + raw_input: Read raw strings, not JSON texts. + colorize_json: Colorize JSON output. + monochrome_json: Do not colorize JSON output. This option overrides -C. + sort_keys: Sort keys of objects on output. + use_tabs_for_indentation: Use tabs for indentation instead of spaces. + args: Optional list of (variable_name, value) tuples to set variable $variable_name to value. + Example: [("myvar", "hello")] will set $myvar to "hello". + argjsons: Optional list of (variable_name, json_value_string) tuples to set variable $variable_name + to a JSON value. The json_value_string must be a valid JSON string. + Example: [("myobj", '{"key": "value"}')] will set $myobj to {"key": "value"}. + slurpfiles: Optional list of (variable_name, file_path) tuples to set variable $variable_name + to an array of JSON texts read from the specified file. + Example: [("data", Path("input.jsonl"))] + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + In case of an error, it includes 'error' and 'returncode'. + """ + if not jq_filter: + raise ValueError("The 'jq_filter' argument cannot be empty.") + + command = ["jq"] + + # Add boolean options + if compact_output: + command.append("-c") + if null_input: + command.append("-n") + if exit_status_from_output: + command.append("-e") + if slurp_input: + command.append("-s") + if raw_output: + command.append("-r") + if raw_input: + command.append("-R") + + # Handle mutually exclusive color options + if colorize_json and monochrome_json: + raise ValueError("Cannot specify both 'colorize_json' (-C) and 'monochrome_json' (-M).") + if colorize_json: + command.append("-C") + if monochrome_json: + command.append("-M") + + if sort_keys: + command.append("-S") + if use_tabs_for_indentation: + command.append("--tab") + + # Add --arg options + if args: + for var_name, value in args: + if not var_name: + raise ValueError("Variable name for --arg cannot be empty.") + command.extend(["--arg", var_name, value]) + + # Add --argjson options + if argjsons: + for var_name, json_value_string in argjsons: + if not var_name: + raise ValueError("Variable name for --argjson cannot be empty.") + # jq will handle parsing errors for the JSON string. + command.extend(["--argjson", var_name, json_value_string]) + + # Add --slurpfile options + if slurpfiles: + for var_name, file_path in slurpfiles: + if not var_name: + raise ValueError("Variable name for --slurpfile cannot be empty.") + if not isinstance(file_path, Path): + file_path = Path(file_path) + if not file_path.is_file(): + raise FileNotFoundError(f"Slurp file not found: {file_path}") + command.extend(["--slurpfile", var_name, str(file_path)]) + + # Add the jq filter (positional argument) + command.append(jq_filter) + + # Add input files (positional arguments) + if input_files: + for file_path in input_files: + if not isinstance(file_path, Path): + file_path = Path(file_path) + if not file_path.is_file(): + raise FileNotFoundError(f"Input file not found: {file_path}") + command.append(str(file_path)) + + try: + process = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + stdout = process.stdout + stderr = process.stderr + # jq typically outputs processed JSON to stdout. No explicit output files are created. + output_files: List[str] = [] + + return { + "command_executed": " ".join(command), + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"jq command failed with exit code {e.returncode}: {e.stderr}", + "returncode": e.returncode, + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "jq command not found. Please ensure 'jq' is installed and available in your system's PATH.", + "error": "jq command not found", + "returncode": 127, # Common return code for command not found + "output_files": [], + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jq/app/jq_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jq/app/jq_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b14d99d87c4c1e89d06dc12482726f4f6f65b122 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jq/app/jq_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jq/app/jq_server.py') +SERVER_NAME = 'biosci_jq' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jq/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jq/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jq/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jq/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jq/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..cbdaeebb17ea356cc49bb71483bc3ee86fd74f3d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jq/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-jq: + build: . + image: mcp-jq:latest + container_name: mcp-jq + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=jq + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jq/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jq/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3183fbbb07ed72005005312ef8ffd678b56048b7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jq/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - jq + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jq/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jq/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_jq/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_k8/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_k8/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..cb898096b6e0c6f86d6951cb0e35fec957b41308 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_k8/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install k8 via conda (e.g., from bioconda) +RUN conda install -c bioconda k8 -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/k8_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/k8_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/k8_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_k8/app/k8_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_k8/app/k8_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2185a1c50d26617ca5331334ca83820a38de4c03 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_k8/app/k8_server.py @@ -0,0 +1,1167 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Dict, Any + +# Helper function to build the common k8 options +def _build_k8_options_list( + use_strict: bool = False, + es5_readonly: bool = True, + es52_globals: bool = True, + harmony_typeof: bool = False, + harmony_scoping: bool = False, + harmony_modules: bool = False, + harmony_proxies: bool = False, + harmony_collections: bool = False, + harmony_observation: bool = False, + harmony: bool = False, + packed_arrays: bool = True, + smi_only_arrays: bool = True, + clever_optimizations: bool = True, + unbox_double_arrays: bool = True, + string_slices: bool = True, + crankshaft: bool = True, + hydrogen_filter: str = "", + use_range: bool = True, + eliminate_dead_phis: bool = True, + use_gvn: bool = True, + use_canonicalizing: bool = True, + use_inlining: bool = True, + max_inlined_source_size: int = 600, + max_inlined_nodes: int = 196, + max_inlined_nodes_cumulative: int = 196, + loop_invariant_code_motion: bool = True, + fast_math: bool = True, + collect_megamorphic_maps_from_stub_cache: bool = True, + hydrogen_stats: bool = False, + trace_hydrogen: bool = False, + trace_phase: str = "Z", + trace_inlining: bool = False, + trace_alloc: bool = False, + trace_all_uses: bool = False, + trace_range: bool = False, + trace_gvn: bool = False, + trace_representation: bool = False, + stress_pointer_maps: bool = False, + stress_environments: bool = False, + deopt_every_n_times: int = 0, + trap_on_deopt: bool = False, + deoptimize_uncommon_cases: bool = True, + polymorphic_inlining: bool = True, + use_osr: bool = True, + array_bounds_checks_elimination: bool = True, + array_index_dehoisting: bool = True, + dead_code_elimination: bool = True, + trace_dead_code_elimination: bool = False, + track_allocation_sites: bool = True, + trace_osr: bool = False, + stress_runs: int = 0, + optimize_closures: bool = True, + lookup_sample_by_shared: bool = True, + cache_optimized_code: bool = True, + inline_construct: bool = True, + inline_arguments: bool = True, + inline_accessors: bool = True, + loop_weight: int = 1, + optimize_for_in: bool = True, + opt_safe_uint32_operations: bool = True, + parallel_recompilation: bool = False, + trace_parallel_recompilation: bool = False, + parallel_recompilation_queue_length: int = 2, + manual_parallel_recompilation: bool = False, + experimental_profiler: bool = True, + watch_ic_patching: bool = False, + frame_count: int = 1, + self_optimization: bool = False, + direct_self_opt: bool = False, + retry_self_opt: bool = False, + interrupt_at_exit: bool = False, + weighted_back_edges: bool = False, + interrupt_budget: int = 5888, + type_info_threshold: int = 15, + self_opt_count: int = 130, + trace_opt_verbose: bool = False, + debug_code: bool = False, + code_comments: bool = False, + enable_sse2: bool = True, + enable_sse3: bool = True, + enable_sse4_1: bool = True, + enable_cmov: bool = True, + enable_rdtsc: bool = True, + enable_sahf: bool = True, + enable_vfp3: bool = True, + enable_vfp2: bool = True, + enable_armv7: bool = True, + enable_sudiv: bool = True, + enable_movw_movt: bool = False, + enable_unaligned_accesses: bool = True, + enable_fpu: bool = True, + enable_vldr_imm: bool = False, + expose_natives_as: str = "NULL", + expose_debug_as: str = "NULL", + expose_gc: bool = False, + expose_externalize_string: bool = False, + stack_trace_limit: int = 10, + builtins_in_stack_traces: bool = False, + disable_native_files: bool = False, + inline_new: bool = True, + stack_trace_on_abort: bool = True, + trace: bool = False, + mask_constants_with_cookie: bool = True, + lazy: bool = True, + trace_opt: bool = False, + trace_opt_stats: bool = False, + opt: bool = True, + always_opt: bool = False, + prepare_always_opt: bool = False, + trace_deopt: bool = False, + min_preparse_length: int = 1024, + always_full_compiler: bool = False, + max_opt_count: int = 10, + compilation_cache: bool = True, + cache_prototype_transitions: bool = True, + trace_debug_json: bool = False, + debugger_auto_break: bool = True, + enable_liveedit: bool = True, + break_on_abort: bool = True, + stack_size: Optional[int] = None, +) -> List[str]: + """ + Helper function to construct the list of command-line options for k8. + Handles boolean flags with --flag / --no-flag logic based on default values, + and string/integer options. + """ + options = [] + + # Helper for boolean flags: add --flag if value is True and different from default, + # add --no-flag if value is False and different from default. + def add_bool_flag(flag_name: str, value: bool, default_value: bool): + if value != default_value: + if value: + options.append(f"--{flag_name}") + else: + options.append(f"--no-{flag_name}") + + # Add all boolean flags + add_bool_flag("use_strict", use_strict, False) + add_bool_flag("es5_readonly", es5_readonly, True) + add_bool_flag("es52_globals", es52_globals, True) + add_bool_flag("harmony_typeof", harmony_typeof, False) + add_bool_flag("harmony_scoping", harmony_scoping, False) + add_bool_flag("harmony_modules", harmony_modules, False) + add_bool_flag("harmony_proxies", harmony_proxies, False) + add_bool_flag("harmony_collections", harmony_collections, False) + add_bool_flag("harmony_observation", harmony_observation, False) + add_bool_flag("harmony", harmony, False) + add_bool_flag("packed_arrays", packed_arrays, True) + add_bool_flag("smi_only_arrays", smi_only_arrays, True) + add_bool_flag("clever_optimizations", clever_optimizations, True) + add_bool_flag("unbox_double_arrays", unbox_double_arrays, True) + add_bool_flag("string_slices", string_slices, True) + add_bool_flag("crankshaft", crankshaft, True) + add_bool_flag("use_range", use_range, True) + add_bool_flag("eliminate_dead_phis", eliminate_dead_phis, True) + add_bool_flag("use_gvn", use_gvn, True) + add_bool_flag("use_canonicalizing", use_canonicalizing, True) + add_bool_flag("use_inlining", use_inlining, True) + add_bool_flag("loop_invariant_code_motion", loop_invariant_code_motion, True) + add_bool_flag("fast_math", fast_math, True) + add_bool_flag("collect_megamorphic_maps_from_stub_cache", collect_megamorphic_maps_from_stub_cache, True) + add_bool_flag("hydrogen_stats", hydrogen_stats, False) + add_bool_flag("trace_hydrogen", trace_hydrogen, False) + add_bool_flag("trace_inlining", trace_inlining, False) + add_bool_flag("trace_alloc", trace_alloc, False) + add_bool_flag("trace_all_uses", trace_all_uses, False) + add_bool_flag("trace_range", trace_range, False) + add_bool_flag("trace_gvn", trace_gvn, False) + add_bool_flag("trace_representation", trace_representation, False) + add_bool_flag("stress_pointer_maps", stress_pointer_maps, False) + add_bool_flag("stress_environments", stress_environments, False) + add_bool_flag("trap_on_deopt", trap_on_deopt, False) + add_bool_flag("deoptimize_uncommon_cases", deoptimize_uncommon_cases, True) + add_bool_flag("polymorphic_inlining", polymorphic_inlining, True) + add_bool_flag("use_osr", use_osr, True) + add_bool_flag("array_bounds_checks_elimination", array_bounds_checks_elimination, True) + add_bool_flag("array_index_dehoisting", array_index_dehoisting, True) + add_bool_flag("dead_code_elimination", dead_code_elimination, True) + add_bool_flag("trace_dead_code_elimination", trace_dead_code_elimination, False) + add_bool_flag("track_allocation_sites", track_allocation_sites, True) + add_bool_flag("trace_osr", trace_osr, False) + add_bool_flag("optimize_closures", optimize_closures, True) + add_bool_flag("lookup_sample_by_shared", lookup_sample_by_shared, True) + add_bool_flag("cache_optimized_code", cache_optimized_code, True) + add_bool_flag("inline_construct", inline_construct, True) + add_bool_flag("inline_arguments", inline_arguments, True) + add_bool_flag("inline_accessors", inline_accessors, True) + add_bool_flag("optimize_for_in", optimize_for_in, True) + add_bool_flag("opt_safe_uint32_operations", opt_safe_uint32_operations, True) + add_bool_flag("parallel_recompilation", parallel_recompilation, False) + add_bool_flag("trace_parallel_recompilation", trace_parallel_recompilation, False) + add_bool_flag("manual_parallel_recompilation", manual_parallel_recompilation, False) + add_bool_flag("experimental_profiler", experimental_profiler, True) + add_bool_flag("watch_ic_patching", watch_ic_patching, False) + add_bool_flag("self_optimization", self_optimization, False) + add_bool_flag("direct_self_opt", direct_self_opt, False) + add_bool_flag("retry_self_opt", retry_self_opt, False) + add_bool_flag("interrupt_at_exit", interrupt_at_exit, False) + add_bool_flag("weighted_back_edges", weighted_back_edges, False) + add_bool_flag("trace_opt_verbose", trace_opt_verbose, False) + add_bool_flag("debug_code", debug_code, False) + add_bool_flag("code_comments", code_comments, False) + add_bool_flag("enable_sse2", enable_sse2, True) + add_bool_flag("enable_sse3", enable_sse3, True) + add_bool_flag("enable_sse4_1", enable_sse4_1, True) + add_bool_flag("enable_cmov", enable_cmov, True) + add_bool_flag("enable_rdtsc", enable_rdtsc, True) + add_bool_flag("enable_sahf", enable_sahf, True) + add_bool_flag("enable_vfp3", enable_vfp3, True) + add_bool_flag("enable_vfp2", enable_vfp2, True) + add_bool_flag("enable_armv7", enable_armv7, True) + add_bool_flag("enable_sudiv", enable_sudiv, True) + add_bool_flag("enable_movw_movt", enable_movw_movt, False) + add_bool_flag("enable_unaligned_accesses", enable_unaligned_accesses, True) + add_bool_flag("enable_fpu", enable_fpu, True) + add_bool_flag("enable_vldr_imm", enable_vldr_imm, False) + add_bool_flag("expose_gc", expose_gc, False) + add_bool_flag("expose_externalize_string", expose_externalize_string, False) + add_bool_flag("builtins_in_stack_traces", builtins_in_stack_traces, False) + add_bool_flag("disable_native_files", disable_native_files, False) + add_bool_flag("inline_new", inline_new, True) + add_bool_flag("stack_trace_on_abort", stack_trace_on_abort, True) + add_bool_flag("trace", trace, False) + add_bool_flag("mask_constants_with_cookie", mask_constants_with_cookie, True) + add_bool_flag("lazy", lazy, True) + add_bool_flag("trace_opt", trace_opt, False) + add_bool_flag("trace_opt_stats", trace_opt_stats, False) + add_bool_flag("opt", opt, True) + add_bool_flag("always_opt", always_opt, False) + add_bool_flag("prepare_always_opt", prepare_always_opt, False) + add_bool_flag("trace_deopt", trace_deopt, False) + add_bool_flag("always_full_compiler", always_full_compiler, False) + add_bool_flag("compilation_cache", compilation_cache, True) + add_bool_flag("cache_prototype_transitions", cache_prototype_transitions, True) + add_bool_flag("trace_debug_json", trace_debug_json, False) + add_bool_flag("debugger_auto_break", debugger_auto_break, True) + add_bool_flag("enable_liveedit", enable_liveedit, True) + add_bool_flag("break_on_abort", break_on_abort, True) + + # Add string options if they differ from their defaults + if hydrogen_filter != "": + options.extend(["--hydrogen_filter", hydrogen_filter]) + if trace_phase != "Z": + options.extend(["--trace_phase", trace_phase]) + if expose_natives_as != "NULL": + options.extend(["--expose_natives_as", expose_natives_as]) + if expose_debug_as != "NULL": + options.extend(["--expose_debug_as", expose_debug_as]) + + # Add integer options if they differ from their defaults + if max_inlined_source_size != 600: + options.append(f"--max_inlined_source_size={max_inlined_source_size}") + if max_inlined_nodes != 196: + options.append(f"--max_inlined_nodes={max_inlined_nodes}") + if max_inlined_nodes_cumulative != 196: + options.append(f"--max_inlined_nodes_cumulative={max_inlined_nodes_cumulative}") + if deopt_every_n_times != 0: + options.append(f"--deopt_every_n_times={deopt_every_n_times}") + if stress_runs != 0: + options.append(f"--stress_runs={stress_runs}") + if loop_weight != 1: + options.append(f"--loop_weight={loop_weight}") + if parallel_recompilation_queue_length != 2: + options.append(f"--parallel_recompilation_queue_length={parallel_recompilation_queue_length}") + if frame_count != 1: + options.append(f"--frame_count={frame_count}") + if interrupt_budget != 5888: + options.append(f"--interrupt_budget={interrupt_budget}") + if type_info_threshold != 15: + options.append(f"--type_info_threshold={type_info_threshold}") + if self_opt_count != 130: + options.append(f"--self_opt_count={self_opt_count}") + if stack_trace_limit != 10: + options.append(f"--stack_trace_limit={stack_trace_limit}") + if min_preparse_length != 1024: + options.append(f"--min_preparse_length={min_preparse_length}") + if max_opt_count != 10: + options.append(f"--max_opt_count={max_opt_count}") + if stack_size is not None: # This option has no default in help, so it's truly optional + options.append(f"--stack_size={stack_size}") + + return options + + +@mcp.tool() +def k8_execute_string( + script_string: str, + use_strict: bool = False, + es5_readonly: bool = True, + es52_globals: bool = True, + harmony_typeof: bool = False, + harmony_scoping: bool = False, + harmony_modules: bool = False, + harmony_proxies: bool = False, + harmony_collections: bool = False, + harmony_observation: bool = False, + harmony: bool = False, + packed_arrays: bool = True, + smi_only_arrays: bool = True, + clever_optimizations: bool = True, + unbox_double_arrays: bool = True, + string_slices: bool = True, + crankshaft: bool = True, + hydrogen_filter: str = "", + use_range: bool = True, + eliminate_dead_phis: bool = True, + use_gvn: bool = True, + use_canonicalizing: bool = True, + use_inlining: bool = True, + max_inlined_source_size: int = 600, + max_inlined_nodes: int = 196, + max_inlined_nodes_cumulative: int = 196, + loop_invariant_code_motion: bool = True, + fast_math: bool = True, + collect_megamorphic_maps_from_stub_cache: bool = True, + hydrogen_stats: bool = False, + trace_hydrogen: bool = False, + trace_phase: str = "Z", + trace_inlining: bool = False, + trace_alloc: bool = False, + trace_all_uses: bool = False, + trace_range: bool = False, + trace_gvn: bool = False, + trace_representation: bool = False, + stress_pointer_maps: bool = False, + stress_environments: bool = False, + deopt_every_n_times: int = 0, + trap_on_deopt: bool = False, + deoptimize_uncommon_cases: bool = True, + polymorphic_inlining: bool = True, + use_osr: bool = True, + array_bounds_checks_elimination: bool = True, + array_index_dehoisting: bool = True, + dead_code_elimination: bool = True, + trace_dead_code_elimination: bool = False, + track_allocation_sites: bool = True, + trace_osr: bool = False, + stress_runs: int = 0, + optimize_closures: bool = True, + lookup_sample_by_shared: bool = True, + cache_optimized_code: bool = True, + inline_construct: bool = True, + inline_arguments: bool = True, + inline_accessors: bool = True, + loop_weight: int = 1, + optimize_for_in: bool = True, + opt_safe_uint32_operations: bool = True, + parallel_recompilation: bool = False, + trace_parallel_recompilation: bool = False, + parallel_recompilation_queue_length: int = 2, + manual_parallel_recompilation: bool = False, + experimental_profiler: bool = True, + watch_ic_patching: bool = False, + frame_count: int = 1, + self_optimization: bool = False, + direct_self_opt: bool = False, + retry_self_opt: bool = False, + interrupt_at_exit: bool = False, + weighted_back_edges: bool = False, + interrupt_budget: int = 5888, + type_info_threshold: int = 15, + self_opt_count: int = 130, + trace_opt_verbose: bool = False, + debug_code: bool = False, + code_comments: bool = False, + enable_sse2: bool = True, + enable_sse3: bool = True, + enable_sse4_1: bool = True, + enable_cmov: bool = True, + enable_rdtsc: bool = True, + enable_sahf: bool = True, + enable_vfp3: bool = True, + enable_vfp2: bool = True, + enable_armv7: bool = True, + enable_sudiv: bool = True, + enable_movw_movt: bool = False, + enable_unaligned_accesses: bool = True, + enable_fpu: bool = True, + enable_vldr_imm: bool = False, + expose_natives_as: str = "NULL", + expose_debug_as: str = "NULL", + expose_gc: bool = False, + expose_externalize_string: bool = False, + stack_trace_limit: int = 10, + builtins_in_stack_traces: bool = False, + disable_native_files: bool = False, + inline_new: bool = True, + stack_trace_on_abort: bool = True, + trace: bool = False, + mask_constants_with_cookie: bool = True, + lazy: bool = True, + trace_opt: bool = False, + trace_opt_stats: bool = False, + opt: bool = True, + always_opt: bool = False, + prepare_always_opt: bool = False, + trace_deopt: bool = False, + min_preparse_length: int = 1024, + always_full_compiler: bool = False, + max_opt_count: int = 10, + compilation_cache: bool = True, + cache_prototype_transitions: bool = True, + trace_debug_json: bool = False, + debugger_auto_break: bool = True, + enable_liveedit: bool = True, + break_on_abort: bool = True, + stack_size: Optional[int] = None, +) -> Dict[str, Any]: + """ + Executes a JavaScript string in the k8 V8 shell. + + Args: + script_string: The JavaScript code to execute. + use_strict: Enforce strict mode. + es5_readonly: Activate correct semantics for inheriting readonliness. + es52_globals: Activate new semantics for global var declarations. + harmony_typeof: Enable harmony semantics for typeof. + harmony_scoping: Enable harmony block scoping. + harmony_modules: Enable harmony modules (implies block scoping). + harmony_proxies: Enable harmony proxies. + harmony_collections: Enable harmony collections (sets, maps, and weak maps). + harmony_observation: Enable harmony object observation (implies harmony collections). + harmony: Enable all harmony features (except typeof). + packed_arrays: Optimizes arrays that have no holes. + smi_only_arrays: Tracks arrays with only smi values. + clever_optimizations: Optimize object size, Array shift, DOM strings and string +. + unbox_double_arrays: Automatically unbox arrays of doubles. + string_slices: Use string slices. + crankshaft: Use crankshaft. + hydrogen_filter: Optimization filter. + use_range: Use hydrogen range analysis. + eliminate_dead_phis: Eliminate dead phis. + use_gvn: Use hydrogen global value numbering. + use_canonicalizing: Use hydrogen instruction canonicalizing. + use_inlining: Use function inlining. + max_inlined_source_size: Maximum source size in bytes considered for a single inlining. + max_inlined_nodes: Maximum number of AST nodes considered for a single inlining. + max_inlined_nodes_cumulative: Maximum cumulative number of AST nodes considered for inlining. + loop_invariant_code_motion: Loop invariant code motion. + fast_math: Faster (but maybe less accurate) math functions. + collect_megamorphic_maps_from_stub_cache: Crankshaft harvests type feedback from stub cache. + hydrogen_stats: Print statistics for hydrogen. + trace_hydrogen: Trace generated hydrogen to file. + trace_phase: Trace generated IR for specified phases. + trace_inlining: Trace inlining decisions. + trace_alloc: Trace register allocator. + trace_all_uses: Trace all use positions. + trace_range: Trace range analysis. + trace_gvn: Trace global value numbering. + trace_representation: Trace representation types. + stress_pointer_maps: Pointer map for every instruction. + stress_environments: Environment for every instruction. + deopt_every_n_times: Deoptimize every n times a deopt point is passed. + trap_on_deopt: Put a break point before deoptimizing. + deoptimize_uncommon_cases: Deoptimize uncommon cases. + polymorphic_inlining: Polymorphic inlining. + use_osr: Use on-stack replacement. + array_bounds_checks_elimination: Perform array bounds checks elimination. + array_index_dehoisting: Perform array index dehoisting. + dead_code_elimination: Use dead code elimination. + trace_dead_code_elimination: Trace dead code elimination. + track_allocation_sites: Use allocation site info to reduce transitions. + trace_osr: Trace on-stack replacement. + stress_runs: Number of stress runs. + optimize_closures: Optimize closures. + lookup_sample_by_shared: When picking a function to optimize, watch for shared function info, not JSFunction itself. + cache_optimized_code: Cache optimized code for closures. + inline_construct: Inline constructor calls. + inline_arguments: Inline functions with arguments object. + inline_accessors: Inline JavaScript accessors. + loop_weight: Loop weight for representation inference. + optimize_for_in: Optimize functions containing for-in loops. + opt_safe_uint32_operations: Allow uint32 values on optimize frames if they are used only in safe operations. + parallel_recompilation: Optimizing hot functions asynchronously on a separate thread. + trace_parallel_recompilation: Track parallel recompilation. + parallel_recompilation_queue_length: The length of the parallel compilation queue. + manual_parallel_recompilation: Disable automatic optimization. + experimental_profiler: Enable all profiler experiments. + watch_ic_patching: Profiler considers IC stability. + frame_count: Number of stack frames inspected by the profiler. + self_optimization: Primitive functions trigger their own optimization. + direct_self_opt: Call recompile stub directly when self-optimizing. + retry_self_opt: Re-try self-optimization if it failed. + interrupt_at_exit: Insert an interrupt check at function exit. + weighted_back_edges: Weight back edges by jump distance for interrupt triggering. + interrupt_budget: Execution budget before interrupt is triggered. + type_info_threshold: Percentage of ICs that must have type info to allow optimization. + self_opt_count: Call count before self-optimization. + trace_opt_verbose: Extra verbose compilation tracing. + debug_code: Generate extra code (assertions) for debugging. + code_comments: Emit comments in code disassembly. + enable_sse2: Enable use of SSE2 instructions if available. + enable_sse3: Enable use of SSE3 instructions if available. + enable_sse4_1: Enable use of SSE4.1 instructions if available. + enable_cmov: Enable use of CMOV instruction if available. + enable_rdtsc: Enable use of RDTSC instruction if available. + enable_sahf: Enable use of SAHF instruction if available (X64 only). + enable_vfp3: Enable use of VFP3 instructions if available - this implies enabling ARMv7 and VFP2 instructions (ARM only). + enable_vfp2: Enable use of VFP2 instructions if available. + enable_armv7: Enable use of ARMv7 instructions if available (ARM only). + enable_sudiv: Enable use of SDIV and UDIV instructions if available (ARM only). + enable_movw_movt: Enable loading 32-bit constant by means of movw/movt instruction pairs (ARM only). + enable_unaligned_accesses: Enable unaligned accesses for ARMv7 (ARM only). + enable_fpu: Enable use of MIPS FPU instructions if available (MIPS only). + enable_vldr_imm: Enable use of constant pools for double immediate (ARM only). + expose_natives_as: Expose natives in global object. + expose_debug_as: Expose debug in global object. + expose_gc: Expose gc extension. + expose_externalize_string: Expose externalize string extension. + stack_trace_limit: Number of stack frames to capture. + builtins_in_stack_traces: Show built-in functions in stack traces. + disable_native_files: Disable builtin natives files. + inline_new: Use fast inline allocation. + stack_trace_on_abort: Print a stack trace if an assertion failure occurs. + trace: Trace function calls. + mask_constants_with_cookie: Use random jit cookie to mask large constants. + lazy: Use lazy compilation. + trace_opt: Trace lazy optimization. + trace_opt_stats: Trace lazy optimization statistics. + opt: Use adaptive optimizations. + always_opt: Always try to optimize functions. + prepare_always_opt: Prepare for turning on always opt. + trace_deopt: Trace deoptimization. + min_preparse_length: Minimum length for automatic enable preparsing. + always_full_compiler: Try to use the dedicated run-once backend for all code. + max_opt_count: Maximum number of optimization attempts before giving up. + compilation_cache: Enable compilation cache. + cache_prototype_transitions: Cache prototype transitions. + trace_debug_json: Trace debugging JSON request/response. + debugger_auto_break: Automatically set the debug break flag when debugger commands are in the queue. + enable_liveedit: Enable liveedit experimental feature. + break_on_abort: Always cause a debug break before aborting. + stack_size: Stack size in kilobytes. + """ + if not script_string: + raise ValueError("script_string cannot be empty.") + + command = ["k8"] + # Pass all relevant parameters from the current function's locals to the helper + # Exclude 'script_string' as it's handled separately. + options_kwargs = {k: v for k, v in locals().items() if k != "script_string"} + command.extend(_build_k8_options_list(**options_kwargs)) + command.extend(["-e", script_string]) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "returncode": e.returncode, + "output_files": [], + } + + +@mcp.tool() +def k8_run_scripts( + script_files: List[Path], + use_strict: bool = False, + es5_readonly: bool = True, + es52_globals: bool = True, + harmony_typeof: bool = False, + harmony_scoping: bool = False, + harmony_modules: bool = False, + harmony_proxies: bool = False, + harmony_collections: bool = False, + harmony_observation: bool = False, + harmony: bool = False, + packed_arrays: bool = True, + smi_only_arrays: bool = True, + clever_optimizations: bool = True, + unbox_double_arrays: bool = True, + string_slices: bool = True, + crankshaft: bool = True, + hydrogen_filter: str = "", + use_range: bool = True, + eliminate_dead_phis: bool = True, + use_gvn: bool = True, + use_canonicalizing: bool = True, + use_inlining: bool = True, + max_inlined_source_size: int = 600, + max_inlined_nodes: int = 196, + max_inlined_nodes_cumulative: int = 196, + loop_invariant_code_motion: bool = True, + fast_math: bool = True, + collect_megamorphic_maps_from_stub_cache: bool = True, + hydrogen_stats: bool = False, + trace_hydrogen: bool = False, + trace_phase: str = "Z", + trace_inlining: bool = False, + trace_alloc: bool = False, + trace_all_uses: bool = False, + trace_range: bool = False, + trace_gvn: bool = False, + trace_representation: bool = False, + stress_pointer_maps: bool = False, + stress_environments: bool = False, + deopt_every_n_times: int = 0, + trap_on_deopt: bool = False, + deoptimize_uncommon_cases: bool = True, + polymorphic_inlining: bool = True, + use_osr: bool = True, + array_bounds_checks_elimination: bool = True, + array_index_dehoisting: bool = True, + dead_code_elimination: bool = True, + trace_dead_code_elimination: bool = False, + track_allocation_sites: bool = True, + trace_osr: bool = False, + stress_runs: int = 0, + optimize_closures: bool = True, + lookup_sample_by_shared: bool = True, + cache_optimized_code: bool = True, + inline_construct: bool = True, + inline_arguments: bool = True, + inline_accessors: bool = True, + loop_weight: int = 1, + optimize_for_in: bool = True, + opt_safe_uint32_operations: bool = True, + parallel_recompilation: bool = False, + trace_parallel_recompilation: bool = False, + parallel_recompilation_queue_length: int = 2, + manual_parallel_recompilation: bool = False, + experimental_profiler: bool = True, + watch_ic_patching: bool = False, + frame_count: int = 1, + self_optimization: bool = False, + direct_self_opt: bool = False, + retry_self_opt: bool = False, + interrupt_at_exit: bool = False, + weighted_back_edges: bool = False, + interrupt_budget: int = 5888, + type_info_threshold: int = 15, + self_opt_count: int = 130, + trace_opt_verbose: bool = False, + debug_code: bool = False, + code_comments: bool = False, + enable_sse2: bool = True, + enable_sse3: bool = True, + enable_sse4_1: bool = True, + enable_cmov: bool = True, + enable_rdtsc: bool = True, + enable_sahf: bool = True, + enable_vfp3: bool = True, + enable_vfp2: bool = True, + enable_armv7: bool = True, + enable_sudiv: bool = True, + enable_movw_movt: bool = False, + enable_unaligned_accesses: bool = True, + enable_fpu: bool = True, + enable_vldr_imm: bool = False, + expose_natives_as: str = "NULL", + expose_debug_as: str = "NULL", + expose_gc: bool = False, + expose_externalize_string: bool = False, + stack_trace_limit: int = 10, + builtins_in_stack_traces: bool = False, + disable_native_files: bool = False, + inline_new: bool = True, + stack_trace_on_abort: bool = True, + trace: bool = False, + mask_constants_with_cookie: bool = True, + lazy: bool = True, + trace_opt: bool = False, + trace_opt_stats: bool = False, + opt: bool = True, + always_opt: bool = False, + prepare_always_opt: bool = False, + trace_deopt: bool = False, + min_preparse_length: int = 1024, + always_full_compiler: bool = False, + max_opt_count: int = 10, + compilation_cache: bool = True, + cache_prototype_transitions: bool = True, + trace_debug_json: bool = False, + debugger_auto_break: bool = True, + enable_liveedit: bool = True, + break_on_abort: bool = True, + stack_size: Optional[int] = None, +) -> Dict[str, Any]: + """ + Runs one or more JavaScript script files using the k8 V8 shell. + The scripts are executed in order and the program exits after execution. + + Args: + script_files: A list of paths to JavaScript files to execute. + Each file must exist. + use_strict: Enforce strict mode. + es5_readonly: Activate correct semantics for inheriting readonliness. + es52_globals: Activate new semantics for global var declarations. + harmony_typeof: Enable harmony semantics for typeof. + harmony_scoping: Enable harmony block scoping. + harmony_modules: Enable harmony modules (implies block scoping). + harmony_proxies: Enable harmony proxies. + harmony_collections: Enable harmony collections (sets, maps, and weak maps). + harmony_observation: Enable harmony object observation (implies harmony collections). + harmony: Enable all harmony features (except typeof). + packed_arrays: Optimizes arrays that have no holes. + smi_only_arrays: Tracks arrays with only smi values. + clever_optimizations: Optimize object size, Array shift, DOM strings and string +. + unbox_double_arrays: Automatically unbox arrays of doubles. + string_slices: Use string slices. + crankshaft: Use crankshaft. + hydrogen_filter: Optimization filter. + use_range: Use hydrogen range analysis. + eliminate_dead_phis: Eliminate dead phis. + use_gvn: Use hydrogen global value numbering. + use_canonicalizing: Use hydrogen instruction canonicalizing. + use_inlining: Use function inlining. + max_inlined_source_size: Maximum source size in bytes considered for a single inlining. + max_inlined_nodes: Maximum number of AST nodes considered for a single inlining. + max_inlined_nodes_cumulative: Maximum cumulative number of AST nodes considered for inlining. + loop_invariant_code_motion: Loop invariant code motion. + fast_math: Faster (but maybe less accurate) math functions. + collect_megamorphic_maps_from_stub_cache: Crankshaft harvests type feedback from stub cache. + hydrogen_stats: Print statistics for hydrogen. + trace_hydrogen: Trace generated hydrogen to file. + trace_phase: Trace generated IR for specified phases. + trace_inlining: Trace inlining decisions. + trace_alloc: Trace register allocator. + trace_all_uses: Trace all use positions. + trace_range: Trace range analysis. + trace_gvn: Trace global value numbering. + trace_representation: Trace representation types. + stress_pointer_maps: Pointer map for every instruction. + stress_environments: Environment for every instruction. + deopt_every_n_times: Deoptimize every n times a deopt point is passed. + trap_on_deopt: Put a break point before deoptimizing. + deoptimize_uncommon_cases: Deoptimize uncommon cases. + polymorphic_inlining: Polymorphic inlining. + use_osr: Use on-stack replacement. + array_bounds_checks_elimination: Perform array bounds checks elimination. + array_index_dehoisting: Perform array index dehoisting. + dead_code_elimination: Use dead code elimination. + trace_dead_code_elimination: Trace dead code elimination. + track_allocation_sites: Use allocation site info to reduce transitions. + trace_osr: Trace on-stack replacement. + stress_runs: Number of stress runs. + optimize_closures: Optimize closures. + lookup_sample_by_shared: When picking a function to optimize, watch for shared function info, not JSFunction itself. + cache_optimized_code: Cache optimized code for closures. + inline_construct: Inline constructor calls. + inline_arguments: Inline functions with arguments object. + inline_accessors: Inline JavaScript accessors. + loop_weight: Loop weight for representation inference. + optimize_for_in: Optimize functions containing for-in loops. + opt_safe_uint32_operations: Allow uint32 values on optimize frames if they are used only in safe operations. + parallel_recompilation: Optimizing hot functions asynchronously on a separate thread. + trace_parallel_recompilation: Track parallel recompilation. + parallel_recompilation_queue_length: The length of the parallel compilation queue. + manual_parallel_recompilation: Disable automatic optimization. + experimental_profiler: Enable all profiler experiments. + watch_ic_patching: Profiler considers IC stability. + frame_count: Number of stack frames inspected by the profiler. + self_optimization: Primitive functions trigger their own optimization. + direct_self_opt: Call recompile stub directly when self-optimizing. + retry_self_opt: Re-try self-optimization if it failed. + interrupt_at_exit: Insert an interrupt check at function exit. + weighted_back_edges: Weight back edges by jump distance for interrupt triggering. + interrupt_budget: Execution budget before interrupt is triggered. + type_info_threshold: Percentage of ICs that must have type info to allow optimization. + self_opt_count: Call count before self-optimization. + trace_opt_verbose: Extra verbose compilation tracing. + debug_code: Generate extra code (assertions) for debugging. + code_comments: Emit comments in code disassembly. + enable_sse2: Enable use of SSE2 instructions if available. + enable_sse3: Enable use of SSE3 instructions if available. + enable_sse4_1: Enable use of SSE4.1 instructions if available. + enable_cmov: Enable use of CMOV instruction if available. + enable_rdtsc: Enable use of RDTSC instruction if available. + enable_sahf: Enable use of SAHF instruction if available (X64 only). + enable_vfp3: Enable use of VFP3 instructions if available - this implies enabling ARMv7 and VFP2 instructions (ARM only). + enable_vfp2: Enable use of VFP2 instructions if available. + enable_armv7: Enable use of ARMv7 instructions if available (ARM only). + enable_sudiv: Enable use of SDIV and UDIV instructions if available (ARM only). + enable_movw_movt: Enable loading 32-bit constant by means of movw/movt instruction pairs (ARM only). + enable_unaligned_accesses: Enable unaligned accesses for ARMv7 (ARM only). + enable_fpu: Enable use of MIPS FPU instructions if available (MIPS only). + enable_vldr_imm: Enable use of constant pools for double immediate (ARM only). + expose_natives_as: Expose natives in global object. + expose_debug_as: Expose debug in global object. + expose_gc: Expose gc extension. + expose_externalize_string: Expose externalize string extension. + stack_trace_limit: Number of stack frames to capture. + builtins_in_stack_traces: Show built-in functions in stack traces. + disable_native_files: Disable builtin natives files. + inline_new: Use fast inline allocation. + stack_trace_on_abort: Print a stack trace if an assertion failure occurs. + trace: Trace function calls. + mask_constants_with_cookie: Use random jit cookie to mask large constants. + lazy: Use lazy compilation. + trace_opt: Trace lazy optimization. + trace_opt_stats: Trace lazy optimization statistics. + opt: Use adaptive optimizations. + always_opt: Always try to optimize functions. + prepare_always_opt: Prepare for turning on always opt. + trace_deopt: Trace deoptimization. + min_preparse_length: Minimum length for automatic enable preparsing. + always_full_compiler: Try to use the dedicated run-once backend for all code. + max_opt_count: Maximum number of optimization attempts before giving up. + compilation_cache: Enable compilation cache. + cache_prototype_transitions: Cache prototype transitions. + trace_debug_json: Trace debugging JSON request/response. + debugger_auto_break: Automatically set the debug break flag when debugger commands are in the queue. + enable_liveedit: Enable liveedit experimental feature. + break_on_abort: Always cause a debug break before aborting. + stack_size: Stack size in kilobytes. + """ + if not script_files: + raise ValueError("At least one script file must be provided.") + + for script_file in script_files: + if not isinstance(script_file, Path): + raise TypeError(f"Expected Path object for script_file, got {type(script_file)}") + if not script_file.is_file(): + raise FileNotFoundError(f"Script file not found: {script_file}") + + command = ["k8"] + # Pass all relevant parameters from the current function's locals to the helper + # Exclude 'script_files' as it's handled separately. + options_kwargs = {k: v for k, v in locals().items() if k != "script_files"} + command.extend(_build_k8_options_list(**options_kwargs)) + command.extend([str(f) for f in script_files]) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "returncode": e.returncode, + "output_files": [], + } + + +@mcp.tool() +def k8_interactive_shell( + script_files: Optional[List[Path]] = None, + use_strict: bool = False, + es5_readonly: bool = True, + es52_globals: bool = True, + harmony_typeof: bool = False, + harmony_scoping: bool = False, + harmony_modules: bool = False, + harmony_proxies: bool = False, + harmony_collections: bool = False, + harmony_observation: bool = False, + harmony: bool = False, + packed_arrays: bool = True, + smi_only_arrays: bool = True, + clever_optimizations: bool = True, + unbox_double_arrays: bool = True, + string_slices: bool = True, + crankshaft: bool = True, + hydrogen_filter: str = "", + use_range: bool = True, + eliminate_dead_phis: bool = True, + use_gvn: bool = True, + use_canonicalizing: bool = True, + use_inlining: bool = True, + max_inlined_source_size: int = 600, + max_inlined_nodes: int = 196, + max_inlined_nodes_cumulative: int = 196, + loop_invariant_code_motion: bool = True, + fast_math: bool = True, + collect_megamorphic_maps_from_stub_cache: bool = True, + hydrogen_stats: bool = False, + trace_hydrogen: bool = False, + trace_phase: str = "Z", + trace_inlining: bool = False, + trace_alloc: bool = False, + trace_all_uses: bool = False, + trace_range: bool = False, + trace_gvn: bool = False, + trace_representation: bool = False, + stress_pointer_maps: bool = False, + stress_environments: bool = False, + deopt_every_n_times: int = 0, + trap_on_deopt: bool = False, + deoptimize_uncommon_cases: bool = True, + polymorphic_inlining: bool = True, + use_osr: bool = True, + array_bounds_checks_elimination: bool = True, + array_index_dehoisting: bool = True, + dead_code_elimination: bool = True, + trace_dead_code_elimination: bool = False, + track_allocation_sites: bool = True, + trace_osr: bool = False, + stress_runs: int = 0, + optimize_closures: bool = True, + lookup_sample_by_shared: bool = True, + cache_optimized_code: bool = True, + inline_construct: bool = True, + inline_arguments: bool = True, + inline_accessors: bool = True, + loop_weight: int = 1, + optimize_for_in: bool = True, + opt_safe_uint32_operations: bool = True, + parallel_recompilation: bool = False, + trace_parallel_recompilation: bool = False, + parallel_recompilation_queue_length: int = 2, + manual_parallel_recompilation: bool = False, + experimental_profiler: bool = True, + watch_ic_patching: bool = False, + frame_count: int = 1, + self_optimization: bool = False, + direct_self_opt: bool = False, + retry_self_opt: bool = False, + interrupt_at_exit: bool = False, + weighted_back_edges: bool = False, + interrupt_budget: int = 5888, + type_info_threshold: int = 15, + self_opt_count: int = 130, + trace_opt_verbose: bool = False, + debug_code: bool = False, + code_comments: bool = False, + enable_sse2: bool = True, + enable_sse3: bool = True, + enable_sse4_1: bool = True, + enable_cmov: bool = True, + enable_rdtsc: bool = True, + enable_sahf: bool = True, + enable_vfp3: bool = True, + enable_vfp2: bool = True, + enable_armv7: bool = True, + enable_sudiv: bool = True, + enable_movw_movt: bool = False, + enable_unaligned_accesses: bool = True, + enable_fpu: bool = True, + enable_vldr_imm: bool = False, + expose_natives_as: str = "NULL", + expose_debug_as: str = "NULL", + expose_gc: bool = False, + expose_externalize_string: bool = False, + stack_trace_limit: int = 10, + builtins_in_stack_traces: bool = False, + disable_native_files: bool = False, + inline_new: bool = True, + stack_trace_on_abort: bool = True, + trace: bool = False, + mask_constants_with_cookie: bool = True, + lazy: bool = True, + trace_opt: bool = False, + trace_opt_stats: bool = False, + opt: bool = True, + always_opt: bool = False, + prepare_always_opt: bool = False, + trace_deopt: bool = False, + min_preparse_length: int = 1024, + always_full_compiler: bool = False, + max_opt_count: int = 10, + compilation_cache: bool = True, + cache_prototype_transitions: bool = True, + trace_debug_json: bool = False, + debugger_auto_break: bool = True, + enable_liveedit: bool = True, + break_on_abort: bool = True, + stack_size: Optional[int] = None, +) -> Dict[str, Any]: + """ + Runs an interactive JavaScript shell using k8. + Optionally loads script files before entering interactive mode. + + Note: This tool will block until the interactive shell is exited. + It is not suitable for automated scripting where immediate return is expected. + + Args: + script_files: An optional list of paths to JavaScript files to load + before entering the interactive shell. Each file must exist. + use_strict: Enforce strict mode. + es5_readonly: Activate correct semantics for inheriting readonliness. + es52_globals: Activate new semantics for global var declarations. + harmony_typeof: Enable harmony semantics for typeof. + harmony_scoping: Enable harmony block scoping. + harmony_modules: Enable harmony modules (implies block scoping). + harmony_proxies: Enable harmony proxies. + harmony_collections: Enable harmony collections (sets, maps, and weak maps). + harmony_observation: Enable harmony object observation (implies harmony collections). + harmony: Enable all harmony features (except typeof). + packed_arrays: Optimizes arrays that have no holes. + smi_only_arrays: Tracks arrays with only smi values. + clever_optimizations: Optimize object size, Array shift, DOM strings and string +. + unbox_double_arrays: Automatically unbox arrays of doubles. + string_slices: Use string slices. + crankshaft: Use crankshaft. + hydrogen_filter: Optimization filter. + use_range: Use hydrogen range analysis. + eliminate_dead_phis: Eliminate dead phis. + use_gvn: Use hydrogen global value numbering. + use_canonicalizing: Use hydrogen instruction canonicalizing. + use_inlining: Use function inlining. + max_inlined_source_size: Maximum source size in bytes considered for a single inlining. + max_inlined_nodes: Maximum number of AST nodes considered for a single inlining. + max_inlined_nodes_cumulative: Maximum cumulative number of AST nodes considered for inlining. + loop_invariant_code_motion: Loop invariant code motion. + fast_math: Faster (but maybe less accurate) math functions. + collect_megamorphic_maps_from_stub_cache: Crankshaft harvests type feedback from stub cache. + hydrogen_stats: Print statistics for hydrogen. + trace_hydrogen: Trace generated hydrogen to file. + trace_phase: Trace generated IR for specified phases. + trace_inlining: Trace inlining decisions. + trace_alloc: Trace register allocator. + trace_all_uses: Trace all use positions. + trace_range: Trace range analysis. + trace_gvn: Trace global value numbering. + trace_representation: Trace representation types. + stress_pointer_maps: Pointer map for every instruction. + stress_environments: Environment for every instruction. + deopt_every_n_times: Deoptimize every n times a deopt point is passed. + trap_on_deopt: Put a break point before deoptimizing. + deoptimize_uncommon_cases: Deoptimize uncommon cases. + polymorphic_inlining: Polymorphic inlining. + use_osr: Use on-stack replacement. + array_bounds_checks_elimination: Perform array bounds checks elimination. + array_index_dehoisting: Perform array index dehoisting. + dead_code_elimination: Use dead code elimination. + trace_dead_code_elimination: Trace dead code elimination. + track_allocation_sites: Use allocation site info to reduce transitions. + trace_osr: Trace on-stack replacement. + stress_runs: Number of stress runs. + optimize_closures: Optimize closures. + lookup_sample_by_shared: When picking a function to optimize, watch for shared function info, not JSFunction itself. + cache_optimized_code: Cache optimized code for closures. + inline_construct: Inline constructor calls. + inline_arguments: Inline functions with arguments object. + inline_accessors: Inline JavaScript accessors. + loop_weight: Loop weight for representation inference. + optimize_for_in: Optimize functions containing for-in loops. + opt_safe_uint32_operations: Allow uint32 values on optimize frames if they are used only in safe operations. + parallel_recompilation: Optimizing hot functions asynchronously on a separate thread. + trace_parallel_recompilation: Track parallel recompilation. + parallel_recompilation_queue_length: The length of the parallel compilation queue. + manual_parallel_recompilation: Disable automatic optimization. + experimental_profiler: Enable all profiler experiments. + watch_ic_patching: Profiler considers IC stability. + frame_count: Number of stack frames inspected by the profiler. + self_optimization: Primitive functions trigger their own optimization. + direct_self_opt: Call recompile stub directly when self-optimizing. + retry_self_opt: Re-try self-optimization if it failed. + interrupt_at_exit: Insert an interrupt check at function exit. + weighted_back_edges: Weight back edges by jump distance for interrupt triggering. + interrupt_budget: Execution budget before interrupt is triggered. + type_info_threshold: Percentage of ICs that must have type info to allow optimization. + self_opt_count: Call count before self-optimization. + trace_opt_verbose: Extra verbose compilation tracing. + debug_code: Generate extra code (assertions) for debugging. + code_comments: Emit comments in code disassembly. + enable_sse2: Enable use of SSE2 instructions if available. + enable_sse3: Enable use of SSE3 instructions if available. + enable_sse4_1: Enable use of SSE4.1 instructions if available. + enable_cmov: Enable use of CMOV instruction if available. + enable_rdtsc: Enable use of RDTSC instruction if available. + enable_sahf: Enable use of SAHF instruction if available (X64 only). + enable_vfp3: Enable use of VFP3 instructions if available - this implies enabling ARMv7 and VFP2 instructions (ARM only). + enable_vfp2: Enable use of VFP2 instructions if available. + enable_armv7: Enable use of ARMv7 instructions if available (ARM only). + enable_sudiv: Enable use of SDIV and UDIV instructions if available (ARM only). + enable_movw_movt: Enable loading 32-bit constant by means of movw/movt instruction pairs (ARM only). + enable_unaligned_accesses: Enable unaligned accesses for ARMv7 (ARM only). + enable_fpu: Enable use of MIPS FPU instructions if available (MIPS only). + enable_vldr_imm: Enable use of constant pools for double immediate (ARM only). + expose_natives_as: Expose natives in global object. + expose_debug_as: Expose debug in global object. + expose_gc: Expose gc extension. + expose_externalize_string: Expose externalize string extension. + stack_trace_limit: Number of stack frames to capture. + builtins_in_stack_traces: Show built-in functions in stack traces. + disable_native_files: Disable builtin natives files. + inline_new: Use fast inline allocation. + stack_trace_on_abort: Print a stack trace if an assertion failure occurs. + trace: Trace function calls. + mask_constants_with_cookie: Use random jit cookie to mask large constants. + lazy: Use lazy compilation. + trace_opt: Trace lazy optimization. + trace_opt_stats: Trace lazy optimization statistics. + opt: Use adaptive optimizations. + always_opt: Always try to optimize functions. + prepare_always_opt: Prepare for turning on always opt. + trace_deopt: Trace deoptimization. + min_preparse_length: Minimum length for automatic enable preparsing. + always_full_compiler: Try to use the dedicated run-once backend for all code. + max_opt_count: Maximum number of optimization attempts before giving up. + compilation_cache: Enable compilation cache. + cache_prototype_transitions: Cache prototype transitions. + trace_debug_json: Trace debugging JSON request/response. + debugger_auto_break: Automatically set the debug break flag when debugger commands are in the queue. + enable_liveedit: Enable liveedit experimental feature. + break_on_abort: Always cause a debug break before aborting. + stack_size: Stack size in kilobytes. + """ + command = ["k8"] + # Pass all relevant parameters from the current function's locals to the helper + # Exclude 'script_files' as it's handled separately. + options_kwargs = {k: v for k, v in locals().items() if k != "script_files"} + command.extend(_build_k8_options_list(**options_kwargs)) + + if script_files: + for script_file in script_files: + if not isinstance(script_file, Path): + raise TypeError(f"Expected Path object for script_file, got {type(script_file)}") + if not script_file.is_file(): + raise FileNotFoundError(f"Script file not found: {script_file}") + command.append("--shell") # Explicitly enable interactive shell when files are provided + command.extend([str(f) for f in script_files]) + # If no script_files, k8 without -e or positional args defaults to interactive shell. + # No explicit --shell is needed in this case based on `shell [options]` usage. + + try: + # For interactive tools, stdout/stderr are usually not captured + # as they are meant for direct user interaction. + # However, MCP tools typically capture output. + # Running an interactive shell in a non-interactive environment + # might lead to unexpected behavior or hang. + # For the purpose of MCP, we will capture, but note the interactive nature. + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "returncode": e.returncode, + "output_files": [], + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_k8/app/k8_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_k8/app/k8_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fc28161a3dc35d5b80ff25f9ea4af41fa225e5b2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_k8/app/k8_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_k8/app/k8_server.py') +SERVER_NAME = 'biosci_k8' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_k8/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_k8/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_k8/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_k8/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_k8/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..95e59ea79b50101ecfaaafc6592af410c689553a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_k8/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-k8: + build: . + image: mcp-k8:latest + container_name: mcp-k8 + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=k8 + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_k8/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_k8/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..936fda977284eebfb043bcf663a2c05e59aa2fca --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_k8/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - k8 + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_k8/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_k8/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_k8/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kaiju/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kaiju/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e78a2d7a1f6cf1e5bbc56c5606c41daa80bbfaf7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kaiju/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install kaiju via conda (e.g., from bioconda) +RUN conda install -c bioconda kaiju -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/kaiju_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/kaiju_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/kaiju_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kaiju/app/kaiju_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kaiju/app/kaiju_server.py new file mode 100644 index 0000000000000000000000000000000000000000..921c8d2b605d8103a878832a18d62a6f9592ef3e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kaiju/app/kaiju_server.py @@ -0,0 +1,854 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Literal, Union +import os +import tempfile + +# Helper function for running commands +def _run_command(cmd: List[str], cwd: Optional[str] = None) -> dict: + """ + Executes a shell command and returns its stdout, stderr, and exit code. + """ + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + cwd=cwd, + ) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "returncode": e.returncode, + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": f"Error: Command '{cmd[0]}' not found. Please ensure Kaiju and its sub-tools are installed and in your PATH.", + "error": "Command not found", + "returncode": 127, + "output_files": [], + } + +# Helper for path validation +def _validate_input_file(file_path: Path, param_name: str): + if not file_path.exists(): + raise ValueError(f"Input file for '{param_name}' not found: {file_path}") + if not file_path.is_file(): + raise ValueError(f"Input path for '{param_name}' is not a file: {file_path}") + +def _validate_output_file(file_path: Path, param_name: str): + if file_path.exists() and not file_path.is_file(): + raise ValueError(f"Output path for '{param_name}' exists but is not a file: {file_path}") + if not file_path.parent.exists(): + # Attempt to create parent directory if it doesn't exist + try: + file_path.parent.mkdir(parents=True, exist_ok=True) + except OSError as e: + raise ValueError(f"Could not create output directory for '{param_name}': {file_path.parent}. Error: {e}") + if not os.access(file_path.parent, os.W_OK): + raise ValueError(f"Output directory for '{param_name}' is not writable: {file_path.parent}") + +def _validate_directory(dir_path: Path, param_name: str, must_exist: bool = True, must_be_writable: bool = False): + if must_exist and not dir_path.exists(): + raise ValueError(f"Directory for '{param_name}' not found: {dir_path}") + if dir_path.exists() and not dir_path.is_dir(): + raise ValueError(f"Path for '{param_name}' is not a directory: {dir_path}") + if not dir_path.exists(): + try: + dir_path.mkdir(parents=True, exist_ok=True) + except OSError as e: + raise ValueError(f"Could not create directory for '{param_name}': {dir_path}. Error: {e}") + if must_be_writable and not os.access(dir_path, os.W_OK): + raise ValueError(f"Directory for '{param_name}' is not writable: {dir_path}") + + +@mcp.tool() +def kaiju_classify( + nodes_dmp_file: Path, + fmi_file: Path, + input_file: Path, + second_input_file: Optional[Path] = None, + output_file: Optional[Path] = None, + threads: int = 1, + mismatches: int = 3, + e_value: float = 0.01, + min_match_len: int = 11, + min_match_score: int = 65, + run_mode: Literal["greedy", "mem"] = "greedy", + protein_input: bool = False, + enable_seg_filter: bool = True, + verbose_output: bool = False, +) -> dict: + """ + Performs fast and sensitive taxonomic classification of high-throughput sequencing reads. + + Args: + nodes_dmp_file: Path to the NCBI taxonomy nodes.dmp file. + fmi_file: Path to the Kaiju database index (.fmi) file. + input_file: Path to the input FASTQ/FASTA file for single-end reads or first mate of paired-end reads. + second_input_file: Optional path to the second input FASTQ/FASTA file for paired-end reads. + output_file: Optional path to the output file. If not provided, output will be printed to STDOUT. + threads: Number of parallel threads to use. Must be >= 1. + mismatches: Number of allowed mismatches in Greedy mode. Must be >= 0. + e_value: E-value threshold for classification in Greedy mode. Must be > 0. + min_match_len: Minimum required match length in MEM mode. Must be >= 1. + min_match_score: Minimum required match score in Greedy mode. Must be >= 0. + run_mode: The classification run mode, either 'greedy' or 'mem'. + protein_input: If True, input sequences are treated as protein sequences (disables translation). + enable_seg_filter: If True, enables filtering of query sequences containing low-complexity regions using SEG. + Enabled by default. Set to False to disable. + verbose_output: If True, enables verbose output with additional columns. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + # Input validation + _validate_input_file(nodes_dmp_file, "nodes_dmp_file") + _validate_input_file(fmi_file, "fmi_file") + _validate_input_file(input_file, "input_file") + if second_input_file: + _validate_input_file(second_input_file, "second_input_file") + if output_file: + _validate_output_file(output_file, "output_file") + + if threads < 1: + raise ValueError("Number of threads must be at least 1.") + if mismatches < 0: + raise ValueError("Number of mismatches must be non-negative.") + if e_value <= 0: + raise ValueError("E-value must be greater than 0.") + if min_match_len < 1: + raise ValueError("Minimum match length must be at least 1.") + if min_match_score < 0: + raise ValueError("Minimum match score must be non-negative.") + + cmd = [ + "kaiju", + "-t", str(nodes_dmp_file), + "-f", str(fmi_file), + "-i", str(input_file), + "-z", str(threads), + ] + + if second_input_file: + cmd.extend(["-j", str(second_input_file)]) + if output_file: + cmd.extend(["-o", str(output_file)]) + + # Run mode specific options + if run_mode == "greedy": + cmd.extend(["-e", str(mismatches)]) + cmd.extend(["-E", str(e_value)]) + cmd.extend(["-s", str(min_match_score)]) + elif run_mode == "mem": + cmd.extend(["-a", "mem"]) + cmd.extend(["-m", str(min_match_len)]) + + if protein_input: + cmd.append("-p") + + # SEG filter: -x enables, -X disables. It's enabled by default. + # So, only add -X if enable_seg_filter is False. + if not enable_seg_filter: + cmd.append("-X") + + if verbose_output: + cmd.append("-v") + + result = _run_command(cmd) + if output_file and "error" not in result: + result["output_files"].append(str(output_file)) + return result + + +@mcp.tool() +def kaiju_makedb( + source_database: Literal[ + "refseq", "refseq_nr", "refseq_ref", "progenomes", "viruses", + "plasmids", "fungi", "nr", "nr_euk", "rvdb" + ], + output_dir: Path, + threads: int = 5, +) -> dict: + """ + Downloads reference databases and builds Kaiju's database index. + + Args: + source_database: The name of the reference database to download and build. + Available options: 'refseq', 'refseq_nr', 'refseq_ref', + 'progenomes', 'viruses', 'plasmids', 'fungi', 'nr', 'nr_euk', 'rvdb'. + output_dir: Directory where the database files and index will be created. + Requires at least 500 GB of free space for large databases. + threads: Number of parallel threads for index construction. A higher number + increases memory usage during construction. Must be >= 1. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + _validate_directory(output_dir, "output_dir", must_exist=False, must_be_writable=True) + if threads < 1: + raise ValueError("Number of threads must be at least 1.") + + cmd = [ + "kaiju-makedb", + "-s", source_database, + "-t", str(threads), + ] + + # Run the command in the specified output directory + result = _run_command(cmd, cwd=str(output_dir)) + + if "error" not in result: + # Identify expected output files. + # The docs state that for "-s refseq", the index is "refseq/kaiju_db_refseq.fmi". + # This implies a subdirectory named after the source database. + db_subdir = output_dir / source_database + fmi_file = db_subdir / f"kaiju_db_{source_database}.fmi" + nodes_file = output_dir / "nodes.dmp" + names_file = output_dir / "names.dmp" + + # Check if they exist before adding + if fmi_file.exists(): + result["output_files"].append(str(fmi_file)) + if nodes_file.exists(): + result["output_files"].append(str(nodes_file)) + if names_file.exists(): + result["output_files"].append(str(names_file)) + + return result + + +@mcp.tool() +def kaiju_mkbwt( + input_fasta: Path, + output_prefix: str, + threads: int = 5, + alphabet: str = "ACDEFGHIKLMNPQRSTVWY", +) -> dict: + """ + Builds the Burrows-Wheeler Transform (BWT) for a custom protein database. + This is the first step in creating a custom Kaiju index. + + Args: + input_fasta: Path to the input FASTA file containing protein sequences. + Headers must be numeric NCBI taxon identifiers, optionally prefixed by an identifier and underscore. + output_prefix: Prefix for the output BWT and SA files (e.g., 'proteins' will create proteins.bwt, proteins.sa). + threads: Number of parallel threads to use. Must be >= 1. + alphabet: The alphabet of protein sequences. Defaults to standard 20 amino acids. + Only uppercase characters are allowed. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + _validate_input_file(input_fasta, "input_fasta") + if threads < 1: + raise ValueError("Number of threads must be at least 1.") + if not alphabet.isupper() or not alphabet.isalpha(): + raise ValueError("Alphabet must contain only uppercase alphabetic characters.") + if not output_prefix: + raise ValueError("Output prefix cannot be empty.") + + cmd = [ + "kaiju-mkbwt", + "-n", str(threads), + "-a", alphabet, + "-o", output_prefix, + str(input_fasta), + ] + + result = _run_command(cmd) + if "error" not in result: + # kaiju-mkbwt creates .bwt and .sa files + bwt_file = Path(f"{output_prefix}.bwt") + sa_file = Path(f"{output_prefix}.sa") + if bwt_file.exists(): + result["output_files"].append(str(bwt_file)) + if sa_file.exists(): + result["output_files"].append(str(sa_file)) + return result + + +@mcp.tool() +def kaiju_mkfmi( + input_prefix: str, +) -> dict: + """ + Builds the FM-index from BWT and SA files created by kaiju-mkbwt. + This is the second step in creating a custom Kaiju index. + + Args: + input_prefix: The prefix used for the BWT and SA files (e.g., 'proteins' + if kaiju-mkbwt created proteins.bwt and proteins.sa). + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + if not input_prefix: + raise ValueError("Input prefix cannot be empty.") + + # Check if intermediate files exist + bwt_file = Path(f"{input_prefix}.bwt") + sa_file = Path(f"{input_prefix}.sa") + if not bwt_file.exists(): + raise ValueError(f"Required BWT file not found: {bwt_file}. Run kaiju_mkbwt first.") + if not sa_file.exists(): + raise ValueError(f"Required SA file not found: {sa_file}. Run kaiju_mkbwt first.") + + cmd = [ + "kaiju-mkfmi", + input_prefix, + ] + + result = _run_command(cmd) + if "error" not in result: + # kaiju-mkfmi creates the .fmi file + fmi_file = Path(f"{input_prefix}.fmi") + if fmi_file.exists(): + result["output_files"].append(str(fmi_file)) + return result + + +@mcp.tool() +def kaiju_multi_classify( + nodes_dmp_file: Path, + fmi_file: Path, + input_files: List[Path], + second_input_files: Optional[List[Path]] = None, + output_files: Optional[List[Path]] = None, + threads: int = 1, + mismatches: int = 3, + e_value: float = 0.01, + min_match_len: int = 11, + min_match_score: int = 65, + run_mode: Literal["greedy", "mem"] = "greedy", + protein_input: bool = False, + enable_seg_filter: bool = True, + verbose_output: bool = False, +) -> dict: + """ + Performs fast and sensitive taxonomic classification for multiple samples simultaneously. + + Args: + nodes_dmp_file: Path to the NCBI taxonomy nodes.dmp file. + fmi_file: Path to the Kaiju database index (.fmi) file. + input_files: A list of paths to input FASTQ/FASTA files for single-end reads + or first mates of paired-end reads. + second_input_files: Optional list of paths to second input FASTQ/FASTA files + for paired-end reads. If provided, its length must match `input_files`. + output_files: Optional list of paths to output files. If not provided, output will be + printed to STDOUT (merged if multiple inputs). If provided, its length + must match `input_files`. + threads: Number of parallel threads to use. Must be >= 1. + mismatches: Number of allowed mismatches in Greedy mode. Must be >= 0. + e_value: E-value threshold for classification in Greedy mode. Must be > 0. + min_match_len: Minimum required match length in MEM mode. Must be >= 1. + min_match_score: Minimum required match score in Greedy mode. Must be >= 0. + run_mode: The classification run mode, either 'greedy' or 'mem'. + protein_input: If True, input sequences are treated as protein sequences (disables translation). + enable_seg_filter: If True, enables filtering of query sequences containing low-complexity regions using SEG. + Enabled by default. Set to False to disable. + verbose_output: If True, enables verbose output with additional columns. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + # Input validation + _validate_input_file(nodes_dmp_file, "nodes_dmp_file") + _validate_input_file(fmi_file, "fmi_file") + + if not input_files: + raise ValueError("At least one input file must be provided.") + for f in input_files: + _validate_input_file(f, "input_files") + + if second_input_files: + if len(input_files) != len(second_input_files): + raise ValueError("Number of first input files must match number of second input files.") + for f in second_input_files: + _validate_input_file(f, "second_input_files") + + if output_files: + if len(input_files) != len(output_files): + raise ValueError("Number of input files must match number of output files.") + for f in output_files: + _validate_output_file(f, "output_files") + + if threads < 1: + raise ValueError("Number of threads must be at least 1.") + if mismatches < 0: + raise ValueError("Number of mismatches must be non-negative.") + if e_value <= 0: + raise ValueError("E-value must be greater than 0.") + if min_match_len < 1: + raise ValueError("Minimum match length must be at least 1.") + if min_match_score < 0: + raise ValueError("Minimum match score must be non-negative.") + + cmd = [ + "kaiju-multi", + "-t", str(nodes_dmp_file), + "-f", str(fmi_file), + "-i", ",".join(str(p) for p in input_files), + "-z", str(threads), + ] + + if second_input_files: + cmd.extend(["-j", ",".join(str(p) for p in second_input_files)]) + if output_files: + cmd.extend(["-o", ",".join(str(p) for p in output_files)]) + + # Run mode specific options + if run_mode == "greedy": + cmd.extend(["-e", str(mismatches)]) + cmd.extend(["-E", str(e_value)]) + cmd.extend(["-s", str(min_match_score)]) + elif run_mode == "mem": + cmd.extend(["-a", "mem"]) + cmd.extend(["-m", str(min_match_len)]) + + if protein_input: + cmd.append("-p") + + if not enable_seg_filter: + cmd.append("-X") + + if verbose_output: + cmd.append("-v") + + result = _run_command(cmd) + if output_files and "error" not in result: + result["output_files"].extend([str(f) for f in output_files]) + return result + + +@mcp.tool() +def kaiju2krona( + nodes_dmp_file: Path, + names_dmp_file: Path, + input_kaiju_output: Path, + output_krona_file: Path, + print_full_taxon_path: bool = False, +) -> dict: + """ + Converts Kaiju's tab-separated output file into a Krona-compatible text file. + + Args: + nodes_dmp_file: Path to the NCBI taxonomy nodes.dmp file. + names_dmp_file: Path to the NCBI taxonomy names.dmp file. + input_kaiju_output: Path to the Kaiju classification output file. + output_krona_file: Path to the output Krona-compatible text file. + print_full_taxon_path: If True, print the full taxon path instead of just the taxon name. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + _validate_input_file(nodes_dmp_file, "nodes_dmp_file") + _validate_input_file(names_dmp_file, "names_dmp_file") + _validate_input_file(input_kaiju_output, "input_kaiju_output") + _validate_output_file(output_krona_file, "output_krona_file") + + cmd = [ + "kaiju2krona", + "-t", str(nodes_dmp_file), + "-n", str(names_dmp_file), + "-i", str(input_kaiju_output), + "-o", str(output_krona_file), + ] + + if print_full_taxon_path: + cmd.append("-l") # The doc says -l for kaiju2krona prints full path. + + result = _run_command(cmd) + if "error" not in result: + result["output_files"].append(str(output_krona_file)) + return result + + +@mcp.tool() +def kaiju2table( + nodes_dmp_file: Path, + names_dmp_file: Path, + taxonomic_rank: str, + output_summary_file: Path, + input_kaiju_outputs: List[Path], + min_percentage: float = 0.0, + min_count: int = 0, + exclude_unclassified: bool = False, + print_full_taxon_path: bool = False, + specific_ranks_for_path: Optional[List[str]] = None, +) -> dict: + """ + Converts Kaiju's output file(s) into a summary table for a given taxonomic rank. + + Args: + nodes_dmp_file: Path to the NCBI taxonomy nodes.dmp file. + names_dmp_file: Path to the NCBI taxonomy names.dmp file. + taxonomic_rank: The taxonomic rank for which to create the summary table (e.g., 'genus', 'species'). + output_summary_file: Path to the output summary table file (TSV format). + input_kaiju_outputs: A list of paths to one or more Kaiju classification output files. + min_percentage: Minimum percentage of total reads for a taxon to be included in the summary. Must be >= 0.0. + min_count: Minimum absolute read count for a taxon to be included in the summary. Must be >= 0. + exclude_unclassified: If True, unclassified reads are not counted towards the total + when calculating percentages. + print_full_taxon_path: If True, print the full taxon path instead of just the taxon name. + specific_ranks_for_path: Optional list of specific ranks to print in the taxon path + (e.g., ['superkingdom', 'phylum', 'class']). Overrides `print_full_taxon_path` if set. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + _validate_input_file(nodes_dmp_file, "nodes_dmp_file") + _validate_input_file(names_dmp_file, "names_dmp_file") + _validate_output_file(output_summary_file, "output_summary_file") + if not input_kaiju_outputs: + raise ValueError("At least one Kaiju output file must be provided.") + for f in input_kaiju_outputs: + _validate_input_file(f, "input_kaiju_outputs") + + if min_percentage < 0.0: + raise ValueError("Minimum percentage must be non-negative.") + if min_count < 0: + raise ValueError("Minimum count must be non-negative.") + if not taxonomic_rank: + raise ValueError("Taxonomic rank cannot be empty.") + + cmd = [ + "kaiju2table", + "-t", str(nodes_dmp_file), + "-n", str(names_dmp_file), + "-r", taxonomic_rank, + "-o", str(output_summary_file), + ] + cmd.extend([str(f) for f in input_kaiju_outputs]) + + if min_percentage > 0.0: + cmd.extend(["-m", str(min_percentage)]) + if min_count > 0: + cmd.extend(["-c", str(min_count)]) + if exclude_unclassified: + cmd.append("-u") + + if specific_ranks_for_path: + cmd.extend(["-l", ",".join(specific_ranks_for_path)]) + elif print_full_taxon_path: + cmd.append("-p") + + result = _run_command(cmd) + if "error" not in result: + result["output_files"].append(str(output_summary_file)) + return result + + +@mcp.tool() +def kaiju_add_taxon_names( + nodes_dmp_file: Path, + names_dmp_file: Path, + input_kaiju_output: Path, + output_file_with_names: Path, + omit_unclassified_reads: bool = False, + print_full_taxon_path: bool = False, + specific_ranks_for_path: Optional[List[str]] = None, +) -> dict: + """ + Appends taxon names or full taxon paths to Kaiju's output file. + + Args: + nodes_dmp_file: Path to the NCBI taxonomy nodes.dmp file. + names_dmp_file: Path to the NCBI taxonomy names.dmp file. + input_kaiju_output: Path to the Kaiju classification output file. + output_file_with_names: Path to the output file with appended taxon names/paths. + omit_unclassified_reads: If True, unclassified reads will be omitted from the output. + print_full_taxon_path: If True, print the full taxon path instead of just the taxon name. + specific_ranks_for_path: Optional list of specific ranks to print in the path + (e.g., ['phylum', 'genus']). Overrides `print_full_taxon_path` if set. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + _validate_input_file(nodes_dmp_file, "nodes_dmp_file") + _validate_input_file(names_dmp_file, "names_dmp_file") + _validate_input_file(input_kaiju_output, "input_kaiju_output") + _validate_output_file(output_file_with_names, "output_file_with_names") + + cmd = [ + "kaiju-addTaxonNames", + "-t", str(nodes_dmp_file), + "-n", str(names_dmp_file), + "-i", str(input_kaiju_output), + "-o", str(output_file_with_names), + ] + + if omit_unclassified_reads: + cmd.append("-u") + + if specific_ranks_for_path: + cmd.extend(["-r", ",".join(specific_ranks_for_path)]) + elif print_full_taxon_path: + cmd.append("-p") + + result = _run_command(cmd) + if "error" not in result: + result["output_files"].append(str(output_file_with_names)) + return result + + +@mcp.tool() +def kaiju_merge_outputs( + input_file1: Path, + input_file2: Path, + output_merged_file: Path, + verbose_output: bool = False, + conflict_strategy: Literal["1", "2", "lca", "lowest"] = "lca", + nodes_dmp_file: Optional[Path] = None, + precedence_by_score: bool = False, +) -> dict: + """ + Merges two tab-separated output files (Kaiju or Kraken format) based on read names. + Input files must be sorted by read name (e.g., using `sort -k2,2`). + + Args: + input_file1: Path to the first sorted input file. + input_file2: Path to the second sorted input file. + output_merged_file: Path to the output merged file. + verbose_output: If True, prints all columns from input files (otherwise only first three). + conflict_strategy: Strategy to resolve conflicting taxon identifiers for a classified read: + '1': Use taxon identifier from the first input file. + '2': Use taxon identifier from the second input file. + 'lca': Use the least common ancestor of the taxon identifiers (default). + 'lowest': Use the lowest ranking of the two taxon identifiers if they are + within the same lineage, otherwise use LCA. + nodes_dmp_file: Path to the NCBI taxonomy nodes.dmp file. Required if `conflict_strategy` + is 'lca' or 'lowest'. + precedence_by_score: If True, gives precedence to the classification result with the higher score + (requires 4th column in input files). + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + _validate_input_file(input_file1, "input_file1") + _validate_input_file(input_file2, "input_file2") + _validate_output_file(output_merged_file, "output_merged_file") + + if conflict_strategy in ["lca", "lowest"] and not nodes_dmp_file: + raise ValueError(f"nodes_dmp_file is required when conflict_strategy is '{conflict_strategy}'.") + if nodes_dmp_file: + _validate_input_file(nodes_dmp_file, "nodes_dmp_file") + + cmd = [ + "kaiju-mergeOutputs", + "-i", str(input_file1), + "-j", str(input_file2), + "-o", str(output_merged_file), + "-c", conflict_strategy, + ] + + if nodes_dmp_file: + cmd.extend(["-t", str(nodes_dmp_file)]) + if verbose_output: + cmd.append("-v") + if precedence_by_score: + cmd.append("-s") + + result = _run_command(cmd) + if "error" not in result: + result["output_files"].append(str(output_merged_file)) + return result + + +@mcp.tool() +def kaijux_search( + fmi_file: Path, + input_file: Path, + second_input_file: Optional[Path] = None, + output_file: Optional[Path] = None, + threads: int = 1, + mismatches: int = 3, + e_value: float = 0.01, + min_match_len: int = 11, + min_match_score: int = 65, + run_mode: Literal["greedy", "mem"] = "greedy", + enable_seg_filter: bool = True, + verbose_output: bool = False, +) -> dict: + """ + Searches translated nucleotide reads against a protein database without taxonomic classification. + Prints the name of the best matching database sequence. + + Args: + fmi_file: Path to the Kaiju database index (.fmi) file. + input_file: Path to the input FASTQ/FASTA file for single-end reads or first mate of paired-end reads. + (Nucleotide sequences). + second_input_file: Optional path to the second input FASTQ/FASTA file for paired-end reads. + output_file: Optional path to the output file. If not provided, output will be printed to STDOUT. + threads: Number of parallel threads to use. Must be >= 1. + mismatches: Number of allowed mismatches in Greedy mode. Must be >= 0. + e_value: E-value threshold for classification in Greedy mode. Must be > 0. + min_match_len: Minimum required match length in MEM mode. Must be >= 1. + min_match_score: Minimum required match score in Greedy mode. Must be >= 0. + run_mode: The classification run mode, either 'greedy' or 'mem'. + enable_seg_filter: If True, enables filtering of query sequences containing low-complexity regions using SEG. + Enabled by default. Set to False to disable. + verbose_output: If True, enables verbose output with additional columns. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + # Input validation + _validate_input_file(fmi_file, "fmi_file") + _validate_input_file(input_file, "input_file") + if second_input_file: + _validate_input_file(second_input_file, "second_input_file") + if output_file: + _validate_output_file(output_file, "output_file") + + if threads < 1: + raise ValueError("Number of threads must be at least 1.") + if mismatches < 0: + raise ValueError("Number of mismatches must be non-negative.") + if e_value <= 0: + raise ValueError("E-value must be greater than 0.") + if min_match_len < 1: + raise ValueError("Minimum match length must be at least 1.") + if min_match_score < 0: + raise ValueError("Minimum match score must be non-negative.") + + cmd = [ + "kaijux", + "-f", str(fmi_file), + "-i", str(input_file), + "-z", str(threads), + ] + + if second_input_file: + cmd.extend(["-j", str(second_input_file)]) + if output_file: + cmd.extend(["-o", str(output_file)]) + + # Run mode specific options + if run_mode == "greedy": + cmd.extend(["-e", str(mismatches)]) + cmd.extend(["-E", str(e_value)]) + cmd.extend(["-s", str(min_match_score)]) + elif run_mode == "mem": + cmd.extend(["-a", "mem"]) + cmd.extend(["-m", str(min_match_len)]) + + if not enable_seg_filter: + cmd.append("-X") + + if verbose_output: + cmd.append("-v") + + result = _run_command(cmd) + if output_file and "error" not in result: + result["output_files"].append(str(output_file)) + return result + + +@mcp.tool() +def kaijup_search( + fmi_file: Path, + input_file: Path, + second_input_file: Optional[Path] = None, + output_file: Optional[Path] = None, + threads: int = 1, + mismatches: int = 3, + e_value: float = 0.01, + min_match_len: int = 11, + min_match_score: int = 65, + run_mode: Literal["greedy", "mem"] = "greedy", + enable_seg_filter: bool = True, + verbose_output: bool = False, +) -> dict: + """ + Searches protein queries against a protein database without taxonomic classification. + Prints the name of the best matching database sequence. + + Args: + fmi_file: Path to the Kaiju database index (.fmi) file. + input_file: Path to the input FASTA file for single-end protein queries or first mate of paired-end. + second_input_file: Optional path to the second input FASTA file for paired-end protein queries. + output_file: Optional path to the output file. If not provided, output will be printed to STDOUT. + threads: Number of parallel threads to use. Must be >= 1. + mismatches: Number of allowed mismatches in Greedy mode. Must be >= 0. + e_value: E-value threshold for classification in Greedy mode. Must be > 0. + min_match_len: Minimum required match length in MEM mode. Must be >= 1. + min_match_score: Minimum required match score in Greedy mode. Must be >= 0. + run_mode: The classification run mode, either 'greedy' or 'mem'. + enable_seg_filter: If True, enables filtering of query sequences containing low-complexity regions using SEG. + Enabled by default. Set to False to disable. + verbose_output: If True, enables verbose output with additional columns. + + Returns: + A dictionary containing the command executed, stdout, stderr, and any output files. + """ + # Input validation + _validate_input_file(fmi_file, "fmi_file") + _validate_input_file(input_file, "input_file") + if second_input_file: + _validate_input_file(second_input_file, "second_input_file") + if output_file: + _validate_output_file(output_file, "output_file") + + if threads < 1: + raise ValueError("Number of threads must be at least 1.") + if mismatches < 0: + raise ValueError("Number of mismatches must be non-negative.") + if e_value <= 0: + raise ValueError("E-value must be greater than 0.") + if min_match_len < 1: + raise ValueError("Minimum match length must be at least 1.") + if min_match_score < 0: + raise ValueError("Minimum match score must be non-negative.") + + cmd = [ + "kaijup", + "-f", str(fmi_file), + "-i", str(input_file), + "-z", str(threads), + ] + + if second_input_file: + cmd.extend(["-j", str(second_input_file)]) + if output_file: + cmd.extend(["-o", str(output_file)]) + + # Run mode specific options + if run_mode == "greedy": + cmd.extend(["-e", str(mismatches)]) + cmd.extend(["-E", str(e_value)]) + cmd.extend(["-s", str(min_match_score)]) + elif run_mode == "mem": + cmd.extend(["-a", "mem"]) + cmd.extend(["-m", str(min_match_len)]) + + if not enable_seg_filter: + cmd.append("-X") + + if verbose_output: + cmd.append("-v") + + result = _run_command(cmd) + if output_file and "error" not in result: + result["output_files"].append(str(output_file)) + return result \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kaiju/app/kaiju_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kaiju/app/kaiju_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1b0cfc2940a9a769329c10e2090661504521d0bc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kaiju/app/kaiju_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kaiju/app/kaiju_server.py') +SERVER_NAME = 'biosci_kaiju' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kaiju/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kaiju/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kaiju/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kaiju/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kaiju/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..a1ad5b20456123671a7101563711cad806372e4c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kaiju/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-kaiju: + build: . + image: mcp-kaiju:latest + container_name: mcp-kaiju + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=kaiju + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kaiju/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kaiju/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..68716f85534f2bc339b296d5dad3f29d3b5c87be --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kaiju/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - kaiju + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kaiju/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kaiju/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kaiju/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kalign2/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kalign2/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d817ef4d35cdea14a55f427149a015850feb8d09 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kalign2/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install kalign2 via conda (e.g., from bioconda) +RUN conda install -c bioconda kalign2 -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/kalign2_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/kalign2_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/kalign2_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kalign2/app/kalign2_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kalign2/app/kalign2_server.py new file mode 100644 index 0000000000000000000000000000000000000000..52dee0aaf5f8ac8ffd35aa92e7d3dbdec7cff5f9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kalign2/app/kalign2_server.py @@ -0,0 +1,110 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +@mcp.tool() +def kalign2_align( + input_fasta: Path, + output_fasta: Path, +) -> Dict[str, Any]: + """ + Performs multiple sequence alignment using kalign2. + + This function aligns protein or DNA/RNA sequences from an input FASTA file + and writes the alignment to an output FASTA file. + + NOTE: The provided documentation for kalign2 (web docs extract and conda info) + did not include detailed command-line help or manual pages. Therefore, this + implementation assumes the most basic usage pattern: `kalign2 ` + which typically prints the alignment to standard output. The output is then + redirected to the specified `output_fasta` file. + + No specific parameters for gap penalties, scoring matrices, sequence type, + or output format could be extracted from the provided documentation. + A more comprehensive MCP tool would require the full `--help` output + or a detailed manual page for kalign2 to expose these options. + + Args: + input_fasta: Path to the input FASTA file containing sequences to align. + This file must exist and be readable. + output_fasta: Path to the output FASTA file where the aligned sequences + will be written. This file will be created or overwritten. + The parent directory will be created if it does not exist. + + Returns: + A dictionary containing the command executed, stdout, stderr, and + a list of generated output files. + + Raises: + ValueError: If `input_fasta` does not exist or is not a file. + subprocess.CalledProcessError: If kalign2 execution fails with a non-zero exit code. + FileNotFoundError: If the `kalign2` executable is not found in the system's PATH. + """ + # Input validation + if not isinstance(input_fasta, Path): + raise TypeError(f"input_fasta must be a Path object, got {type(input_fasta)}") + if not input_fasta.is_file(): + raise ValueError(f"Input FASTA file not found or is not a file: {input_fasta}") + + if not isinstance(output_fasta, Path): + raise TypeError(f"output_fasta must be a Path object, got {type(output_fasta)}") + + # Ensure output directory exists + output_fasta.parent.mkdir(parents=True, exist_ok=True) + + command = ["kalign2", str(input_fasta)] + + stdout_content = "" + stderr_content = "" + output_files: List[Path] = [] + + try: + # Execute kalign2. Assuming it prints the alignment to stdout by default. + # Redirect stdout to the specified output_fasta file. + with open(output_fasta, "w") as outfile: + process = subprocess.run( + command, + stdout=outfile, # Redirect stdout to the output file + stderr=subprocess.PIPE, + check=True, + text=True, + encoding="utf-8", + ) + + # Since stdout is redirected, process.stdout will be empty. + # We provide a descriptive message for stdout_content. + stdout_content = f"Alignment successfully written to {output_fasta}" + stderr_content = process.stderr + output_files.append(output_fasta) + + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "kalign2 executable not found. Please ensure it is installed and in your system's PATH.", + "output_files": [], + "error": "kalign2 executable not found.", + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, # This will be empty if stdout was redirected + "stderr": e.stderr, + "output_files": [], + "error": f"kalign2 execution failed with exit code {e.returncode}. Stderr: {e.stderr}", + } + except Exception as e: + return { + "command_executed": " ".join(command), + "stdout": stdout_content, + "stderr": stderr_content, + "output_files": [], + "error": f"An unexpected error occurred during kalign2 execution: {str(e)}", + } + + return { + "command_executed": " ".join(command), + "stdout": stdout_content, + "stderr": stderr_content, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kalign2/app/kalign2_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kalign2/app/kalign2_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8ce228b12b389a72f4e8534688a9097d2590c1b5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kalign2/app/kalign2_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kalign2/app/kalign2_server.py') +SERVER_NAME = 'biosci_kalign2' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kalign2/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kalign2/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kalign2/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kalign2/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kalign2/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d051ea54c55891614f7f2b8586113f748cf13278 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kalign2/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-kalign2: + build: . + image: mcp-kalign2:latest + container_name: mcp-kalign2 + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=kalign2 + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kalign2/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kalign2/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8cb94499dd106cee9e6d985c91ed3388171d77ee --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kalign2/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - kalign2 + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kalign2/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kalign2/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kalign2/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kallisto/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kallisto/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..be0ff34dfe4e8ccad8b8a12f7c1db222cd600347 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kallisto/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install kallisto via conda (e.g., from bioconda) +RUN conda install -c bioconda kallisto -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/kallisto_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/kallisto_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/kallisto_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kallisto/app/kallisto_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kallisto/app/kallisto_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b89f523a7e8dafc49977479517c1355a3b1bf419 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kallisto/app/kallisto_server.py @@ -0,0 +1,456 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union + +@mcp.tool() +def kallisto_index( + fasta_files: List[str], + index: str, + kmer_size: int = 31, + d_list: Optional[str] = None, + make_unique: bool = False, + aa: bool = False, + distinguish: bool = False, + threads: int = 1, + min_size: Optional[int] = None, + ec_max_size: Optional[int] = None, +): + """ + Builds a kallisto index from a FASTA formatted file of target sequences. + + :param fasta_files: List of FASTA files (plaintext or gzipped) to build the index from. + :param index: Filename for the kallisto index to be constructed. + :param kmer_size: k-mer (odd) length (default: 31, max value: 31). + :param d_list: Path to a FASTA-file containing sequences to mask from quantification. + :param make_unique: Replace repeated target names with unique names. + :param aa: Generate index from a FASTA-file containing amino acid sequences. + :param distinguish: Generate index where sequences are distinguished by the sequence name. + :param threads: Number of threads to use (default: 1). + :param min_size: Length of minimizers (default: automatically chosen). + :param ec_max_size: Maximum number of targets in an equivalence class (default: no maximum). + """ + # Validation + if kmer_size > 31 or kmer_size % 2 == 0: + return {"error": "kmer_size must be an odd integer <= 31"} + + for f in fasta_files: + if not Path(f).exists(): + return {"error": f"Input FASTA file not found: {f}"} + + # kallisto index is single-threaded in common releases and does not accept -t. + # Keep the threads parameter for API compatibility, but do not pass it here. + cmd = ["kallisto", "index", "-i", index, "-k", str(kmer_size)] + + if d_list: + cmd.extend(["-d", d_list]) + if make_unique: + cmd.append("--make-unique") + if aa: + cmd.append("--aa") + if distinguish: + cmd.append("--distinguish") + if min_size is not None: + cmd.extend(["-m", str(min_size)]) + if ec_max_size is not None: + cmd.extend(["-e", str(ec_max_size)]) + + cmd.extend(fasta_files) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [index] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def kallisto_quant( + fastq_files: List[str], + index: str, + output_dir: str, + bootstrap_samples: int = 0, + seed: int = 42, + plaintext: bool = False, + single: bool = False, + single_overhang: bool = False, + fr_stranded: bool = False, + rf_stranded: bool = False, + fragment_length: Optional[float] = None, + sd: Optional[float] = None, + threads: int = 1, + bias: bool = False, + fusion: bool = False, + pseudobam: bool = False, + genomebam: bool = False, + gtf: Optional[str] = None, + chromosomes: Optional[str] = None +): + """ + Runs the kallisto quantification algorithm on RNA-Seq reads. + + :param fastq_files: List of FASTQ files. For paired-end, provide pairs (e.g., [R1, R2]). + :param index: Filename for the kallisto index to be used. + :param output_dir: Directory to write output to. + :param bootstrap_samples: Number of bootstrap samples (default: 0). + :param seed: Seed for the bootstrap sampling (default: 42). + :param plaintext: Output plaintext instead of HDF5. + :param single: Quantify single-end reads. + :param single_overhang: Include reads where unobserved rest of fragment is predicted to lie outside a transcript. + :param fr_stranded: Strand specific reads, first read forward. + :param rf_stranded: Strand specific reads, first read reverse. + :param fragment_length: Estimated average fragment length (Required for --single). + :param sd: Estimated standard deviation of fragment length (Required for --single). + :param threads: Number of threads to use (default: 1). + :param bias: Learn parameters for a model of sequences specific bias (Legacy/0.48.0). + :param fusion: Look for reads from fusion genes (Legacy/0.48.0). + :param pseudobam: Output pseudoalignments to a BAM file (Legacy/0.48.0). + :param genomebam: Project transcript alignments to genome coordinates (Legacy/0.48.0). + :param gtf: GTF file for genomebam (Required if --genomebam is used). + :param chromosomes: Length of genomic chromosomes for BAM header. + """ + # Validation + if not Path(index).exists(): + return {"error": f"Index file not found: {index}"} + + if single: + if fragment_length is None or sd is None: + return {"error": "fragment_length (-l) and sd (-s) are required when using --single"} + + if genomebam and not gtf: + return {"error": "GTF file (--gtf) is required when using --genomebam"} + + Path(output_dir).mkdir(parents=True, exist_ok=True) + + cmd = ["kallisto", "quant", "-i", index, "-o", output_dir, "-b", str(bootstrap_samples), "--seed", str(seed), "-t", str(threads)] + + if plaintext: cmd.append("--plaintext") + if single: cmd.append("--single") + if single_overhang: cmd.append("--single-overhang") + if fr_stranded: cmd.append("--fr-stranded") + if rf_stranded: cmd.append("--rf-stranded") + if fragment_length is not None: cmd.extend(["-l", str(fragment_length)]) + if sd is not None: cmd.extend(["-s", str(sd)]) + if bias: cmd.append("--bias") + if fusion: cmd.append("--fusion") + if pseudobam: cmd.append("--pseudobam") + if genomebam: cmd.append("--genomebam") + if gtf: cmd.extend(["--gtf", gtf]) + if chromosomes: cmd.extend(["--chromosomes", chromosomes]) + + cmd.extend(fastq_files) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_directory": output_dir + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def kallisto_bus( + fastq_files: List[str], + index: str, + output_dir: str, + technology: str, + batch: Optional[str] = None, + threads: int = 1, + bam: bool = False, + num: bool = False, + num_reads: Optional[int] = None, + tag: Optional[str] = None, + fr_stranded: bool = False, + rf_stranded: bool = False, + unstranded: bool = False, + paired: bool = False, + long_reads: bool = False, + aa: bool = False, + inleaved: bool = False, + batch_barcodes: bool = False, + verbose: bool = False +): + """ + Generates BUS files for single-cell sequencing data. + + :param fastq_files: List of FASTQ files. + :param index: Filename for the kallisto index to be used for pseudoalignment. + :param output_dir: Directory to write output to. + :param technology: Single-cell technology used (e.g., 10xv2, 10xv3, or custom format). + :param batch: Process files listed in a batch file. + :param threads: Number of threads to use (default: 1). + :param bam: Input file is a BAM file. + :param num: Output number of read in flag column (incompatible with --bam). + :param num_reads: Maximum number of reads to process from supplied input. + :param tag: 5' tag sequence to identify UMI reads for certain technologies. + :param fr_stranded: Strand specific reads for UMI-tagged reads, first read forward. + :param rf_stranded: Strand specific reads for UMI-tagged reads, first read reverse. + :param unstranded: Treat all read as non-strand-specific. + :param paired: Treat reads as paired. + :param long_reads: Treat reads as long. + :param aa: Align to index generated from amino acid sequences. + :param inleaved: Specifies that input is an interleaved FASTQ file. + :param batch_barcodes: Records both batch and extracted barcode in BUS file. + :param verbose: Print out progress information every 1M processed reads. + """ + if not Path(index).exists(): + return {"error": f"Index file not found: {index}"} + + Path(output_dir).mkdir(parents=True, exist_ok=True) + + cmd = ["kallisto", "bus", "-i", index, "-o", output_dir, "-x", technology, "-t", str(threads)] + + if batch: cmd.extend(["-B", batch]) + if bam: cmd.append("-b") + if num: cmd.append("-n") + if num_reads is not None: cmd.extend(["-N", str(num_reads)]) + if tag: cmd.extend(["-T", tag]) + if fr_stranded: cmd.append("--fr-stranded") + if rf_stranded: cmd.append("--rf-stranded") + if unstranded: cmd.append("--unstranded") + if paired: cmd.append("--paired") + if long_reads: cmd.append("--long") + if aa: cmd.append("--aa") + if inleaved: cmd.append("--inleaved") + if batch_barcodes: cmd.append("--batch-barcodes") + if verbose: cmd.append("--verbose") + + cmd.extend(fastq_files) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_directory": output_dir + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def kallisto_quant_tcc( + output_dir: str, + index: Optional[str] = None, + txnames: Optional[str] = None, + ec_file: Optional[str] = None, + fragment_file: Optional[str] = None, + long_reads: bool = False, + platform: Optional[str] = None, + fragment_length: Optional[float] = None, + sd: Optional[float] = None, + threads: int = 1, + genemap: Optional[str] = None, + gtf: Optional[str] = None, + bootstrap_samples: int = 0, + matrix_to_files: bool = False, + matrix_to_directories: bool = False, + seed: int = 42, + plaintext: bool = False +): + """ + Runs the EM algorithm to produce estimated counts from a transcript-compatibility-counts matrix file. + + :param output_dir: Directory to write output to. + :param index: Filename for the kallisto index (required if txnames not supplied). + :param txnames: File with names of transcripts (required if index not supplied). + :param ec_file: File containing equivalence classes. + :param fragment_file: File containing fragment length distribution. + :param long_reads: Use version of EM for long reads. + :param platform: [PacBio or ONT] used for sequencing. + :param fragment_length: Estimated average fragment length. + :param sd: Estimated standard deviation of fragment length. + :param threads: Number of threads to use (default: 1). + :param genemap: File for mapping transcripts to genes. + :param gtf: GTF file for transcriptome information. + :param bootstrap_samples: Number of bootstrap samples (default: 0). + :param matrix_to_files: Reorganize matrix output into abundance tsv files. + :param matrix_to_directories: Reorganize matrix output into abundance tsv files across multiple directories. + :param seed: Seed for the bootstrap sampling (default: 42). + :param plaintext: Output plaintext only, not HDF5. + """ + if not index and not txnames: + return {"error": "Either index (-i) or txnames (-T) must be provided."} + + Path(output_dir).mkdir(parents=True, exist_ok=True) + + cmd = ["kallisto", "quant-tcc", "-o", output_dir, "-t", str(threads), "-b", str(bootstrap_samples), "--seed", str(seed)] + + if index: cmd.extend(["-i", index]) + if txnames: cmd.extend(["-T", txnames]) + if ec_file: cmd.extend(["-e", ec_file]) + if fragment_file: cmd.extend(["-f", fragment_file]) + if long_reads: cmd.append("--long") + if platform: cmd.extend(["-p", platform]) + if fragment_length is not None: cmd.extend(["-l", str(fragment_length)]) + if sd is not None: cmd.extend(["-s", str(sd)]) + if genemap: cmd.extend(["-g", genemap]) + if gtf: cmd.extend(["-G", gtf]) + if matrix_to_files: cmd.append("--matrix-to-files") + if matrix_to_directories: cmd.append("--matrix-to-directories") + if plaintext: cmd.append("--plaintext") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_directory": output_dir + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def kallisto_h5dump( + h5_file: str, + output_dir: str +): + """ + Converts HDF5-formatted results (abundance.h5) to plaintext. + + :param h5_file: Path to the abundance.h5 file. + :param output_dir: Directory to write output to. + """ + if not Path(h5_file).exists(): + return {"error": f"HDF5 file not found: {h5_file}"} + + Path(output_dir).mkdir(parents=True, exist_ok=True) + + cmd = ["kallisto", "h5dump", "-o", output_dir, h5_file] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_directory": output_dir + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def kallisto_inspect( + index_file: str, + threads: int = 1 +): + """ + Inspects and gives information about a kallisto index. + + :param index_file: Path to the kallisto index file. + :param threads: Number of threads to use. + """ + if not Path(index_file).exists(): + return {"error": f"Index file not found: {index_file}"} + + cmd = ["kallisto", "inspect", index_file, "-t", str(threads)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def kallisto_version(): + """Prints kallisto version information.""" + cmd = ["kallisto", "version"] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return {"version": result.stdout.strip()} + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def kallisto_cite(): + """Prints citation information for kallisto.""" + cmd = ["kallisto", "cite"] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return {"citation": result.stdout.strip()} + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} + +@mcp.tool() +def kallisto_bus_list_technologies(): + """Lists all single-cell technologies supported by kallisto bus.""" + cmd = ["kallisto", "bus", "-l"] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return {"supported_technologies": result.stdout} + except subprocess.CalledProcessError as e: + # kallisto bus -l might return exit code 0 or 1 depending on version + return {"supported_technologies": e.stdout if e.stdout else e.stderr} + +@mcp.tool() +def kallisto_merge( + output_dir: str, + input_dirs: List[str] +): + """ + Merges several batch runs. + + :param output_dir: Directory to write merged output to. + :param input_dirs: List of directories containing kallisto results to merge. + """ + Path(output_dir).mkdir(parents=True, exist_ok=True) + + cmd = ["kallisto", "merge", "-o", output_dir] + cmd.extend(input_dirs) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_directory": output_dir + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kallisto/app/kallisto_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kallisto/app/kallisto_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..b9626ad27988d6af4e3364d5cfcd07ab45708d7a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kallisto/app/kallisto_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kallisto/app/kallisto_server.py') +SERVER_NAME = 'biosci_kallisto' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kallisto/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kallisto/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kallisto/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kallisto/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kallisto/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..ae6743240ef416df1b2d63ae865bc94a2e88660a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kallisto/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-kallisto: + build: . + image: mcp-kallisto:latest + container_name: mcp-kallisto + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=kallisto + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kallisto/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kallisto/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..67ed8c709fefd02655e0912c4987f578b8b1a42b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kallisto/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - kallisto + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kallisto/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kallisto/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kallisto/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kb-python/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kb-python/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..048ebcc61c1a8d3b158d40d450cd92b24573b7c0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kb-python/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install kb-python via conda (e.g., from bioconda) +RUN conda install -c bioconda kb-python -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY kb-python_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/kb-python_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/kb-python_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kb-python/app/kb-python_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kb-python/app/kb-python_server.py new file mode 100644 index 0000000000000000000000000000000000000000..99dfb90f7051c06853165889315e583b88f3e160 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kb-python/app/kb-python_server.py @@ -0,0 +1,298 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union +import os + +@mcp.tool() +def kb_info(): + """ + Display kb-python package and citation information, including versions of + kallisto and bustools and their installation locations. + """ + cmd = ["kb", "info"] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def kb_list(): + """ + List all supported single-cell technologies/assays for kb-python. + """ + cmd = ["kb", "--list"] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def kb_compile(): + """ + Compile kallisto and bustools binaries from source. + Note: This is usually not required as binaries are included with the package. + """ + cmd = ["kb", "compile"] + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def kb_ref( + index_path: str, + t2g_path: str, + fasta_path: Optional[str] = None, + species: Optional[str] = None, + genome_fasta: Optional[str] = None, + genome_annotation: Optional[str] = None, + workflow: str = "standard", + feature_barcodes: Optional[str] = None, + tmp_dir: Optional[str] = None, + keep_tmp: bool = False, + overwrite: bool = False +): + """ + Build a kallisto index and transcript-to-gene mapping. + + Args: + index_path: Path to the generated index file. + t2g_path: Path to the generated transcript-to-gene mapping file. + fasta_path: Path to the generated transcriptome FASTA file. + species: Species name to download pre-built reference (e.g., 'human', 'mouse'). + genome_fasta: Path to the genome FASTA file (required if species is not provided). + genome_annotation: Path to the genome GTF file (required if species is not provided). + workflow: The workflow to use (standard, lamanno, nucleus, kite). Default is 'standard'. + feature_barcodes: Path to the feature barcodes file (required for 'kite' workflow). + tmp_dir: Path to temporary directory. + keep_tmp: Whether to keep temporary files. + overwrite: Whether to overwrite existing files. + """ + cmd = ["kb", "ref", "-i", index_path, "-g", t2g_path] + + if fasta_path: + cmd.extend(["-f1", fasta_path]) + if species: + cmd.extend(["-d", species]) + if workflow != "standard": + cmd.extend(["--workflow", workflow]) + if tmp_dir: + cmd.extend(["--tmp", tmp_dir]) + if keep_tmp: + cmd.append("--keep-tmp") + if overwrite: + cmd.append("--overwrite") + + # Positional arguments handling + if workflow == "kite": + if not feature_barcodes: + return {"error": "feature_barcodes is required for kite workflow"} + if not Path(feature_barcodes).exists(): + return {"error": f"Feature barcodes file not found: {feature_barcodes}"} + cmd.append(feature_barcodes) + elif not species: + if not genome_fasta or not genome_annotation: + return {"error": "genome_fasta and genome_annotation are required if species is not provided"} + if not Path(genome_fasta).exists(): + return {"error": f"Genome FASTA not found: {genome_fasta}"} + if not Path(genome_annotation).exists(): + return {"error": f"Genome annotation not found: {genome_annotation}"} + cmd.extend([genome_fasta, genome_annotation]) + + 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": [index_path, t2g_path] + ([fasta_path] if fasta_path else []) + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def kb_count( + index_path: str, + t2g_path: str, + output_dir: str, + technology: str, + fastqs: List[str], + workflow: str = "standard", + h5ad: bool = False, + loom: bool = False, + tcc: bool = False, + mm: bool = False, + filter: bool = False, + tmp_dir: Optional[str] = None, + keep_tmp: bool = False, + overwrite: bool = False, + threads: int = 8 +): + """ + Generate count matrices from a set of single-cell FASTQ files. + + Args: + index_path: Path to the kallisto index. + t2g_path: Path to the transcript-to-gene mapping. + output_dir: Directory where output files will be saved. + technology: Single-cell technology used (e.g., 10xv3, 10xv2, dropseq, etc.). + fastqs: List of paths to FASTQ files. + workflow: The workflow to use (standard, lamanno, nucleus, kite). Default is 'standard'. + h5ad: Export result as h5ad file. + loom: Export result as loom file. + tcc: Generate a TCC (Transcript Compatibility Count) matrix. + mm: Include multi-mapping reads. + filter: Filter the count matrix (bustools filter). + tmp_dir: Path to temporary directory. + keep_tmp: Whether to keep temporary files. + overwrite: Whether to overwrite existing files in the output directory. + threads: Number of threads to use. Default is 8. + """ + # Validation + if not Path(index_path).exists(): + return {"error": f"Index file not found: {index_path}"} + if not Path(t2g_path).exists(): + return {"error": f"T2G file not found: {t2g_path}"} + for f in fastqs: + if not Path(f).exists(): + return {"error": f"FASTQ file not found: {f}"} + + cmd = [ + "kb", "count", + "-i", index_path, + "-g", t2g_path, + "-o", output_dir, + "-x", technology, + "-t", str(threads) + ] + + if workflow != "standard": + cmd.extend(["--workflow", workflow]) + if h5ad: + cmd.append("--h5ad") + if loom: + cmd.append("--loom") + if tcc: + cmd.append("--tcc") + if mm: + cmd.append("--mm") + if filter: + cmd.append("--filter") + if tmp_dir: + cmd.extend(["--tmp", tmp_dir]) + if keep_tmp: + cmd.append("--keep-tmp") + if overwrite: + cmd.append("--overwrite") + + cmd.extend(fastqs) + + try: + # Ensure output directory exists or will be created by kb + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + # Identify potential output files based on flags + output_files = [str(p) for p in Path(output_dir).rglob("*") if p.is_file()] + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_dir": output_dir, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def kb_extract( + index_path: str, + output_path: str, + bus_path: str, + tmp_dir: Optional[str] = None, + keep_tmp: bool = False +): + """ + Extract reads that were pseudoaligned to specific genes/transcripts + (or extract all reads that were / were not pseudoaligned). + + Args: + index_path: Path to the kallisto index. + output_path: Path to the output BUS file. + bus_path: Path to the input BUS file. + tmp_dir: Path to temporary directory. + keep_tmp: Whether to keep temporary files. + """ + if not Path(index_path).exists(): + return {"error": f"Index file not found: {index_path}"} + if not Path(bus_path).exists(): + return {"error": f"Input BUS file not found: {bus_path}"} + + cmd = [ + "kb", "extract", + "-i", index_path, + "-o", output_path + ] + + if tmp_dir: + cmd.extend(["--tmp", tmp_dir]) + if keep_tmp: + cmd.append("--keep-tmp") + + cmd.append(bus_path) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_path] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kb-python/app/kb-python_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kb-python/app/kb-python_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..793e81709cc6fa1124bd1c8ca73711e44c582b1a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kb-python/app/kb-python_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kb-python/app/kb-python_server.py') +SERVER_NAME = 'biosci_kb_python' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kb-python/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kb-python/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..56e365874d51c5a442ac56d8855d3c3ad27294df --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kb-python/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-kb-python: + build: . + image: mcp-kb-python:latest + container_name: mcp-kb-python + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=kb-python + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kb-python/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kb-python/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..07df37c2c49abd1de0da3095ac1fd6d1d21ec872 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kb-python/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - kb-python + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kb-python/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kb-python/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kb-python/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_khipu-metabolomics/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_khipu-metabolomics/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..64f6d2c104e42bc06e2e44255378eac299c6baaf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_khipu-metabolomics/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install khipu-metabolomics via conda (e.g., from bioconda) +RUN conda install -c bioconda khipu-metabolomics -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY khipu-metabolomics_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/khipu-metabolomics_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/khipu-metabolomics_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_khipu-metabolomics/app/khipu-metabolomics_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_khipu-metabolomics/app/khipu-metabolomics_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5dda203e91ba5e16e0c358d65d32d0a558970b40 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_khipu-metabolomics/app/khipu-metabolomics_server.py @@ -0,0 +1,116 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +@mcp.tool() +def khipu_annotate( + input_file: Path, + output_prefix: str, + mode: Optional[str] = None, + ppm: Optional[float] = None, + rtol: Optional[float] = None, + start_col: Optional[int] = None, + end_col: Optional[int] = None, +): + """ + Annotates metabolomics features into empirical compounds (empCpds). + + This tool takes a feature table from a preprocessing tool as input and + annotates degenerate ions in relation to the original compound to infer + neutral mass. It identifies isotopic and adduct relationships to group features. + The results are saved to a JSON file and a tab-delimited file. + + Args: + input_file: Path to the input feature table file (tab-delimited). + output_prefix: Prefix for the output files. Two files will be generated: + .json and .tsv. + mode: Mode of ionization, 'pos' or 'neg'. + ppm: Mass precision in ppm (parts per million) for m/z tolerance. + rtol: Tolerance of retention time match, in an arbitrary unit dependent + on the preprocessing tool. + start_col: Start column for intensity data in the input table. + end_col: End column for intensity data in the input table. + """ + # 1. Input Validation + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + if mode and mode not in ["pos", "neg"]: + raise ValueError("Mode must be either 'pos' or 'neg'.") + + if ppm is not None and ppm <= 0: + raise ValueError("PPM must be a positive number.") + + if rtol is not None and rtol < 0: + raise ValueError("RTOL (retention time tolerance) cannot be a negative number.") + + if start_col is not None and start_col <= 0: + raise ValueError("Start column must be a positive integer.") + + if end_col is not None and end_col <= 0: + raise ValueError("End column must be a positive integer.") + + if start_col is not None and end_col is not None and end_col < start_col: + raise ValueError("End column must be greater than or equal to the start column.") + + # 2. Command Construction & Output Handling + with tempfile.TemporaryDirectory() as temp_dir: + output_path_prefix = Path(temp_dir) / output_prefix + + cmd = [ + "khipu", + "-i", str(input_file), + "-o", str(output_path_prefix), + ] + + if mode: + cmd.extend(["-m", mode]) + if ppm is not None: + cmd.extend(["--ppm", str(ppm)]) + if rtol is not None: + cmd.extend(["--rtol", str(rtol)]) + if start_col is not None: + cmd.extend(["-s", str(start_col)]) + if end_col is not None: + cmd.extend(["-e", str(end_col)]) + + command_str = " ".join(cmd) + + # 3. Subprocess Execution + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + encoding='utf-8' + ) + except FileNotFoundError: + raise RuntimeError("khipu executable not found. Please ensure khipu-metabolomics is installed and in your PATH.") + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + "output_files": [] + } + + # 4. Collect Output Files + output_files_generated: List[str] = [] + json_output = output_path_prefix.with_suffix(".json") + tsv_output = output_path_prefix.with_suffix(".tsv") + + if json_output.exists(): + output_files_generated.append(str(json_output)) + if tsv_output.exists(): + output_files_generated.append(str(tsv_output)) + + # 5. Return Structured Output + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files_generated + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_khipu-metabolomics/app/khipu-metabolomics_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_khipu-metabolomics/app/khipu-metabolomics_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..548eb6d3a2e70f4d1119f22a552a5ecddc1bd9cf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_khipu-metabolomics/app/khipu-metabolomics_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_khipu-metabolomics/app/khipu-metabolomics_server.py') +SERVER_NAME = 'biosci_khipu_metabolomics' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_khipu-metabolomics/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_khipu-metabolomics/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..7040be92dee6f2c41b94e107e1a883bf1323d878 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_khipu-metabolomics/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-khipu-metabolomics: + build: . + image: mcp-khipu-metabolomics:latest + container_name: mcp-khipu-metabolomics + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=khipu-metabolomics + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_khipu-metabolomics/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_khipu-metabolomics/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..82f3ae22a998036c0e2f660e5682de2a2f16ea3d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_khipu-metabolomics/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - khipu-metabolomics + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_khipu-metabolomics/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_khipu-metabolomics/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_khipu-metabolomics/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kma/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kma/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kma/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmc/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmc/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5cc2d4d814c1452c2c850d0f9ad86514efabe576 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmc/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install kmc via conda (e.g., from bioconda) +RUN conda install -c bioconda kmc -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/kmc_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/kmc_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/kmc_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmc/app/kmc_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmc/app/kmc_server.py new file mode 100644 index 0000000000000000000000000000000000000000..963b3c3b840403adde98775518ab0a6eca78ff63 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmc/app/kmc_server.py @@ -0,0 +1,219 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# @mcp.tool() decorator is not needed in the final code, as per instructions. +# This is a placeholder for the MCP environment. +def tool_decorator(func): + return func + +@tool_decorator +def kmc( + input_path: Path, + output_prefix: Path, + working_directory: Path, + verbose: bool = False, + kmer_length: int = 25, + max_ram_gb: int = 12, + strict_memory: bool = False, + homopolymer_compressed: bool = False, + signature_length: int = 9, + input_format: str = "q", + min_count: int = 2, + max_count: int = 255, + max_count_high: float = 1e9, + no_canonical: bool = False, + ram_only: bool = False, + num_bins: Optional[int] = None, + threads: Optional[int] = None, + fastq_threads: Optional[int] = None, + splitting_threads: Optional[int] = None, + stage2_threads: Optional[int] = None, + json_summary: Optional[Path] = None, + without_output: bool = False, + output_format: str = "kmc", + hide_progress: bool = False, + estimate_only: bool = False, + optimize_output_size: bool = False, +): + """ + Counts k-mers from sequence data using KMC (K-Mer Counter). + + This tool takes a sequence file (or a list of files) and counts the occurrences + of k-mers of a specified length. The results are stored in a KMC database. + + Args: + input_path: Path to a single input file or a file containing a list of + input files (prefixed with '@'). + output_prefix: The path and prefix for the output database files. + KMC will create .kmc_pre and .kmc_suf. + working_directory: Path to a directory for temporary files. + verbose: Show all parameter settings. + kmer_length: K-mer length (k from 1 to 256). + max_ram_gb: Max amount of RAM in GB (from 1 to 1024). + strict_memory: Use strict memory mode (memory limit will not be exceeded). + homopolymer_compressed: Count homopolymer compressed k-mers (experimental). + signature_length: Signature length (5-11). + input_format: Input format: 'a' (FASTA), 'q' (FASTQ), 'm' (multi FASTA), + 'bam' (BAM), or 'kmc' (KMC). + min_count: Exclude k-mers occurring less than this value. + max_count: Maximal value of a counter. + max_count_high: Exclude k-mers occurring more than this value. + no_canonical: Turn off transformation of k-mers into canonical form. + ram_only: Turn on RAM-only mode. + num_bins: Number of bins. + threads: Total number of threads. + fastq_threads: Number of FASTQ reading threads. + splitting_threads: Number of splitting threads. + stage2_threads: Number of threads for the 2nd stage. + json_summary: Path to save the execution summary in JSON format. + without_output: Do not generate output files. + output_format: Output format: 'kmc' or 'kff'. + hide_progress: Hide percentage progress. + estimate_only: Only estimate histogram of k-mers occurrences. + optimize_output_size: Optimize output database size (may increase running time). + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not input_path.exists(): + raise FileNotFoundError(f"Input file not found: {input_path}") + + if not (1 <= kmer_length <= 256): + raise ValueError("k-mer length must be between 1 and 256.") + + if not (1 <= max_ram_gb <= 1024): + raise ValueError("Max RAM must be between 1 and 1024 GB.") + + if signature_length not in [5, 6, 7, 8, 9, 10, 11]: + raise ValueError("Signature length must be one of: 5, 6, 7, 8, 9, 10, 11.") + + valid_input_formats = ['a', 'q', 'm', 'bam', 'kmc'] + if input_format not in valid_input_formats: + raise ValueError(f"Input format must be one of: {valid_input_formats}") + + valid_output_formats = ['kmc', 'kff'] + if output_format not in valid_output_formats: + raise ValueError(f"Output format must be one of: {valid_output_formats}") + + if min_count < 1: + raise ValueError("min_count must be a positive integer.") + if max_count < 1: + raise ValueError("max_count must be a positive integer.") + if max_count_high < 1: + raise ValueError("max_count_high must be a positive number.") + + if num_bins is not None and num_bins < 1: + raise ValueError("num_bins must be a positive integer.") + if threads is not None and threads < 1: + raise ValueError("threads must be a positive integer.") + if fastq_threads is not None and fastq_threads < 1: + raise ValueError("fastq_threads must be a positive integer.") + if splitting_threads is not None and splitting_threads < 1: + raise ValueError("splitting_threads must be a positive integer.") + if stage2_threads is not None and stage2_threads < 1: + raise ValueError("stage2_threads must be a positive integer.") + + # --- Path Handling --- + working_directory.mkdir(parents=True, exist_ok=True) + output_prefix.parent.mkdir(parents=True, exist_ok=True) + if json_summary: + json_summary.parent.mkdir(parents=True, exist_ok=True) + + # --- Command Construction --- + cmd = ["kmc"] + + # Boolean flags + if verbose: + cmd.append("-v") + if strict_memory: + cmd.append("-sm") + if homopolymer_compressed: + cmd.append("-hc") + if no_canonical: + cmd.append("-b") + if ram_only: + cmd.append("-r") + if without_output: + cmd.append("-w") + if hide_progress: + cmd.append("-hp") + if estimate_only: + cmd.append("-e") + if optimize_output_size: + cmd.append("--opt-out-size") + + # Parameters with values + cmd.append(f"-k{kmer_length}") + cmd.append(f"-m{max_ram_gb}") + cmd.append(f"-p{signature_length}") + cmd.append(f"-f{input_format}") + cmd.append(f"-ci{min_count}") + cmd.append(f"-cs{max_count}") + cmd.append(f"-cx{max_count_high}") + cmd.append(f"-o{output_format}") + + # Optional parameters + if num_bins is not None: + cmd.append(f"-n{num_bins}") + if threads is not None: + cmd.append(f"-t{threads}") + if fastq_threads is not None: + cmd.append(f"-sf{fastq_threads}") + if splitting_threads is not None: + cmd.append(f"-sp{splitting_threads}") + if stage2_threads is not None: + cmd.append(f"-sr{stage2_threads}") + if json_summary is not None: + cmd.append(f"-j{json_summary}") + + # Positional arguments + cmd.extend([str(input_path), str(output_prefix), str(working_directory)]) + + # --- Subprocess Execution --- + command_executed = " ".join(cmd) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + "output_files": [], + } + + # --- Structured Result Return --- + output_files = [] + if not without_output and not estimate_only: + # KMC creates two files for its database + db_prefix = output_prefix.with_suffix(f".{output_prefix.name}.kmc_pre") + db_suffix = output_prefix.with_suffix(f".{output_prefix.name}.kmc_suf") + + # A more robust way to handle output naming + final_prefix_path = output_prefix.parent / output_prefix.name + + out_pre = Path(f"{final_prefix_path}.kmc_pre") + out_suf = Path(f"{final_prefix_path}.kmc_suf") + + if out_pre.exists(): + output_files.append(str(out_pre)) + if out_suf.exists(): + output_files.append(str(out_suf)) + + if json_summary and json_summary.exists(): + output_files.append(str(json_summary)) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmc/app/kmc_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmc/app/kmc_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8234539316871045e5cb1a529a97f8ff823b02a7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmc/app/kmc_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmc/app/kmc_server.py') +SERVER_NAME = 'biosci_kmc' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmc/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmc/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmc/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmc/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmc/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..658aff4b79b367241fc6a6af7a63fc11c25e8e5f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmc/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-kmc: + build: . + image: mcp-kmc:latest + container_name: mcp-kmc + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=kmc + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmc/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmc/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bda0bbaf0996d1c62bdb166aba0ed5f2b99cda9b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmc/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - kmc + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmc/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmc/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmc/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmer-jellyfish/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmer-jellyfish/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8e77081917949744f665e037dcca082150d367c7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmer-jellyfish/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install kmer-jellyfish via conda (e.g., from bioconda) +RUN conda install -c bioconda kmer-jellyfish -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/kmer-jellyfish_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/kmer-jellyfish_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/kmer-jellyfish_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmer-jellyfish/app/kmer-jellyfish_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmer-jellyfish/app/kmer-jellyfish_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a5cf2bca3b1845f69e4cf305f5242227cb640bed --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmer-jellyfish/app/kmer-jellyfish_server.py @@ -0,0 +1,446 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# MCP-ready Python functions for the kmer-jellyfish tool + +def _run_jellyfish_command(cmd: List[str], output_files_dict: dict) -> dict: + """Helper function to execute a jellyfish command and handle output.""" + 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": output_files_dict, + } + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "jellyfish command not found. Please ensure it is in your PATH.", + "error": "Executable not found.", + "output_files": {}, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Jellyfish command failed with exit code {e.returncode}", + "output_files": {}, + } + + +@mcp.tool() +def jellyfish_count( + input_files: List[Path], + mer_len: int, + size: str, + output_file: Optional[Path] = None, + threads: int = 1, + counter_len: int = 7, + both_strands: bool = False, + quality_cutoff: int = 0, + quality_start: int = 33, + bloom_filter_if: Optional[Path] = None, + text_input: bool = False, + out_counter_len: Optional[int] = None, + bf_size: Optional[str] = None, + bf_fp: Optional[float] = None, + reprobes: int = 126, + no_remap: bool = False, + verbose: bool = False, +): + """ + Count k-mers in DNA sequences from FASTA/multi-FASTA files. + + Args: + input_files: List of input FASTA/multi-FASTA files. + mer_len: Length of the k-mers. + size: Initial hash size (e.g., 100M, 1G). + output_file: Output file name for the Jellyfish database. + threads: Number of threads to use. + counter_len: Number of bits for the counter. + both_strands: Count k-mers on both strands (canonical representation). + quality_cutoff: Filter out bases with quality score less than this value. + quality_start: Quality scores are encoded as Q+. + bloom_filter_if: Use a bloom filter to filter k-mers. + text_input: Input files are text files with one k-mer per line. + out_counter_len: Set output counter length. + bf_size: Bloom filter size. + bf_fp: Bloom filter false positive rate. + reprobes: Number of reprobes. + no_remap: Do not remap hash. + verbose: Be verbose. + """ + if not input_files: + raise ValueError("At least one input file must be provided.") + for file_path in input_files: + if not file_path.exists(): + raise FileNotFoundError(f"Input file not found: {file_path}") + if mer_len < 1: + raise ValueError("mer_len must be a positive integer.") + if threads < 1: + raise ValueError("threads must be a positive integer.") + if bloom_filter_if and not bloom_filter_if.exists(): + raise FileNotFoundError(f"Bloom filter file not found: {bloom_filter_if}") + + output_path = output_file or Path(tempfile.mkstemp(suffix=".jf")[1]) + output_files_dict = {"database": str(output_path)} + + cmd = [ + "jellyfish", "count", + "-m", str(mer_len), + "-s", size, + "-t", str(threads), + "-o", str(output_path), + "-c", str(counter_len), + "--quality-cutoff", str(quality_cutoff), + "--quality-start", str(quality_start), + "--reprobes", str(reprobes), + ] + + if both_strands: + cmd.append("-C") + if text_input: + cmd.append("--text") + if no_remap: + cmd.append("--no-remap") + if verbose: + cmd.append("--verbose") + if bloom_filter_if: + cmd.extend(["--if", str(bloom_filter_if)]) + if out_counter_len is not None: + cmd.extend(["--out-counter-len", str(out_counter_len)]) + if bf_size: + cmd.extend(["--bf-size", bf_size]) + if bf_fp is not None: + cmd.extend(["--bf-fp", str(bf_fp)]) + + cmd.extend([str(p) for p in input_files]) + + return _run_jellyfish_command(cmd, output_files_dict) + + +@mcp.tool() +def jellyfish_dump( + database_file: Path, + output_file: Optional[Path] = None, + column: bool = False, + tab_separator: bool = False, + lower_count: Optional[int] = None, + upper_count: Optional[int] = None, + prefix: Optional[str] = None, +): + """ + Dumps k-mer counts from a Jellyfish database to a human-readable text file. + + Args: + database_file: Input Jellyfish database file. + output_file: Output file for the dumped k-mers. If not provided, output is to stdout. + column: Output in two columns (k-mer, count). + tab_separator: Use tab as a separator. + lower_count: Do not output k-mers with count less than this value. + upper_count: Do not output k-mers with count greater than this value. + prefix: Dump only k-mers with this prefix. + """ + if not database_file.exists(): + raise FileNotFoundError(f"Database file not found: {database_file}") + + output_files_dict = {} + cmd = ["jellyfish", "dump"] + + if output_file: + cmd.extend(["-o", str(output_file)]) + output_files_dict["dump_file"] = str(output_file) + + if column: + cmd.append("-c") + if tab_separator: + cmd.append("-t") + if lower_count is not None: + cmd.extend(["-L", str(lower_count)]) + if upper_count is not None: + cmd.extend(["-U", str(upper_count)]) + if prefix: + cmd.extend(["-p", prefix]) + + cmd.append(str(database_file)) + + return _run_jellyfish_command(cmd, output_files_dict) + + +@mcp.tool() +def jellyfish_query( + database_file: Path, + kmers_to_query: Optional[List[str]] = None, + sequence_file: Optional[Path] = None, +): + """ + Queries a Jellyfish database for the counts of specific k-mers. + + Args: + database_file: Input Jellyfish database file. + kmers_to_query: List of k-mers to query. + sequence_file: Query all k-mers in a FASTA file. + """ + if not database_file.exists(): + raise FileNotFoundError(f"Database file not found: {database_file}") + if not kmers_to_query and not sequence_file: + raise ValueError("Either 'kmers_to_query' or 'sequence_file' must be provided.") + if kmers_to_query and sequence_file: + raise ValueError("'kmers_to_query' and 'sequence_file' are mutually exclusive.") + if sequence_file and not sequence_file.exists(): + raise FileNotFoundError(f"Sequence file not found: {sequence_file}") + + cmd = ["jellyfish", "query", str(database_file)] + + if sequence_file: + cmd.extend(["-s", str(sequence_file)]) + if kmers_to_query: + cmd.extend(kmers_to_query) + + return _run_jellyfish_command(cmd, {}) + + +@mcp.tool() +def jellyfish_stats( + database_file: Path, + output_file: Optional[Path] = None, + verbose: bool = False, + lower_count: Optional[int] = None, + upper_count: Optional[int] = None, + dump_config: bool = False, +): + """ + Computes and prints statistics about a Jellyfish database. + + Args: + database_file: Input Jellyfish database file. + output_file: Output file for statistics. If not provided, output is to stdout. + verbose: Verbose output. + lower_count: Lower bound for count in statistics. + upper_count: Upper bound for count in statistics. + dump_config: Dump the configuration of the file. + """ + if not database_file.exists(): + raise FileNotFoundError(f"Database file not found: {database_file}") + + output_files_dict = {} + cmd = ["jellyfish", "stats"] + + if output_file: + cmd.extend(["-o", str(output_file)]) + output_files_dict["stats_file"] = str(output_file) + + if verbose: + cmd.append("-v") + if dump_config: + cmd.append("--dump-config") + if lower_count is not None: + cmd.extend(["-L", str(lower_count)]) + if upper_count is not None: + cmd.extend(["-U", str(upper_count)]) + + cmd.append(str(database_file)) + + return _run_jellyfish_command(cmd, output_files_dict) + + +@mcp.tool() +def jellyfish_histo( + database_file: Path, + output_file: Optional[Path] = None, + low: int = 1, + high: int = 10000, + increment: int = 1, + full: bool = False, + threads: int = 1, +): + """ + Creates a histogram of k-mer counts from a Jellyfish database. + + Args: + database_file: Input Jellyfish database file. + output_file: Output file for the histogram. If not provided, output is to stdout. + low: Low count value for the histogram range. + high: High count value for the histogram range. + increment: Increment value for histogram bins. + full: Create a full histogram up to the max count. + threads: Number of threads to use. + """ + if not database_file.exists(): + raise FileNotFoundError(f"Database file not found: {database_file}") + if threads < 1: + raise ValueError("threads must be a positive integer.") + if low < 0 or high < 0 or increment < 1: + raise ValueError("low, high, and increment must be positive integers.") + if not full and low >= high: + raise ValueError("low must be less than high if --full is not specified.") + + output_files_dict = {} + cmd = [ + "jellyfish", "histo", + "-t", str(threads), + "-l", str(low), + "-h", str(high), + "-i", str(increment), + ] + + if output_file: + cmd.extend(["-o", str(output_file)]) + output_files_dict["histogram_file"] = str(output_file) + + if full: + cmd.append("-f") + + cmd.append(str(database_file)) + + return _run_jellyfish_command(cmd, output_files_dict) + + +@mcp.tool() +def jellyfish_merge( + input_files: List[Path], + output_file: Optional[Path] = None, + lower_count: Optional[int] = None, + upper_count: Optional[int] = None, + verbose: bool = False, +): + """ + Merges multiple Jellyfish databases into a single database. + + Args: + input_files: List of input Jellyfish database files to merge. + output_file: Output file for the merged database. Defaults to 'out.jf'. + lower_count: Lower bound for count in the merged database. + upper_count: Upper bound for count in the merged database. + verbose: Verbose output. + """ + if not input_files or len(input_files) < 2: + raise ValueError("At least two input database files must be provided for merging.") + for file_path in input_files: + if not file_path.exists(): + raise FileNotFoundError(f"Input file not found: {file_path}") + + output_path = output_file or Path("out.jf") + output_files_dict = {"merged_database": str(output_path)} + + cmd = ["jellyfish", "merge", "-o", str(output_path)] + + if verbose: + cmd.append("-v") + if lower_count is not None: + cmd.extend(["-L", str(lower_count)]) + if upper_count is not None: + cmd.extend(["-U", str(upper_count)]) + + cmd.extend([str(p) for p in input_files]) + + return _run_jellyfish_command(cmd, output_files_dict) + + +@mcp.tool() +def jellyfish_info( + database_file: Path, + output_format: str = "text", + verbose: bool = False, +): + """ + Displays metadata information about a Jellyfish database. + + Args: + database_file: Input Jellyfish database file. + output_format: Output format ('text', 'json', or 'xml'). + verbose: Verbose output. + """ + if not database_file.exists(): + raise FileNotFoundError(f"Database file not found: {database_file}") + if output_format not in ["text", "json", "xml"]: + raise ValueError("output_format must be one of 'text', 'json', or 'xml'.") + + cmd = ["jellyfish", "info", "-f", output_format] + + if verbose: + cmd.append("-v") + + cmd.append(str(database_file)) + + return _run_jellyfish_command(cmd, {}) + + +@mcp.tool() +def jellyfish_bc( + input_file: Path, + mer_len: int, + size: str, + output_file: Optional[Path] = None, + threads: int = 1, + both_strands: bool = False, + out_counter_len: Optional[int] = None, + bf_size: Optional[str] = None, + bf_fp: Optional[float] = None, + reprobes: int = 126, + no_remap: bool = False, + verbose: bool = False, +): + """ + Compute a lower bound on the size of a hash to count k-mers in a file. + + Args: + input_file: Input FASTA file. + mer_len: Length of the k-mers. + size: Initial hash size (e.g., 100M, 1G). + output_file: Output file name for the histogram. Defaults to 'bc.histo'. + threads: Number of threads to use. + both_strands: Count k-mers on both strands. + out_counter_len: Set output counter length. + bf_size: Bloom filter size. + bf_fp: Bloom filter false positive rate. + reprobes: Number of reprobes. + no_remap: Do not remap hash. + verbose: Be verbose. + """ + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if mer_len < 1: + raise ValueError("mer_len must be a positive integer.") + if threads < 1: + raise ValueError("threads must be a positive integer.") + + output_path = output_file or Path("bc.histo") + output_files_dict = {"bc_histogram": str(output_path)} + + cmd = [ + "jellyfish", "bc", + "-m", str(mer_len), + "-s", size, + "-t", str(threads), + "-o", str(output_path), + "--reprobes", str(reprobes), + ] + + if both_strands: + cmd.append("-C") + if no_remap: + cmd.append("--no-remap") + if verbose: + cmd.append("--verbose") + if out_counter_len is not None: + cmd.extend(["--out-counter-len", str(out_counter_len)]) + if bf_size: + cmd.extend(["--bf-size", bf_size]) + if bf_fp is not None: + cmd.extend(["--bf-fp", str(bf_fp)]) + + cmd.append(str(input_file)) + + return _run_jellyfish_command(cmd, output_files_dict) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmer-jellyfish/app/kmer-jellyfish_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmer-jellyfish/app/kmer-jellyfish_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..89bb1a8180b11101a146ab72ea00aeab92f1c22d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmer-jellyfish/app/kmer-jellyfish_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmer-jellyfish/app/kmer-jellyfish_server.py') +SERVER_NAME = 'biosci_kmer_jellyfish' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmer-jellyfish/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmer-jellyfish/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmer-jellyfish/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmer-jellyfish/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmer-jellyfish/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..4d01d24f4327365c388085a2fde0b1238ff46b0d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmer-jellyfish/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-kmer-jellyfish: + build: . + image: mcp-kmer-jellyfish:latest + container_name: mcp-kmer-jellyfish + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=kmer-jellyfish + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmer-jellyfish/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmer-jellyfish/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..59c5c9892cffbd7f86ceb79777d2f9753c35451e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmer-jellyfish/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - kmer-jellyfish + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmer-jellyfish/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmer-jellyfish/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kmer-jellyfish/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kraken2/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kraken2/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9f0143f267bb44f451955f52413a42f18489fe8f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kraken2/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install kraken2 via conda (e.g., from bioconda) +RUN conda install -c bioconda kraken2 -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/kraken2_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/kraken2_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/kraken2_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kraken2/app/kraken2_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kraken2/app/kraken2_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0f2fdd27eb502f36dfc81e2aa5d312e7fcbe4800 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kraken2/app/kraken2_server.py @@ -0,0 +1,451 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional, Dict, Any + +# Helper function for running subprocesses +def _run_command(cmd: List[str], cwd: Optional[Path] = None) -> Dict[str, Any]: + """ + Executes a shell command and returns its output. + """ + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + cwd=cwd + ) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [], # This will be populated by the tool functions + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "returncode": e.returncode, + "output_files": [], + } + except FileNotFoundError: + return { + "command_executed": " ".join(cmd), + "stdout": "", + "stderr": f"Error: Command '{cmd[0]}' not found. Is Kraken2 installed and in your PATH?", + "error": "Command not found", + "output_files": [], + } + +@mcp.tool() +def kraken2_classify( + database: Path, + input_files: List[Path], + output_file: Optional[Path] = None, + report_file: Optional[Path] = None, + threads: int = 1, + paired: bool = False, + unclassified_out: Optional[Path] = None, + classified_out: Optional[Path] = None, + confidence: float = 0.0, + minimum_hit_groups: int = 2, + quick: bool = False, + use_mpa_style: bool = False, + gzip_compressed: bool = False, + bzip2_compressed: bool = False, + memory_mapping: bool = False, + preload_db: bool = False, + report_zero_counts: bool = False, + report_minimizer_data: bool = False, + skip_classified: bool = False, + skip_unclassified: bool = False, + scientific_name_output: bool = False, + taxid_output: bool = False, + kmer_len: Optional[int] = None, + minimizer_len: Optional[int] = None, + minimizer_spaces: Optional[int] = None, +) -> Dict[str, Any]: + """ + Classifies metagenomic reads using Kraken2. + + Args: + database: Path to the Kraken2 database directory. + input_files: List of input FASTA/FASTQ files. For paired-end reads, provide + R1 files followed by R2 files (e.g., [R1_1, R1_2, ..., R2_1, R2_2, ...]). + output_file: Path for the Kraken2 classification output. If not provided, + output goes to stdout. + report_file: Path for the Kraken2 report file. + threads: Number of threads to use for classification. Must be at least 1. + paired: Set to True if input_files contain paired-end reads. + unclassified_out: Path to write unclassified reads. + classified_out: Path to write classified reads. + confidence: Confidence score threshold (0.0-1.0). + minimum_hit_groups: Minimum number of hit groups required for a classification. Must be at least 1. + quick: Enable quick classification mode. + use_mpa_style: Report output in MPA-style format. + gzip_compressed: Assume input files are gzip compressed. + bzip2_compressed: Assume input files are bzip2 compressed. + memory_mapping: Use memory mapping for database. + preload_db: Preload database into RAM. + report_zero_counts: Include taxa with zero counts in the report. + report_minimizer_data: Include minimizer data in the report. + skip_classified: Do not output classified reads. + skip_unclassified: Do not output unclassified reads. + scientific_name_output: Output scientific names instead of taxids in classification. + taxid_output: Output taxids instead of names in classification. + kmer_len: Override k-mer length from database. Must be positive if provided. + minimizer_len: Override minimizer length from database. Must be positive if provided. + minimizer_spaces: Override minimizer spaces from database. Must be non-negative if provided. + + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + if not database.is_dir(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Database directory '{database}' not found or is not a directory.", + "error": "Invalid database path", + "output_files": [], + } + + if not input_files: + return { + "command_executed": "", + "stdout": "", + "stderr": "Error: No input files provided.", + "error": "Missing input files", + "output_files": [], + } + + for f in input_files: + if not f.is_file(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Input file '{f}' not found or is not a file.", + "error": "Invalid input file path", + "output_files": [], + } + + if paired and len(input_files) % 2 != 0: + return { + "command_executed": "", + "stdout": "", + "stderr": "Error: For paired-end reads, an even number of input files is required.", + "error": "Mismatched paired-end files", + "output_files": [], + } + + if threads < 1: + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Number of threads must be at least 1, got {threads}.", + "error": "Invalid threads count", + "output_files": [], + } + + if not (0.0 <= confidence <= 1.0): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Confidence score must be between 0.0 and 1.0, got {confidence}.", + "error": "Invalid confidence score", + "output_files": [], + } + + if minimum_hit_groups < 1: + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Minimum hit groups must be at least 1, got {minimum_hit_groups}.", + "error": "Invalid minimum hit groups", + "output_files": [], + } + + if kmer_len is not None and kmer_len < 1: + return { + "command_executed": "", "stdout": "", + "stderr": f"Error: kmer_len must be positive, got {kmer_len}.", + "error": "Invalid kmer_len", "output_files": [] + } + if minimizer_len is not None and minimizer_len < 1: + return { + "command_executed": "", "stdout": "", + "stderr": f"Error: minimizer_len must be positive, got {minimizer_len}.", + "error": "Invalid minimizer_len", "output_files": [] + } + if minimizer_spaces is not None and minimizer_spaces < 0: + return { + "command_executed": "", "stdout": "", + "stderr": f"Error: minimizer_spaces cannot be negative, got {minimizer_spaces}.", + "error": "Invalid minimizer_spaces", "output_files": [] + } + + # Prepare command + cmd = ["kraken2", "--db", str(database)] + + if threads > 1: + cmd.extend(["--threads", str(threads)]) + if output_file: + output_file.parent.mkdir(parents=True, exist_ok=True) + cmd.extend(["--output", str(output_file)]) + if report_file: + report_file.parent.mkdir(parents=True, exist_ok=True) + cmd.extend(["--report", str(report_file)]) + if paired: + cmd.append("--paired") + if unclassified_out: + unclassified_out.parent.mkdir(parents=True, exist_ok=True) + cmd.extend(["--unclassified-out", str(unclassified_out)]) + if classified_out: + classified_out.parent.mkdir(parents=True, exist_ok=True) + cmd.extend(["--classified-out", str(classified_out)]) + if confidence != 0.0: # Only add if not default + cmd.extend(["--confidence", str(confidence)]) + if minimum_hit_groups != 2: # Only add if not default + cmd.extend(["--minimum-hit-groups", str(minimum_hit_groups)]) + if quick: + cmd.append("--quick") + if use_mpa_style: + cmd.append("--use-mpa-style") + if gzip_compressed: + cmd.append("--gzip-compressed") + if bzip2_compressed: + cmd.append("--bzip2-compressed") + if memory_mapping: + cmd.append("--memory-mapping") + if preload_db: + cmd.append("--preload-db") + if report_zero_counts: + cmd.append("--report-zero-counts") + if report_minimizer_data: + cmd.append("--report-minimizer-data") + if skip_classified: + cmd.append("--skip-classified") + if skip_unclassified: + cmd.append("--skip-unclassified") + if scientific_name_output: + # Standard Kraken2 releases do not support this generated flag. Use + # --report and taxonomy post-processing for scientific names instead. + pass + if taxid_output: + # Kraken2 output already includes taxids; this generated flag is not portable. + pass + if kmer_len is not None: + cmd.extend(["--kmer-len", str(kmer_len)]) + if minimizer_len is not None: + cmd.extend(["--minimizer-len", str(minimizer_len)]) + if minimizer_spaces is not None: + cmd.extend(["--minimizer-spaces", str(minimizer_spaces)]) + + cmd.extend([str(f) for f in input_files]) + + result = _run_command(cmd) + + # Add output files to the result + output_files = [] + if output_file: + output_files.append(str(output_file)) + if report_file: + output_files.append(str(report_file)) + if unclassified_out: + output_files.append(str(unclassified_out)) + if classified_out: + output_files.append(str(classified_out)) + result["output_files"] = output_files + + return result + +@mcp.tool() +def kraken2_build_db( + database: Path, + threads: int = 1, + add_to_library_files: Optional[List[Path]] = None, + build_db: bool = False, + download_taxonomy: bool = False, + download_library: Optional[str] = None, # e.g., 'nt', 'refseq', 'viral', 'archaea', 'bacteria', 'human' + clean: bool = False, + kmer_len: Optional[int] = None, + minimizer_len: Optional[int] = None, + minimizer_spaces: Optional[int] = None, + max_db_size: Optional[str] = None, # e.g., '50G' + protein: bool = False, + fast_build: bool = False, + no_masking: bool = False, + taxid_map: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Builds or updates a Kraken2 database. + + Args: + database: Path to the Kraken2 database directory to be built or updated. + threads: Number of threads to use for database building. Must be at least 1. + add_to_library_files: List of FASTA files to add to the database library. + build_db: Set to True to initiate the database build process after adding files. + download_taxonomy: Set to True to download NCBI taxonomy. + download_library: Specify a library to download (e.g., 'nt', 'refseq', 'viral', 'archaea', 'bacteria', 'human', 'fungi', 'plant', 'protozoa'). + clean: Remove intermediate files after building. + kmer_len: K-mer length for the database. Must be positive if provided. + minimizer_len: Minimizer length for the database. Must be positive if provided. + minimizer_spaces: Number of spaces in minimizers for the database. Must be non-negative if provided. + max_db_size: Maximum database size (e.g., '50G', '100M'). + protein: Build a protein database. + fast_build: Use a faster, less memory-intensive build process. + no_masking: Do not mask low-complexity regions in input sequences. + taxid_map: Path to a custom taxid map file. + + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + if not database.parent.is_dir(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Parent directory of database '{database.parent}' not found.", + "error": "Invalid database path", + "output_files": [], + } + + if threads < 1: + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Number of threads must be at least 1, got {threads}.", + "error": "Invalid threads count", + "output_files": [], + } + + if add_to_library_files: + for f in add_to_library_files: + if not f.is_file(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Library file '{f}' not found or is not a file.", + "error": "Invalid library file path", + "output_files": [], + } + + if kmer_len is not None and kmer_len < 1: + return { + "command_executed": "", "stdout": "", + "stderr": f"Error: kmer_len must be positive, got {kmer_len}.", + "error": "Invalid kmer_len", "output_files": [] + } + if minimizer_len is not None and minimizer_len < 1: + return { + "command_executed": "", "stdout": "", + "stderr": f"Error: minimizer_len must be positive, got {minimizer_len}.", + "error": "Invalid minimizer_len", "output_files": [] + } + if minimizer_spaces is not None and minimizer_spaces < 0: + return { + "command_executed": "", "stdout": "", + "stderr": f"Error: minimizer_spaces cannot be negative, got {minimizer_spaces}.", + "error": "Invalid minimizer_spaces", "output_files": [] + } + + if taxid_map and not taxid_map.is_file(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Custom taxid map file '{taxid_map}' not found or is not a file.", + "error": "Invalid taxid map path", + "output_files": [], + } + + # Prepare command + cmd = ["kraken2-build", "--db", str(database)] + + if threads > 1: + cmd.extend(["--threads", str(threads)]) + if download_taxonomy: + cmd.append("--download-taxonomy") + if download_library: + valid_libraries = ['nt', 'refseq', 'viral', 'archaea', 'bacteria', 'human', 'fungi', 'plant', 'protozoa'] # Common ones + if download_library not in valid_libraries: + return { + "command_executed": "", "stdout": "", + "stderr": f"Error: Invalid download_library '{download_library}'. Must be one of {', '.join(valid_libraries)}.", + "error": "Invalid download_library", "output_files": [] + } + cmd.extend(["--download-library", download_library]) + if add_to_library_files: + for f in add_to_library_files: + cmd.extend(["--add-to-library", str(f)]) + if build_db: + cmd.append("--build") + if clean: + cmd.append("--clean") + if kmer_len is not None: + cmd.extend(["--kmer-len", str(kmer_len)]) + if minimizer_len is not None: + cmd.extend(["--minimizer-len", str(minimizer_len)]) + if minimizer_spaces is not None: + cmd.extend(["--minimizer-spaces", str(minimizer_spaces)]) + if max_db_size: + cmd.extend(["--max-db-size", max_db_size]) + if protein: + cmd.append("--protein") + if fast_build: + cmd.append("--fast-build") + if no_masking: + cmd.append("--no-masking") + if taxid_map: + cmd.extend(["--taxid-map", str(taxid_map)]) + + # Ensure at least one action is specified for kraken2-build + if not (download_taxonomy or download_library or add_to_library_files or build_db or clean): + return { + "command_executed": "", + "stdout": "", + "stderr": "Error: No action specified for kraken2-build. Please specify --download-taxonomy, --download-library, --add-to-library, --build, or --clean.", + "error": "No build action specified", + "output_files": [], + } + + result = _run_command(cmd) + + # The database directory itself is the primary output if build was successful + if result.get("returncode", 0) == 0 and (build_db or download_taxonomy or download_library): + result["output_files"].append(str(database)) + + return result + +@mcp.tool() +def kraken2_inspect_db( + database: Path, +) -> Dict[str, Any]: + """ + Inspects a Kraken2 database and prints its contents. + + Args: + database: Path to the Kraken2 database directory. + + Returns: + A dictionary containing command execution details, stdout, stderr, and output files. + """ + # Input validation + if not database.is_dir(): + return { + "command_executed": "", + "stdout": "", + "stderr": f"Error: Database directory '{database}' not found or is not a directory.", + "error": "Invalid database path", + "output_files": [], + } + + # Prepare command + cmd = ["kraken2-inspect", "--db", str(database)] + + result = _run_command(cmd) + + # No specific output files are generated by inspect, its output is stdout + return result diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kraken2/app/kraken2_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kraken2/app/kraken2_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..763255b8e0e77e24bcb827d298e0a0c15aab7ebc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kraken2/app/kraken2_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kraken2/app/kraken2_server.py') +SERVER_NAME = 'biosci_kraken2' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kraken2/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kraken2/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kraken2/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kraken2/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kraken2/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..12678b81c5c5a49282c43e9bc1d47af2b88bbc0c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kraken2/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-kraken2: + build: . + image: mcp-kraken2:latest + container_name: mcp-kraken2 + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=kraken2 + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kraken2/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kraken2/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c3885284a988e6cfaff2e0b4165922a3e163706f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kraken2/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - kraken2 + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kraken2/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kraken2/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_kraken2/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_krona/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_krona/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..910d9b53f1a7bc9135859db790acd1d690d83f90 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_krona/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install krona via conda (e.g., from bioconda) +RUN conda install -c bioconda krona -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/krona_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/krona_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/krona_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_krona/app/krona_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_krona/app/krona_server.py new file mode 100644 index 0000000000000000000000000000000000000000..cb0b8e357b74ab9576758d69ed63642be27a1ed4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_krona/app/krona_server.py @@ -0,0 +1,541 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Dict, List, Optional + +# Per instructions, the @mcp.tool decorator is assumed to be provided by the environment. +# We do not define or import it. + +@mcp.tool() +def update_taxonomy( + taxonomy_directory: Path, + only_build: bool = False, + tax_dump: Optional[Path] = None, + accession2taxid: Optional[Path] = None, +) -> Dict: + """ + Downloads and builds the Krona taxonomy database. Wraps 'ktUpdateTaxonomy.sh'. + + Args: + taxonomy_directory: The directory to store the taxonomy database. + only_build: Do not download files; build from existing ones. + tax_dump: Path to a local taxdump.tar.gz file. + accession2taxid: Path to a local accession2taxid.gz file. + + Returns: + A dictionary containing the execution details and output directory path. + """ + # Input validation + if not taxonomy_directory.parent.exists(): + raise FileNotFoundError(f"Parent directory for {taxonomy_directory} does not exist.") + taxonomy_directory.mkdir(exist_ok=True) + + cmd = ["ktUpdateTaxonomy.sh"] + + if only_build: + cmd.append("--only-build") + if tax_dump: + if not tax_dump.exists(): + raise FileNotFoundError(f"Tax dump file not found: {tax_dump}") + cmd.extend(["--tax-dump", str(tax_dump)]) + if accession2taxid: + if not accession2taxid.exists(): + raise FileNotFoundError(f"Accession2taxid file not found: {accession2taxid}") + cmd.extend(["--accession2taxid", str(accession2taxid)]) + + cmd.append(str(taxonomy_directory)) + + 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": {"taxonomy_directory": str(taxonomy_directory)}, + } + except FileNotFoundError: + raise RuntimeError("ktUpdateTaxonomy.sh not found. Is KronaTools installed and in your PATH?") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Krona update_taxonomy failed with exit code {e.returncode}.\n" + f"Command: {' '.join(cmd)}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def import_text( + input_files: List[str], + output_file: Path, + name: Optional[str] = None, + url: Optional[str] = None, + query_column: int = 1, + taxonomy_column: int = 2, + score_column: Optional[int] = None, + magnitude_column: Optional[int] = None, + include_unassigned: bool = False, + depth: int = 5, + no_magnitude: bool = False, + no_rank: bool = False, + combine: bool = False, + cellular: bool = False, + key: bool = False, + taxonomy_directory: Optional[Path] = None, +) -> Dict: + """ + Generates a Krona chart from generic text files. Wraps 'ktImportText'. + + Args: + input_files: List of input text files. Can use 'file=name' syntax. + output_file: Path for the output HTML file. + name: Root name of the chart. + url: Base URL to be prepended to query IDs for links. + query_column: Column of query ID (1-based). + taxonomy_column: Column of taxonomy ID (1-based). + score_column: Column of score (1-based). + magnitude_column: Column of magnitude (1-based). + include_unassigned: Include queries with no taxonomy ID. + depth: Initial visible depth of the chart. + no_magnitude: Do not use magnitudes from input files. + no_rank: Do not use ranks for unassigned queries. + combine: Treat all input files as a single dataset. + cellular: Only include cellular organisms (bacteria, archaea, eukarya). + key: Use query IDs as wedge labels. + taxonomy_directory: Path to the Krona taxonomy database. + + Returns: + A dictionary containing the execution details and output file path. + """ + if not input_files: + raise ValueError("At least one input file must be provided.") + + for file_str in input_files: + file_path_str = file_str.split('=')[0] + if not Path(file_path_str).exists(): + raise FileNotFoundError(f"Input file not found: {file_path_str}") + + if not output_file.parent.exists(): + output_file.parent.mkdir(parents=True, exist_ok=True) + + cmd = ["ktImportText", "-o", str(output_file)] + + if name: + cmd.extend(["-n", name]) + if url: + cmd.extend(["-u", url]) + if query_column != 1: + cmd.extend(["-q", str(query_column)]) + if taxonomy_column != 2: + cmd.extend(["-t", str(taxonomy_column)]) + if score_column is not None: + cmd.extend(["-s", str(score_column)]) + if magnitude_column is not None: + cmd.extend(["-m", str(magnitude_column)]) + if include_unassigned: + cmd.append("-i") + if depth != 5: + cmd.extend(["-d", str(depth)]) + if no_magnitude: + cmd.append("--no-mag") + if no_rank: + cmd.append("--no-rank") + if combine: + cmd.append("--combine") + if cellular: + cmd.append("--cellular") + if key: + cmd.append("--key") + if taxonomy_directory: + if not taxonomy_directory.is_dir(): + raise NotADirectoryError(f"Taxonomy directory not found: {taxonomy_directory}") + cmd.extend(["--tax", str(taxonomy_directory)]) + + cmd.extend(input_files) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"krona_chart": str(output_file)}, + } + except FileNotFoundError: + raise RuntimeError("ktImportText not found. Is KronaTools installed and in your PATH?") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Krona import_text failed with exit code {e.returncode}.\n" + f"Command: {' '.join(cmd)}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def import_blast( + input_files: List[str], + output_file: Path, + name: Optional[str] = None, + url: Optional[str] = None, + query_column: int = 1, + taxonomy_column: int = 2, + score_column: int = 3, + max_evalue: float = 0.01, + max_matches: int = 25, + include: bool = False, + depth: int = 5, + no_hits: bool = False, + combine: bool = False, + cellular: bool = False, + key: bool = False, + taxonomy_directory: Optional[Path] = None, + blast_format: str = "tab", +) -> Dict: + """ + Generates a Krona chart from BLAST results. Wraps 'ktImportBLAST'. + + Args: + input_files: List of BLAST output files. Can use 'file=name' syntax. + output_file: Path for the output HTML file. + name: Root name of the chart. + url: Base URL to be prepended to query IDs for links. + query_column: Column of query ID (1-based). + taxonomy_column: Column of taxonomy ID (1-based). + score_column: Column of score (bit score or e-value, 1-based). + max_evalue: Maximum e-value to be included. + max_matches: Maximum number of matches to consider per query. + include: Include queries with no hits. + depth: Initial visible depth of the chart. + no_hits: Do not use hit counts as magnitudes. + combine: Treat all input files as a single dataset. + cellular: Only include cellular organisms. + key: Use query IDs as wedge labels. + taxonomy_directory: Path to the Krona taxonomy database. + blast_format: Format of BLAST output ('tab' or 'xml'). + + Returns: + A dictionary containing the execution details and output file path. + """ + if not input_files: + raise ValueError("At least one input file must be provided.") + if blast_format not in ["tab", "xml"]: + raise ValueError("blast_format must be either 'tab' or 'xml'.") + + for file_str in input_files: + file_path_str = file_str.split('=')[0] + if not Path(file_path_str).exists(): + raise FileNotFoundError(f"Input file not found: {file_path_str}") + + if not output_file.parent.exists(): + output_file.parent.mkdir(parents=True, exist_ok=True) + + cmd = ["ktImportBLAST", "-o", str(output_file)] + + if name: + cmd.extend(["-n", name]) + if url: + cmd.extend(["-u", url]) + if query_column != 1: + cmd.extend(["-q", str(query_column)]) + if taxonomy_column != 2: + cmd.extend(["-t", str(taxonomy_column)]) + if score_column != 3: + cmd.extend(["-s", str(score_column)]) + if max_evalue != 0.01: + cmd.extend(["-e", str(max_evalue)]) + if max_matches != 25: + cmd.extend(["-m", str(max_matches)]) + if include: + cmd.append("-i") + if depth != 5: + cmd.extend(["-d", str(depth)]) + if no_hits: + cmd.append("--no-hits") + if combine: + cmd.append("--combine") + if cellular: + cmd.append("--cellular") + if key: + cmd.append("--key") + if taxonomy_directory: + if not taxonomy_directory.is_dir(): + raise NotADirectoryError(f"Taxonomy directory not found: {taxonomy_directory}") + cmd.extend(["--tax", str(taxonomy_directory)]) + if blast_format != "tab": + cmd.extend(["--blast-format", blast_format]) + + cmd.extend(input_files) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"krona_chart": str(output_file)}, + } + except FileNotFoundError: + raise RuntimeError("ktImportBLAST not found. Is KronaTools installed and in your PATH?") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Krona import_blast failed with exit code {e.returncode}.\n" + f"Command: {' '.join(cmd)}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def import_xml( + input_files: List[str], + output_file: Path, + name: Optional[str] = None, + url: Optional[str] = None, + include: bool = False, + depth: int = 5, + no_hits: bool = False, + combine: bool = False, + cellular: bool = False, + key: bool = False, + taxonomy_directory: Optional[Path] = None, +) -> Dict: + """ + Generates a Krona chart from various XML formats. Wraps 'ktImportXML'. + + Args: + input_files: List of input XML files. Can use 'file=name' syntax. + output_file: Path for the output HTML file. + name: Root name of the chart. + url: Base URL to be prepended to query IDs for links. + include: Include queries with no hits. + depth: Initial visible depth of the chart. + no_hits: Do not use hit counts as magnitudes. + combine: Treat all input files as a single dataset. + cellular: Only include cellular organisms. + key: Use query IDs as wedge labels. + taxonomy_directory: Path to the Krona taxonomy database. + + Returns: + A dictionary containing the execution details and output file path. + """ + if not input_files: + raise ValueError("At least one input file must be provided.") + + for file_str in input_files: + file_path_str = file_str.split('=')[0] + if not Path(file_path_str).exists(): + raise FileNotFoundError(f"Input file not found: {file_path_str}") + + if not output_file.parent.exists(): + output_file.parent.mkdir(parents=True, exist_ok=True) + + cmd = ["ktImportXML", "-o", str(output_file)] + + if name: + cmd.extend(["-n", name]) + if url: + cmd.extend(["-u", url]) + if include: + cmd.append("-i") + if depth != 5: + cmd.extend(["-d", str(depth)]) + if no_hits: + cmd.append("--no-hits") + if combine: + cmd.append("--combine") + if cellular: + cmd.append("--cellular") + if key: + cmd.append("--key") + if taxonomy_directory: + if not taxonomy_directory.is_dir(): + raise NotADirectoryError(f"Taxonomy directory not found: {taxonomy_directory}") + cmd.extend(["--tax", str(taxonomy_directory)]) + + cmd.extend(input_files) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"krona_chart": str(output_file)}, + } + except FileNotFoundError: + raise RuntimeError("ktImportXML not found. Is KronaTools installed and in your PATH?") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Krona import_xml failed with exit code {e.returncode}.\n" + f"Command: {' '.join(cmd)}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def import_taxonomy( + input_files: List[str], + output_file: Path, + name: Optional[str] = None, + url: Optional[str] = None, + taxonomy_column: int = 2, + magnitude_column: Optional[int] = None, + include_unassigned: bool = False, + depth: int = 5, + no_magnitude: bool = False, + no_rank: bool = False, + combine: bool = False, + cellular: bool = False, + key: bool = False, + taxonomy_directory: Optional[Path] = None, + query_ids: bool = False, +) -> Dict: + """ + Generates a Krona chart from taxonomy data. Wraps 'ktImportTaxonomy'. + + Args: + input_files: List of input files with lineages. Can use 'file=name' syntax. + output_file: Path for the output HTML file. + name: Root name of the chart. + url: Base URL to be prepended to query IDs for links. + taxonomy_column: Column of taxonomy ID (1-based). + magnitude_column: Column of magnitude (1-based). + include_unassigned: Include queries with no taxonomy ID. + depth: Initial visible depth of the chart. + no_magnitude: Do not use magnitudes from input files. + no_rank: Do not use ranks for unassigned queries. + combine: Treat all input files as a single dataset. + cellular: Only include cellular organisms. + key: Use query IDs as wedge labels. + taxonomy_directory: Path to the Krona taxonomy database. + query_ids: Input files have query IDs in the first column. + + Returns: + A dictionary containing the execution details and output file path. + """ + if not input_files: + raise ValueError("At least one input file must be provided.") + + for file_str in input_files: + file_path_str = file_str.split('=')[0] + if not Path(file_path_str).exists(): + raise FileNotFoundError(f"Input file not found: {file_path_str}") + + if not output_file.parent.exists(): + output_file.parent.mkdir(parents=True, exist_ok=True) + + cmd = ["ktImportTaxonomy", "-o", str(output_file)] + + if name: + cmd.extend(["-n", name]) + if url: + cmd.extend(["-u", url]) + if taxonomy_column != 2: + cmd.extend(["-t", str(taxonomy_column)]) + if magnitude_column is not None: + cmd.extend(["-m", str(magnitude_column)]) + if include_unassigned: + cmd.append("-i") + if depth != 5: + cmd.extend(["-d", str(depth)]) + if no_magnitude: + cmd.append("--no-mag") + if no_rank: + cmd.append("--no-rank") + if combine: + cmd.append("--combine") + if cellular: + cmd.append("--cellular") + if key: + cmd.append("--key") + if taxonomy_directory: + if not taxonomy_directory.is_dir(): + raise NotADirectoryError(f"Taxonomy directory not found: {taxonomy_directory}") + cmd.extend(["--tax", str(taxonomy_directory)]) + if query_ids: + cmd.append("-q") + + cmd.extend(input_files) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"krona_chart": str(output_file)}, + } + except FileNotFoundError: + raise RuntimeError("ktImportTaxonomy not found. Is KronaTools installed and in your PATH?") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Krona import_taxonomy failed with exit code {e.returncode}.\n" + f"Command: {' '.join(cmd)}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + +@mcp.tool() +def classify_blast( + blast_results: Path, + output_file: Path, + taxonomy_column: int = 2, + max_matches: int = 25, + max_names: int = 5, + taxonomy_directory: Optional[Path] = None, +) -> Dict: + """ + Adds taxonomy information to BLAST results. Wraps 'ktClassifyBLAST'. + + Args: + blast_results: Path to the input BLAST results file. + output_file: Path for the classified output file. + taxonomy_column: Column of taxonomy ID (1-based). + max_matches: Maximum number of matches to consider per query. + max_names: Maximum number of names to add per match. + taxonomy_directory: Path to the Krona taxonomy database. + + Returns: + A dictionary containing the execution details and output file path. + """ + if not blast_results.exists(): + raise FileNotFoundError(f"Input file not found: {blast_results}") + + if not output_file.parent.exists(): + output_file.parent.mkdir(parents=True, exist_ok=True) + + cmd = ["ktClassifyBLAST", "-o", str(output_file)] + + if taxonomy_column != 2: + cmd.extend(["-t", str(taxonomy_column)]) + if max_matches != 25: + cmd.extend(["-m", str(max_matches)]) + if max_names != 5: + cmd.extend(["-n", str(max_names)]) + if taxonomy_directory: + if not taxonomy_directory.is_dir(): + raise NotADirectoryError(f"Taxonomy directory not found: {taxonomy_directory}") + cmd.extend(["--tax", str(taxonomy_directory)]) + + cmd.append(str(blast_results)) + + 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": {"classified_blast": str(output_file)}, + } + except FileNotFoundError: + raise RuntimeError("ktClassifyBLAST not found. Is KronaTools installed and in your PATH?") + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Krona classify_blast failed with exit code {e.returncode}.\n" + f"Command: {' '.join(cmd)}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_krona/app/krona_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_krona/app/krona_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7ced1c8999fc0539aeecb836867f3ff763b6ce56 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_krona/app/krona_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_krona/app/krona_server.py') +SERVER_NAME = 'biosci_krona' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_krona/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_krona/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_krona/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_krona/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_krona/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..c2724a22eb5f82f596b8354ad74b377f25c9a161 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_krona/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-krona: + build: . + image: mcp-krona:latest + container_name: mcp-krona + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=krona + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_krona/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_krona/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3e1dbf6c69686308e1bf2d2036f28bb8d0761757 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_krona/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - krona + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_krona/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_krona/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_krona/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_last/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_last/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..59483952effb91e93d6fe94ff3a4e05472227116 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_last/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install last via conda (e.g., from bioconda) +RUN conda install -c bioconda last -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/last_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/last_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/last_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_last/app/last_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_last/app/last_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c044e549fc57d4116dab46fab50671b67a8a6ff8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_last/app/last_server.py @@ -0,0 +1,258 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Union + +@mcp.tool() +def lastdb( + db_name: str, + input_fasta: str, + is_protein: bool = False, + seed_pattern: Optional[str] = None, + soft_mask_lowercase: bool = False, + index_volume_size: Optional[str] = None, +): + """ + Prepare a sequence database for LAST alignment. + + Args: + db_name: Name for the output database files. + input_fasta: Path to the input FASTA file containing reference sequences. + is_protein: Set to True if the sequences are proteins. + seed_pattern: Specify a seed pattern (e.g., '11011'). + soft_mask_lowercase: Use lowercase letters as soft-masking of repeats. + index_volume_size: Max size for each index volume (e.g., '4G'). + """ + input_path = Path(input_fasta) + if not input_path.exists(): + return {"error": f"Input file {input_fasta} not found."} + + cmd = ["lastdb"] + + if is_protein: + cmd.append("-p") + if soft_mask_lowercase: + cmd.append("-c") + if seed_pattern: + cmd.extend(["-u", seed_pattern]) + if index_volume_size: + cmd.extend(["-v", index_volume_size]) + + cmd.extend([db_name, str(input_path)]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(p) for p in Path(".").glob(f"{db_name}.*")] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": e.stderr, + "stdout": e.stdout + } + +@mcp.tool() +def lastal( + db_name: str, + query_file: str, + output_format: str = "maf", + threads: int = 1, + min_score: Optional[int] = None, + query_step: Optional[int] = None, + max_initial_matches: Optional[int] = None, + strand: int = 2, +): + """ + Align sequences to a LAST database. + + Args: + db_name: Base name of the LAST database. + query_file: Path to the query sequences (FASTA/FASTQ). + output_format: Output format: 'maf', 'sam', 'tab', or 'blast'. + threads: Number of parallel threads to use. + min_score: Minimum score for gapless alignments (-e). + query_step: Query step size (-D). + max_initial_matches: Maximum initial matches per query position (-m). + strand: 0 for reverse, 1 for forward, 2 for both strands. + """ + query_path = Path(query_file) + if not query_path.exists(): + return {"error": f"Query file {query_file} not found."} + + cmd = ["lastal"] + + # Format handling + format_map = {"maf": "0", "tab": "1", "blast": "3", "sam": "sam"} + cmd.extend(["-f", format_map.get(output_format.lower(), "0")]) + + if threads > 1: + cmd.extend(["-P", str(threads)]) + if min_score is not None: + cmd.extend(["-e", str(min_score)]) + if query_step is not None: + cmd.extend(["-D", str(query_step)]) + if max_initial_matches is not None: + cmd.extend(["-m", str(max_initial_matches)]) + + cmd.extend(["-s", str(strand)]) + cmd.extend([db_name, str(query_path)]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": e.stderr, + "stdout": e.stdout + } + +@mcp.tool() +def last_train( + db_name: str, + query_file: str, + output_param_file: str, + threads: int = 1, + alignment_type: str = "DNA", +): + """ + Find optimal score parameters for LAST alignment. + + Args: + db_name: Base name of the LAST database. + query_file: Path to the query sequences. + output_param_file: Path to save the trained parameters. + threads: Number of threads to use. + alignment_type: 'DNA' or 'protein'. + """ + query_path = Path(query_file) + if not query_path.exists(): + return {"error": f"Query file {query_file} not found."} + + cmd = ["last-train"] + + if threads > 1: + cmd.extend(["-P", str(threads)]) + + if alignment_type.lower() == "protein": + cmd.append("-p") + + cmd.extend([db_name, str(query_path)]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + with open(output_param_file, "w") as f: + f.write(result.stdout) + + return { + "command_executed": " ".join(cmd), + "stdout": "Parameters written to " + output_param_file, + "stderr": result.stderr, + "output_files": [output_param_file] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": e.stderr, + "stdout": e.stdout + } + +@mcp.tool() +def last_split( + input_maf: str, + output_maf: str, + mismatch_probability: float = 0.1, + reverse_only: bool = False, +): + """ + Find unique alignments for each part of a query (split-mapping). + + Args: + input_maf: Path to the input MAF file. + output_maf: Path to save the split-mapped MAF file. + mismatch_probability: Mismatch probability per base (-m). + reverse_only: Only look for alignments on the reverse strand. + """ + input_path = Path(input_maf) + if not input_path.exists(): + return {"error": f"Input MAF {input_maf} not found."} + + cmd = ["last-split"] + cmd.extend(["-m", str(mismatch_probability)]) + if reverse_only: + cmd.append("-r") + + try: + with open(input_path, "r") as fin, open(output_maf, "w") as fout: + result = subprocess.run(cmd, stdin=fin, stdout=fout, stderr=subprocess.PIPE, text=True, check=True) + + return { + "command_executed": f"last-split {' '.join(cmd[1:])} < {input_maf} > {output_maf}", + "stdout": "Split mapping complete.", + "stderr": result.stderr, + "output_files": [output_maf] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": e.stderr, + "stdout": e.stdout + } + +@mcp.tool() +def maf_convert( + output_format: str, + input_maf: str, + output_file: Optional[str] = None, + include_header: bool = True, +): + """ + Convert LAST MAF format to other formats (SAM, BLAST, etc.). + + Args: + output_format: Target format: 'sam', 'blast', 'blasttab', 'html', 'psl', 'tab'. + input_maf: Path to the input MAF file. + output_file: Path to save the converted output. If None, returns stdout. + include_header: Whether to include the header in the output. + """ + input_path = Path(input_maf) + if not input_path.exists(): + return {"error": f"Input MAF {input_maf} not found."} + + cmd = ["maf-convert"] + if not include_header: + cmd.append("-n") + + cmd.extend([output_format, str(input_path)]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + if output_file: + with open(output_file, "w") as f: + f.write(result.stdout) + return { + "command_executed": " ".join(cmd), + "stdout": f"Converted output saved to {output_file}", + "stderr": result.stderr, + "output_files": [output_file] + } + else: + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": e.stderr, + "stdout": e.stdout + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_last/app/last_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_last/app/last_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a84ec78a1671d0d8abe9a4eaec58615eea1d1dd4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_last/app/last_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_last/app/last_server.py') +SERVER_NAME = 'biosci_last' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_last/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_last/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_last/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_last/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_last/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f11374230c29c61fa7cbe392bccd719c5bbd170f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_last/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-last: + build: . + image: mcp-last:latest + container_name: mcp-last + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=last + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_last/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_last/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3ca4459a1b5cfccdfb8ecc122b0d497c0670d4ff --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_last/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - last + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_last/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_last/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_last/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_lastz/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_lastz/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..a5cd4ea021233528c3a1ffe78a91148969772053 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_lastz/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install lastz via conda (e.g., from bioconda) +RUN conda install -c bioconda lastz -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/lastz_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/lastz_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/lastz_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_lastz/app/lastz_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_lastz/app/lastz_server.py new file mode 100644 index 0000000000000000000000000000000000000000..3d935b839a5d7db709ee3bb4fb41bc35896280f9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_lastz/app/lastz_server.py @@ -0,0 +1,271 @@ +import subprocess +import tempfile +from pathlib import Path +import re +from typing import Optional, List, Dict, Any + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided by the MCP framework. +def tool(func): + def wrapper(*args, **kwargs): + # In a real scenario, the MCP framework would handle marshalling + # and execution. This is a simple pass-through for local testing. + return func(*args, **kwargs) + return wrapper + +mcp = type("mcp", (), {"tool": staticmethod(tool)}) + + +@mcp.tool +def lastz_align( + target: str, + query: Optional[str] = None, + self_align: bool = False, + output: Optional[Path] = None, + seed: Optional[str] = None, + notransition: bool = False, + transition_is_two: bool = False, + step: Optional[int] = None, + strand: str = "both", + ambiguous: Optional[str] = None, + ambiguous_penalty: Optional[int] = None, + gfextend: bool = True, + chain: bool = False, + chain_penalties: Optional[str] = None, + gapped: bool = True, + notrivial: bool = False, + scores: Optional[Path] = None, + match: Optional[str] = None, + gap: str = "400,30", + xdrop: Optional[int] = None, + ydrop: Optional[int] = None, + noxtrim: bool = False, + noytrim: bool = False, + hspthresh: Optional[str] = None, + exact: Optional[int] = None, + inner: Optional[int] = None, + gappedthresh: Optional[str] = None, + entropy: bool = True, + nomirror: bool = False, + allocate_traceback: Optional[str] = None, + masking: int = 0, + identity: Optional[str] = None, + coverage: Optional[str] = None, + format: str = "lav", + rdotplot: Optional[Path] = None, + axt: Optional[Path] = None, + maf: Optional[Path] = None, + progress: Optional[int] = None, +) -> Dict[str, Any]: + """ + LASTZ is a program for aligning DNA sequences, a pairwise aligner. + + Args: + target: Path to the target sequence file (fasta, fastq, nib, 2bit or hsx). + Can include a subrange specifier, e.g., 'myseq.fa[[100..200]]'. + query: Path to the query sequence file. Can also include a subrange. + If absent, and --self is not used, queries are expected from stdin (not supported here). + self_align: If True, the target sequence is also the query. Replaces the query file. + output: Specify the output alignment file. If None, alignments are written to stdout. + seed: Use a word with no gaps instead of a seed pattern (e.g., 'match12'). + notransition: Disallow transitions in a seed hit. + transition_is_two: Allow two transitions in a seed hit. + step: Set step length (default is 1). + strand: Strand to search ('both', 'plus', 'minus'). Default is 'both'. + ambiguous: Treat ambiguous nucleotides as 'n' or 'iupac'. + ambiguous_penalty: Penalty for ambiguous characters when 'ambiguous' is set. + gfextend: Perform gap-free extension of seed hits to HSPs. Default is True. + chain: Perform chaining. Default is False. + chain_penalties: Perform chaining with given penalties for diagonal and anti-diagonal (e.g., 'diag,anti'). + gapped: Perform gapped alignment (instead of gap-free). Default is True. + notrivial: Do not output a trivial self-alignment block if target and query are identical. + scores: Read substitution scores from a file. Default is HOXD70. + match: Scores are +R/-P for match/mismatch (e.g., 'R,P'). + gap: Set gap open and extend penalties. Default is '400,30'. + xdrop: Set x-drop threshold. + ydrop: Set y-drop threshold. + noxtrim: If x-drop extension encounters end of sequence, don't trim back to peak score. + noytrim: If y-drop extension encounters end of sequence, don't trim back to peak score. + hspthresh: Set threshold for high scoring pairs. Can be a score, percentage, or base count. + exact: Set threshold for exact matches. Replaces --hspthresh. + inner: Set threshold for HSPs during interpolation. + gappedthresh: Set threshold for gapped alignments. + entropy: Involve entropy in filtering high scoring pairs. Default is True. + nomirror: Don't report mirror-image alignments when using --self. + allocate_traceback: Space for trace-back information (e.g., '80.0M'). + masking: Mask any position in target hit this many times. 0 indicates no masking. + identity: Filter alignments by percent identity (e.g., '90..100'). + coverage: Filter alignments by percentage of query covered (e.g., '95..100'). + format: Specify output format ('lav', 'axt', 'maf', 'cigar', 'rdotplot', 'text', 'general'). + rdotplot: Create an output file suitable for plotting in R. + axt: Create an output file in AXT format. + maf: Create an output file in MAF format. + progress: Report processing of every nth query. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # --- Input Validation --- + if not query and not self_align: + raise ValueError("Either a query file must be provided or 'self_align' must be True.") + if query and self_align: + raise ValueError("'query' and 'self_align' are mutually exclusive.") + if notransition and transition_is_two: + raise ValueError("'notransition' and 'transition_is_two' are mutually exclusive.") + if hspthresh and exact: + raise ValueError("'hspthresh' and 'exact' are mutually exclusive.") + + # Helper to parse file paths from target/query strings + def parse_seq_spec(spec: str) -> Path: + match = re.match(r"([^[]+)", spec) + if not match: + raise ValueError(f"Could not parse file path from specifier: {spec}") + file_path = Path(match.group(1)) + if not file_path.exists(): + raise FileNotFoundError(f"Input sequence file not found: {file_path}") + return file_path + + parse_seq_spec(target) + if query: + parse_seq_spec(query) + if scores and not scores.exists(): + raise FileNotFoundError(f"Scores file not found: {scores}") + + allowed_strands = ["both", "plus", "minus"] + if strand not in allowed_strands: + raise ValueError(f"Invalid strand '{strand}'. Must be one of {allowed_strands}.") + + allowed_formats = ["lav", "axt", "maf", "cigar", "rdotplot", "text", "general"] + if format not in allowed_formats: + raise ValueError(f"Invalid format '{format}'. Must be one of {allowed_formats}.") + + if ambiguous and ambiguous not in ["n", "iupac"]: + raise ValueError(f"Invalid value for 'ambiguous': {ambiguous}. Must be 'n' or 'iupac'.") + + # --- Command Construction --- + cmd = ["lastz", target] + + if self_align: + cmd.append("--self") + elif query: + cmd.append(query) + + if seed: + cmd.append(f"--seed={seed}") + if notransition: + cmd.append("--notransition") + elif transition_is_two: + cmd.append("--transition=2") + if step is not None: + cmd.append(f"--step={step}") + if strand != "both": # 'both' is the default + cmd.append(f"--strand={strand}") + if ambiguous: + ambiguous_val = ambiguous + if ambiguous_penalty is not None: + ambiguous_val += f",{ambiguous_penalty}" + cmd.append(f"--ambiguous={ambiguous_val}") + + cmd.append("--gfextend" if gfextend else "--nogfextend") + + if chain_penalties: + cmd.append(f"--chain={chain_penalties}") + elif chain: + cmd.append("--chain") + + cmd.append("--gapped" if gapped else "--nogapped") + + if notrivial: + cmd.append("--notrivial") + if scores: + cmd.append(f"--scores={scores}") + if match: + cmd.append(f"--match={match}") + if gap != "400,30": # Only add if not default + cmd.append(f"--gap={gap}") + if xdrop is not None: + cmd.append(f"--xdrop={xdrop}") + if ydrop is not None: + cmd.append(f"--ydrop={ydrop}") + if noxtrim: + cmd.append("--noxtrim") + if noytrim: + cmd.append("--noytrim") + if hspthresh is not None: + cmd.append(f"--hspthresh={hspthresh}") + if exact is not None: + cmd.append(f"--exact={exact}") + if inner is not None: + cmd.append(f"--inner={inner}") + if gappedthresh is not None: + cmd.append(f"--gappedthresh={gappedthresh}") + + cmd.append("--entropy" if entropy else "--noentropy") + + if nomirror: + cmd.append("--nomirror") + if allocate_traceback: + cmd.append(f"--allocate:traceback={allocate_traceback}") + if masking > 0: + cmd.append(f"--masking={masking}") + if identity: + cmd.append(f"--identity={identity}") + if coverage: + cmd.append(f"--coverage={coverage}") + if output: + cmd.append(f"--output={output}") + if format != "lav": # 'lav' is the default + cmd.append(f"--format={format}") + if rdotplot: + cmd.append(f"--rdotplot={rdotplot}") + if axt: + cmd.append(f"--axt={axt}") + if maf: + cmd.append(f"--maf={maf}") + if progress is not None: + cmd.append(f"--progress={progress}") + + # --- Subprocess Execution --- + command_executed = " ".join(map(str, cmd)) + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'lastz' command not found. Please ensure it is in your PATH.", + "output_files": {}, + "return_code": 1 + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": {}, + "return_code": e.returncode + } + + # --- Output Handling --- + output_files = {} + if output: + output_files["main_output"] = str(output) + if rdotplot: + output_files["rdotplot"] = str(rdotplot) + if axt: + output_files["axt"] = str(axt) + if maf: + output_files["maf"] = str(maf) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + "return_code": 0 + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_lastz/app/lastz_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_lastz/app/lastz_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..45c0b593435114be693ddd118a6c8c176d701569 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_lastz/app/lastz_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_lastz/app/lastz_server.py') +SERVER_NAME = 'biosci_lastz' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_lastz/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_lastz/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_lastz/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_lastz/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_lastz/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..a163832603d5db48dc63783237178a716a11dfdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_lastz/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-lastz: + build: . + image: mcp-lastz:latest + container_name: mcp-lastz + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=lastz + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_lastz/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_lastz/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..30976e716e4b66d4b32d377ea6712a7661c9547b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_lastz/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - lastz + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_lastz/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_lastz/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_lastz/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_liana/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_liana/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_liana/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libcifpp/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libcifpp/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..38e86dc750b6aa44aa0c484700d6571e3038d75b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libcifpp/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install libcifpp via conda (e.g., from bioconda) +RUN conda install -c bioconda libcifpp -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/libcifpp_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/libcifpp_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/libcifpp_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libcifpp/app/libcifpp_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libcifpp/app/libcifpp_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c2d84bb01a737952dd8d7fe54ea0a3f49d511e73 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libcifpp/app/libcifpp_server.py @@ -0,0 +1,277 @@ +import subprocess +from pathlib import Path +from typing import Optional, List + +@mcp.tool() +def cif_validate( + input_file: str, + dictionary: Optional[str] = None, + validate_links: bool = False, + check_mandatory: bool = False, + verbose: bool = False +): + """ + Validates a CIF, mmCIF, or PDB file against a CIF dictionary using cif-validate. + + This tool ensures that the file is syntactically valid and its content + conforms to the specified CIF dictionary (e.g., mmcif_pdbx.dic). + + Args: + input_file: Path to the CIF/mmCIF or PDB file to validate. Supports .gz compression. + dictionary: Path to a specific CIF dictionary file. If not provided, the library's internal default dictionary is used. + validate_links: If True, validates parent/child relationships (links) between categories. + check_mandatory: If True, checks if all mandatory items are present. + verbose: If True, provides detailed validation output. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + + cmd = ["cif-validate"] + + if dictionary: + dict_path = Path(dictionary) + if not dict_path.exists(): + return {"error": f"Dictionary file not found: {dictionary}"} + cmd.extend(["--dict", str(dict_path)]) + + if validate_links: + cmd.append("--validate-links") + + if check_mandatory: + cmd.append("--check-mandatory") + + if verbose: + cmd.append("--verbose") + + cmd.append(str(input_path)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "Validation successful" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Validation failed or found issues", + "exit_code": e.returncode + } + +@mcp.tool() +def cif_diff( + file1: str, + file2: str, + quiet: bool = False, + ignore_order: bool = False +): + """ + Compares two CIF files and reports the differences using cif-diff. + + Args: + file1: Path to the first CIF file. + file2: Path to the second CIF file. + quiet: If True, suppresses output and only returns status via exit code. + ignore_order: If True, ignores the order of categories and rows. + """ + p1 = Path(file1) + p2 = Path(file2) + + if not p1.exists(): + return {"error": f"File 1 not found: {file1}"} + if not p2.exists(): + return {"error": f"File 2 not found: {file2}"} + + cmd = ["cif-diff"] + if quiet: + cmd.append("--quiet") + if ignore_order: + cmd.append("--ignore-order") + + cmd.extend([str(p1), str(p2)]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "Files are identical" + } + except subprocess.CalledProcessError as e: + # cif-diff returns 1 if files differ, which is a valid result state + if e.returncode == 1: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "status": "Differences found" + } + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Execution failed with exit code {e.returncode}" + } + +@mcp.tool() +def cif_merge( + input_files: List[str], + output_file: str, + dictionary: Optional[str] = None, + validate: bool = False +): + """ + Merges multiple CIF or PDB files into a single output CIF file using cif-merge. + + Args: + input_files: List of paths to CIF/PDB files to merge. + output_file: Path where the merged CIF file will be saved. + dictionary: Optional path to a CIF dictionary for validation during merging. + validate: If True, performs validation on the merged result. + """ + if not input_files: + return {"error": "No input files provided."} + + cmd = ["cif-merge", "-o", output_file] + + if dictionary: + dict_path = Path(dictionary) + if not dict_path.exists(): + return {"error": f"Dictionary file not found: {dictionary}"} + cmd.extend(["--dict", str(dict_path)]) + + if validate: + cmd.append("--validate") + + for f in input_files: + p = Path(f) + if not p.exists(): + return {"error": f"Input file not found: {f}"} + cmd.append(str(p)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Merge operation failed" + } + +@mcp.tool() +def cif_grep( + query: str, + input_files: List[str], + count: bool = False, + list_files: bool = False +): + """ + Searches for specific data or patterns in one or more CIF files using cif-grep. + + Args: + query: The search pattern or tag name to look for. + input_files: List of paths to CIF/mmCIF files to search. + count: If True, only returns the number of matches found. + list_files: If True, only lists the names of files with matches. + """ + if not input_files: + return {"error": "No input files provided."} + + cmd = ["cif-grep"] + if count: + cmd.append("-c") + if list_files: + cmd.append("-l") + + cmd.append(query) + + for f in input_files: + p = Path(f) + if not p.exists(): + return {"error": f"Input file not found: {f}"} + cmd.append(str(p)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + # grep returns 1 if no matches are found + if e.returncode == 1: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "status": "No matches found" + } + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Search failed with exit code {e.returncode}" + } + +@mcp.tool() +def mmcif_pdbx( + dictionary_file: str, + output_file: Optional[str] = None, + check: bool = False, + convert_to_binary: bool = False +): + """ + Utility tool for working with mmCIF dictionaries (mmcif_pdbx). + + Args: + dictionary_file: Path to the CIF dictionary file (e.g., .dic). + output_file: Optional path for the output file (e.g., compiled dictionary). + check: If True, checks the dictionary for consistency. + convert_to_binary: If True, converts the dictionary to a binary format for faster loading. + """ + p = Path(dictionary_file) + if not p.exists(): + return {"error": f"Dictionary file not found: {dictionary_file}"} + + cmd = ["mmcif_pdbx"] + + if check: + cmd.append("--check") + + if convert_to_binary: + cmd.append("--binary") + + if output_file: + cmd.extend(["-o", output_file]) + + cmd.append(str(p)) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file] if output_file else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Dictionary operation failed" + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libcifpp/app/libcifpp_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libcifpp/app/libcifpp_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..13f14749dcbee49b503058777576ff148056445e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libcifpp/app/libcifpp_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libcifpp/app/libcifpp_server.py') +SERVER_NAME = 'biosci_libcifpp' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libcifpp/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libcifpp/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libcifpp/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libcifpp/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libcifpp/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..fc3376dabe08e7959a5fabf5df07a7565e1a3d47 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libcifpp/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-libcifpp: + build: . + image: mcp-libcifpp:latest + container_name: mcp-libcifpp + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=libcifpp + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libcifpp/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libcifpp/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..38ad866988512d7e8b646acdfb551f933077736b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libcifpp/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - libcifpp + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libcifpp/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libcifpp/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libcifpp/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libdb/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libdb/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libdb/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libdeflate/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libdeflate/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..49409e80936f47683817454756c98374f09cf81f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libdeflate/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install libdeflate via conda (e.g., from bioconda) +RUN conda install -c bioconda libdeflate -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/libdeflate_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/libdeflate_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/libdeflate_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libdeflate/app/libdeflate_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libdeflate/app/libdeflate_server.py new file mode 100644 index 0000000000000000000000000000000000000000..db5e88da6312e6a176fc0f77cba56d725502c26e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libdeflate/app/libdeflate_server.py @@ -0,0 +1,280 @@ +from typing import Optional, List +import subprocess +from pathlib import Path + +@mcp.tool() +def libdeflate_gzip( + input_file: str, + output_file: Optional[str] = None, + compression_level: int = 6, + keep: bool = True, + force: bool = False, + no_name: bool = False, + verbose: bool = False, +): + """ + Compress files using libdeflate-gzip, a fast drop-in replacement for gzip. + + Args: + input_file: Path to the file to compress. + output_file: Optional path for the output .gz file. If not provided, uses input_file + .gz. + compression_level: Compression level (1-12). Higher is better but slower. Default is 6. + keep: Keep (don't delete) input files during compression. Default is True. + force: Force overwrite of output files. + no_name: Do not save or restore the original name and timestamp. + verbose: Verbose mode. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + + if compression_level < 1 or compression_level > 12: + return {"error": "Compression level must be between 1 and 12."} + + cmd = ["libdeflate-gzip"] + + # Compression level + cmd.append(f"-{compression_level}") + + if keep: + cmd.append("-k") + if force: + cmd.append("-f") + if no_name: + cmd.append("-n") + if verbose: + cmd.append("-v") + + cmd.append(str(input_path)) + + # Handle output file redirection if specified + # libdeflate-gzip supports -c for stdout + if output_file: + cmd.insert(1, "-c") + output_path = Path(output_file) + else: + output_path = Path(f"{input_file}.gz") + + try: + if output_file: + with open(output_path, "w") as out_f: + process = subprocess.run( + cmd, + check=True, + stdout=out_f, + stderr=subprocess.PIPE, + text=True + ) + stdout = "Output written to " + output_file + stderr = process.stderr + else: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True + ) + stdout = process.stdout + stderr = process.stderr + + return { + "command_executed": " ".join(cmd), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_path)] if output_path.exists() else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def libdeflate_gunzip( + input_file: str, + output_file: Optional[str] = None, + keep: bool = True, + force: bool = False, + verbose: bool = False, +): + """ + Decompress .gz files using libdeflate-gunzip. + + Args: + input_file: Path to the .gz file to decompress. + output_file: Optional path for the decompressed output. + keep: Keep (don't delete) input files during decompression. Default is True. + force: Force overwrite of output files. + verbose: Verbose mode. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + + cmd = ["libdeflate-gunzip"] + + if keep: + cmd.append("-k") + if force: + cmd.append("-f") + if verbose: + cmd.append("-v") + + cmd.append(str(input_path)) + + # Handle output file redirection + if output_file: + cmd.insert(1, "-c") + output_path = Path(output_file) + else: + # Default gunzip behavior removes .gz + if input_file.endswith(".gz"): + output_path = Path(input_file[:-3]) + else: + output_path = Path(f"{input_file}.out") + + try: + if output_file: + with open(output_path, "w") as out_f: + process = subprocess.run( + cmd, + check=True, + stdout=out_f, + stderr=subprocess.PIPE, + text=True + ) + stdout = "Output written to " + output_file + stderr = process.stderr + else: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True + ) + stdout = process.stdout + stderr = process.stderr + + return { + "command_executed": " ".join(cmd), + "stdout": stdout, + "stderr": stderr, + "output_files": [str(output_path)] if output_path.exists() else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def libdeflate_benchmark( + input_file: str, + compression_level: int = 6, + engine: str = "libdeflate", +): + """ + Run a round-trip compression and decompression benchmark on the provided data. + + Args: + input_file: Path to the data file to benchmark. + compression_level: Compression level to test (1-12). Default is 6. + engine: Compression engine to use. Options: 'libdeflate', 'zlib', or 'both'. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + + if compression_level < 1 or compression_level > 12: + return {"error": "Compression level must be between 1 and 12."} + + # The benchmark tool is usually named 'benchmark' in the libdeflate source + # but might be prefixed in some distributions. + cmd = ["benchmark"] + + cmd.append(f"-{compression_level}") + + if engine.lower() == "zlib": + cmd.append("-zlib") + elif engine.lower() == "both": + cmd.append("-both") + elif engine.lower() != "libdeflate": + return {"error": "Invalid engine. Choose 'libdeflate', 'zlib', or 'both'."} + + cmd.append(str(input_path)) + + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + except FileNotFoundError: + return {"error": "The 'benchmark' executable was not found in the PATH."} + +@mcp.tool() +def libdeflate_checksum( + input_file: str, + algorithm: str = "crc32", +): + """ + Compute Adler-32 or CRC-32 checksums using libdeflate's optimized implementations. + + Args: + input_file: Path to the file to checksum. + algorithm: Checksum algorithm to use. Options: 'crc32' or 'adler32'. + """ + input_path = Path(input_file) + if not input_path.exists(): + return {"error": f"Input file not found: {input_file}"} + + # The checksum tool is usually named 'checksum' in the libdeflate source + cmd = ["checksum"] + + if algorithm.lower() == "adler32": + cmd.append("-adler32") + elif algorithm.lower() == "crc32": + cmd.append("-crc32") + else: + return {"error": "Invalid algorithm. Choose 'crc32' or 'adler32'."} + + cmd.append(str(input_path)) + + try: + process = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + except FileNotFoundError: + return {"error": "The 'checksum' executable was not found in the PATH."} \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libdeflate/app/libdeflate_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libdeflate/app/libdeflate_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d8b3c4efd9f31d7a4ffa9dfb7098e2e024eba837 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libdeflate/app/libdeflate_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libdeflate/app/libdeflate_server.py') +SERVER_NAME = 'biosci_libdeflate' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libdeflate/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libdeflate/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libdeflate/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libdeflate/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libdeflate/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..672ec17d8ddc18ab1bd483d5ed8338f73dca6390 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libdeflate/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-libdeflate: + build: . + image: mcp-libdeflate:latest + container_name: mcp-libdeflate + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=libdeflate + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libdeflate/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libdeflate/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..e3b30e5b91eb620439529d8c62a88e87a2bcaa6e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libdeflate/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - libdeflate + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libdeflate/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libdeflate/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libdeflate/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libsequence/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libsequence/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2100e99912a4b8e8e2314275f3860a7dbeed4d3a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libsequence/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install libsequence via conda (e.g., from bioconda) +RUN conda install -c bioconda libsequence -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/libsequence_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/libsequence_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/libsequence_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libsequence/app/libsequence_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libsequence/app/libsequence_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4b87f886a1919068ae077a86dc2bc9a6d9b6e5cf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libsequence/app/libsequence_server.py @@ -0,0 +1,43 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +# NO NEED to import mcp as per instructions, assuming it's available in the execution environment. + +@mcp.tool() +def libsequence_library_info(): + """ + Provides information about the libsequence C++ class library. + + Based on the provided documentation, libsequence is a C++ class library + for evolutionary genetics and does not expose direct command-line executables + or subcommands that can be run via `subprocess.run`. + + This function serves to inform users about the nature of the tool as described + in its documentation, rather than executing a command-line program. + """ + tool_name = "libsequence" + summary = "A C++ class library for evolutionary genetics." + description = "A C++ class library for evolutionary genetics." + home_url = "http://molpopgen.github.io/libsequence/" + + # Since the provided documentation indicates libsequence is a C++ class library + # and does not describe any command-line executables, we cannot perform + # a `subprocess.run` operation. Instead, we return structured information + # explaining this fact. + info_message = ( + f"Tool: {tool_name}\n" + f"Summary: {summary}\n" + f"Description: {description}\n" + f"Home URL: {home_url}\n\n" + "The provided documentation indicates that libsequence is a C++ class library " + "and does not expose command-line functions or executables. Therefore, " + "no `subprocess.run` operation can be performed for this tool as a direct CLI." + ) + + return { + "command_executed": f"No direct command-line executable found for '{tool_name}' based on documentation.", + "stdout": info_message, + "stderr": "", + "output_files": [], + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libsequence/app/libsequence_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libsequence/app/libsequence_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..07840244818a30ff94f41d5b5bdde2b32061881f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libsequence/app/libsequence_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libsequence/app/libsequence_server.py') +SERVER_NAME = 'biosci_libsequence' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libsequence/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libsequence/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libsequence/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libsequence/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libsequence/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..158fcea9ce40c28e902d44a7b7a619e13de4d21d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libsequence/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-libsequence: + build: . + image: mcp-libsequence:latest + container_name: mcp-libsequence + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=libsequence + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libsequence/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libsequence/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..7800304e4bfd85c7a76a2528cadef6f263efa430 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libsequence/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - libsequence + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libsequence/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libsequence/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_libsequence/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_locarna/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_locarna/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2f54d18f08bf933f847ef9ebbfee1d5e2d6030cb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_locarna/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install locarna via conda (e.g., from bioconda) +RUN conda install -c bioconda locarna -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/locarna_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/locarna_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/locarna_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_locarna/app/locarna_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_locarna/app/locarna_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c9a91e92ef7f90ea6e746c40f4f994cfd657cb99 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_locarna/app/locarna_server.py @@ -0,0 +1,343 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +@mcp.tool() +def locarna( + fasta_1: str, + fasta_2: str, + tau: int = 50, + struct_weight: int = 180, + indel: int = 400, + indel_opening: int = 400, + min_prob: float = 0.0005, + max_diff: int = -1, + max_diff_am: int = -1, + free_endgaps: bool = False, + sequ_weight: int = 100, + match: int = 50, + mismatch: int = 0, + consensus_structure: Optional[str] = None, +) -> Dict[str, Any]: + """ + Perform pairwise local or global alignment of RNA sequences using LocARNA. + + Args: + fasta_1: Path to the first FASTA file. + fasta_2: Path to the second FASTA file. + tau: Sequence contribution (default 50). + struct_weight: Structure contribution (default 180). + indel: Indel penalty (default 400). + indel_opening: Indel opening penalty (default 400). + min_prob: Minimal base pair probability (default 0.0005). + max_diff: Maximal difference for alignment (default -1, no limit). + max_diff_am: Maximal difference for alignment in AM (default -1). + free_endgaps: Whether to allow free endgaps (local alignment). + sequ_weight: Weight for sequence similarity. + match: Match score. + mismatch: Mismatch penalty. + consensus_structure: Optional fixed consensus structure. + """ + p1 = Path(fasta_1) + p2 = Path(fasta_2) + if not p1.exists() or not p2.exists(): + return {"error": "One or both input FASTA files do not exist."} + + cmd = [ + "locarna", + str(p1), + str(p2), + f"--tau={tau}", + f"--struct-weight={struct_weight}", + f"--indel={indel}", + f"--indel-opening={indel_opening}", + f"--min-prob={min_prob}", + f"--max-diff={max_diff}", + f"--max-diff-am={max_diff_am}", + f"--sequ-weight={sequ_weight}", + f"--match={match}", + f"--mismatch={mismatch}" + ] + + if free_endgaps: + cmd.append("--free-endgaps") + if consensus_structure: + cmd.extend(["--consensus-structure", consensus_structure]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def mlocarna( + input_fasta: str, + output_dir: str = "mlocarna_results", + threads: int = 1, + iterative: bool = False, + refinement: bool = False, + probabilistic: bool = False, + consistency: bool = False, + consistency_weight: int = 100, + tg_struct: Optional[str] = None, + min_prob: float = 0.001, +) -> Dict[str, Any]: + """ + Perform multiple alignment of RNA sequences using the mlocarna wrapper. + + Args: + input_fasta: Path to the input FASTA file containing multiple sequences. + output_dir: Directory to store results. + threads: Number of threads to use. + iterative: Use iterative refinement. + refinement: Perform alignment refinement. + probabilistic: Use probabilistic consistency transformation. + consistency: Use consistency transformation. + consistency_weight: Weight for consistency. + tg_struct: Target structure for structure-guided alignment. + min_prob: Minimal base pair probability. + """ + p_in = Path(input_fasta) + if not p_in.exists(): + return {"error": f"Input file {input_fasta} not found."} + + cmd = [ + "mlocarna", + str(p_in), + f"--threads={threads}", + f"--min-prob={min_prob}", + f"--output-dir={output_dir}" + ] + + if iterative: + cmd.append("--iterative") + if refinement: + cmd.append("--refinement") + if probabilistic: + cmd.append("--probabilistic") + if consistency: + cmd.append("--consistency") + cmd.append(f"--consistency-weight={consistency_weight}") + if tg_struct: + cmd.extend(["--tg-struct", tg_struct]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_directory": output_dir, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def locarna_p( + fasta_1: str, + fasta_2: str, + tau: int = 50, + struct_weight: int = 180, + min_prob: float = 0.0005, + temperature: float = 37.0, +) -> Dict[str, Any]: + """ + Calculate the partition function and base pair probabilities for RNA alignment. + + Args: + fasta_1: Path to the first FASTA file. + fasta_2: Path to the second FASTA file. + tau: Sequence contribution. + struct_weight: Structure contribution. + min_prob: Minimal base pair probability. + temperature: Temperature in Celsius. + """ + p1 = Path(fasta_1) + p2 = Path(fasta_2) + if not p1.exists() or not p2.exists(): + return {"error": "Input files not found."} + + cmd = [ + "locarna_p", + str(p1), + str(p2), + f"--tau={tau}", + f"--struct-weight={struct_weight}", + f"--min-prob={min_prob}", + f"--temperature={temperature}" + ] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def sparse_locarna( + fasta_1: str, + fasta_2: str, + exp_prob: float = 0.0, + min_prob: float = 0.0005, + struct_weight: int = 180, + indel: int = 400, +) -> Dict[str, Any]: + """ + Perform memory-efficient RNA alignment using Sparse LocARNA. + + Args: + fasta_1: Path to the first FASTA file. + fasta_2: Path to the second FASTA file. + exp_prob: Expected probability for sparsification. + min_prob: Minimal base pair probability. + struct_weight: Structure contribution. + indel: Indel penalty. + """ + p1 = Path(fasta_1) + p2 = Path(fasta_2) + if not p1.exists() or not p2.exists(): + return {"error": "Input files not found."} + + cmd = [ + "sparse_locarna", + str(p1), + str(p2), + f"--exp-prob={exp_prob}", + f"--min-prob={min_prob}", + f"--struct-weight={struct_weight}", + f"--indel={indel}" + ] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def locarna_eval( + alignment_file: str, + reference_file: str, + verbose: bool = False +) -> Dict[str, Any]: + """ + Evaluate a LocARNA alignment against a reference alignment. + + Args: + alignment_file: Path to the alignment to evaluate (Clustal or Stockholm format). + reference_file: Path to the reference alignment. + verbose: Enable verbose output. + """ + p_aln = Path(alignment_file) + p_ref = Path(reference_file) + + if not p_aln.exists() or not p_ref.exists(): + return {"error": "Alignment or reference file not found."} + + cmd = ["locarna-eval", str(p_aln), str(p_ref)] + if verbose: + cmd.append("--verbose") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } + +@mcp.tool() +def locarna_predict_and_plot( + input_fasta: str, + output_ps: str = "alignment.ps", + width: int = 80, + columns: int = 3 +) -> Dict[str, Any]: + """ + Predict RNA consensus structure and generate a secondary structure plot. + + Args: + input_fasta: Path to the input FASTA/alignment file. + output_ps: Filename for the output PostScript plot. + width: Width of the plot. + columns: Number of columns in the plot. + """ + p_in = Path(input_fasta) + if not p_in.exists(): + return {"error": f"Input file {input_fasta} not found."} + + cmd = [ + "locarna-predict-and-plot", + str(p_in), + "--out", output_ps, + "--width", str(width), + "--columns", str(columns) + ] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_ps], + "status": "success" + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "status": "error" + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_locarna/app/locarna_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_locarna/app/locarna_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0d6b521f1c7dc872b5fc8350c488467e10a59863 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_locarna/app/locarna_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_locarna/app/locarna_server.py') +SERVER_NAME = 'biosci_locarna' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_locarna/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_locarna/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_locarna/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_locarna/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_locarna/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..005c7386259f8d1e35e27864130c4cbd69f4296a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_locarna/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-locarna: + build: . + image: mcp-locarna:latest + container_name: mcp-locarna + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=locarna + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_locarna/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_locarna/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2408eea7d962edc9ea0fa0095488f08e62a86f0c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_locarna/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - locarna + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_locarna/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_locarna/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_locarna/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_macs2/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_macs2/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5e80936eefd4d52f34e5a1361f7153be9de7c3a8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_macs2/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install macs2 via conda (e.g., from bioconda) +RUN conda install -c bioconda macs2 -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/macs2_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/macs2_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/macs2_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_macs2/app/macs2_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_macs2/app/macs2_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f67521f9e6ad66c3085b16164ce2945beefb04ac --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_macs2/app/macs2_server.py @@ -0,0 +1,817 @@ +import subprocess +import logging +from pathlib import Path +from typing import Optional, List, Union, Literal + +# Configure logging +logging.basicConfig(level=logging.INFO) + +# Helper function to generate output file paths for macs2_callpeak +def _get_callpeak_output_files(outdir: Path, name: str, options: dict) -> List[str]: + """Generates a list of expected output files based on MACS2 callpeak options.""" + files = [] + # Common files + files.append(str(outdir / f"{name}_peaks.xls")) + files.append(str(outdir / f"{name}_peaks.narrowPeak")) + if options.get("call_summits"): + files.append(str(outdir / f"{name}_summits.bed")) + if options.get("store_bdg"): + files.append(str(outdir / f"{name}_treat_pileup.bdg")) + if options.get("control_file"): + files.append(str(outdir / f"{name}_control_lambda.bdg")) + if options.get("store_spmr"): + # --SPMR implies -B, so bdg files are created + files.append(str(outdir / f"{name}_treat_pileup.bdg")) + if options.get("control_file"): + files.append(str(outdir / f"{name}_control_lambda.bdg")) + files.append(str(outdir / f"{name}_logLR.bdg")) + files.append(str(outdir / f"{name}_logFE.bdg")) + if options.get("broad"): + files.append(str(outdir / f"{name}_peaks.broadPeak")) + files.append(str(outdir / f"{name}_peaks.gappedPeak")) + + return files + + +@mcp.tool() +def macs2_callpeak( + treatment_file: List[Path], + name: str, + outdir: Path, + control_file: Optional[List[Path]] = None, + format: Literal["AUTO", "BAM", "SAM", "BED", "ELAND", "ELANDMULTI", "ELANDEXPORT", "BOWTIE", "BAMPE", "BEDPE"] = "AUTO", + gsize: str = "hs", + keep_dup: Union[str, int] = "auto", + q_value: float = 0.05, + p_value: Optional[float] = None, + m_fold_lower: int = 5, + m_fold_upper: int = 50, + broad: bool = False, + broad_cutoff: float = 0.1, + no_model: bool = False, + shift: int = 0, + extsize: int = 200, + bandwidth: int = 300, + store_bdg: bool = False, + call_summits: bool = False, + store_spmr: bool = False, + buffer_size: int = 100000, + verbose: int = 2, +) -> dict: + """ + Main MACS2 function to call peaks from alignment files. + + This function identifies transcript factor binding sites from ChIP-Seq data. + It can be used for both narrow and broad peak calling. + """ + # Input validation + if not treatment_file: + raise ValueError("At least one treatment file must be provided.") + for tf in treatment_file: + if not tf.exists(): + raise FileNotFoundError(f"Treatment file not found: {tf}") + if control_file: + for cf in control_file: + if not cf.exists(): + raise FileNotFoundError(f"Control file not found: {cf}") + + if p_value is not None and q_value != 0.05: + logging.warning("Both p-value and q-value are provided. p-value will be used.") + elif p_value is None and q_value == 0.05: + pass # Default behavior + elif p_value is not None and q_value == 0.05: + pass # p-value takes precedence + elif p_value is None and q_value != 0.05: + pass # q-value is used + else: # p_value is not None and q_value is not 0.05 + raise ValueError("p_value and q_value are mutually exclusive. Please provide only one.") + + if m_fold_lower >= m_fold_upper: + raise ValueError("m_fold_lower must be less than m_fold_upper.") + + # Create output directory + outdir.mkdir(parents=True, exist_ok=True) + + # Command construction + cmd = [ + "macs2", "callpeak", + "-t", *[str(f) for f in treatment_file], + "-f", format, + "-g", str(gsize), + "-n", name, + "--outdir", str(outdir), + "--keep-dup", str(keep_dup), + "--mfold", str(m_fold_lower), str(m_fold_upper), + "--bw", str(bandwidth), + "--buffer-size", str(buffer_size), + "-v", str(verbose), + ] + + if control_file: + cmd.extend(["-c", *[str(f) for f in control_file]]) + + if p_value is not None: + cmd.extend(["-p", str(p_value)]) + else: + cmd.extend(["-q", str(q_value)]) + + if broad: + cmd.append("--broad") + cmd.extend(["--broad-cutoff", str(broad_cutoff)]) + + if no_model: + cmd.append("--nomodel") + cmd.extend(["--shift", str(shift)]) + cmd.extend(["--extsize", str(extsize)]) + + if store_bdg: + cmd.append("-B") + + if call_summits: + cmd.append("--call-summits") + + if store_spmr: + cmd.append("--SPMR") + + # Execute command + command_str = " ".join(cmd) + logging.info(f"Executing command: {command_str}") + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + options = { + "call_summits": call_summits, + "store_bdg": store_bdg, + "store_spmr": store_spmr, + "broad": broad, + "control_file": control_file is not None + } + output_files = _get_callpeak_output_files(outdir, name, options) + + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + logging.error(f"MACS2 callpeak failed: {e.stderr}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "MACS2 callpeak execution failed.", + "return_code": e.returncode, + } + + +@mcp.tool() +def macs2_bdgpeakcall( + input_file: Path, + cutoff: float, + min_length: int, + max_gap: int, + outdir: Path, + prefix: str, +) -> dict: + """Call peaks from a bedGraph file using a cutoff.""" + # Input validation + if not input_file.exists(): + raise FileNotFoundError(f"Input bedGraph file not found: {input_file}") + if cutoff <= 0: + raise ValueError("Cutoff must be a positive number.") + if min_length <= 0: + raise ValueError("min_length must be a positive integer.") + if max_gap < 0: + raise ValueError("max_gap must be a non-negative integer.") + + # Create output directory + outdir.mkdir(parents=True, exist_ok=True) + output_file = outdir / f"{prefix}_peaks.narrowPeak" + + # Command construction + cmd = [ + "macs2", "bdgpeakcall", + "-i", str(input_file), + "-c", str(cutoff), + "-l", str(min_length), + "-g", str(max_gap), + "-o", str(output_file), + ] + + # Execute command + command_str = " ".join(cmd) + logging.info(f"Executing command: {command_str}") + 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": [str(output_file)], + } + except subprocess.CalledProcessError as e: + logging.error(f"MACS2 bdgpeakcall failed: {e.stderr}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "MACS2 bdgpeakcall execution failed.", + "return_code": e.returncode, + } + + +@mcp.tool() +def macs2_bdgbroadcall( + input_file: Path, + cutoff: float, + min_length: int, + max_gap: int, + cutoff_peak: float, + outdir: Path, + prefix: str, +) -> dict: + """Call broad peaks from a bedGraph file.""" + # Input validation + if not input_file.exists(): + raise FileNotFoundError(f"Input bedGraph file not found: {input_file}") + if cutoff <= 0 or cutoff_peak <= 0: + raise ValueError("Cutoffs must be positive numbers.") + if min_length <= 0: + raise ValueError("min_length must be a positive integer.") + if max_gap < 0: + raise ValueError("max_gap must be a non-negative integer.") + + # Create output directory + outdir.mkdir(parents=True, exist_ok=True) + output_file = outdir / f"{prefix}_peaks.broadPeak" + + # Command construction + cmd = [ + "macs2", "bdgbroadcall", + "-i", str(input_file), + "-c", str(cutoff), + "-l", str(min_length), + "-g", str(max_gap), + "--cutoff-peak", str(cutoff_peak), + "-o", str(output_file), + ] + + # Execute command + command_str = " ".join(cmd) + logging.info(f"Executing command: {command_str}") + 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": [str(output_file)], + } + except subprocess.CalledProcessError as e: + logging.error(f"MACS2 bdgbroadcall failed: {e.stderr}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "MACS2 bdgbroadcall execution failed.", + "return_code": e.returncode, + } + + +@mcp.tool() +def macs2_bdgcmp( + treatment_bdg: Path, + control_bdg: Path, + method: Literal["ppois", "qpois", "subtract", "logFE", "FE", "logLR"], + outdir: Path, + prefix: str, + pseudocount: Optional[float] = None, +) -> dict: + """Compare two bedGraph files and generate a new bedGraph file.""" + # Input validation + if not treatment_bdg.exists(): + raise FileNotFoundError(f"Treatment bedGraph file not found: {treatment_bdg}") + if not control_bdg.exists(): + raise FileNotFoundError(f"Control bedGraph file not found: {control_bdg}") + + # Create output directory + outdir.mkdir(parents=True, exist_ok=True) + output_file = outdir / f"{prefix}_comp.bdg" + + # Command construction + cmd = [ + "macs2", "bdgcmp", + "-t", str(treatment_bdg), + "-c", str(control_bdg), + "-m", method, + "-o", str(output_file), + ] + if pseudocount is not None: + cmd.extend(["-p", str(pseudocount)]) + + # Execute command + command_str = " ".join(cmd) + logging.info(f"Executing command: {command_str}") + 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": [str(output_file)], + } + except subprocess.CalledProcessError as e: + logging.error(f"MACS2 bdgcmp failed: {e.stderr}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "MACS2 bdgcmp execution failed.", + "return_code": e.returncode, + } + + +@mcp.tool() +def macs2_bdgdiff( + treatment1_bdg: Path, + treatment2_bdg: Path, + control1_bdg: Path, + control2_bdg: Path, + min_length: int, + max_gap: int, + outdir: Path, + prefix: str, + depth1: float = 1.0, + depth2: float = 1.0, +) -> dict: + """Differential peak detection from four bedGraph files.""" + # Input validation + if not treatment1_bdg.exists(): + raise FileNotFoundError(f"Treatment 1 bedGraph file not found: {treatment1_bdg}") + if not treatment2_bdg.exists(): + raise FileNotFoundError(f"Treatment 2 bedGraph file not found: {treatment2_bdg}") + if not control1_bdg.exists(): + raise FileNotFoundError(f"Control 1 bedGraph file not found: {control1_bdg}") + if not control2_bdg.exists(): + raise FileNotFoundError(f"Control 2 bedGraph file not found: {control2_bdg}") + + # Create output directory + outdir.mkdir(parents=True, exist_ok=True) + output_prefix = outdir / prefix + + # Command construction + cmd = [ + "macs2", "bdgdiff", + "--t1", str(treatment1_bdg), + "--t2", str(treatment2_bdg), + "--c1", str(control1_bdg), + "--c2", str(control2_bdg), + "-l", str(min_length), + "-g", str(max_gap), + "--d1", str(depth1), + "--d2", str(depth2), + "-o", str(output_prefix), + ] + + # Execute command + command_str = " ".join(cmd) + logging.info(f"Executing command: {command_str}") + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + output_files = [ + str(f"{output_prefix}_c1_cond1.bed"), + str(f"{output_prefix}_c2_cond2.bed"), + str(f"{output_prefix}_c3_common.bed"), + ] + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + logging.error(f"MACS2 bdgdiff failed: {e.stderr}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "MACS2 bdgdiff execution failed.", + "return_code": e.returncode, + } + + +@mcp.tool() +def macs2_filterdup( + input_file: Path, + output_file: Path, + gsize: str = "hs", + format: Literal["AUTO", "BAM", "SAM", "BED", "ELAND", "ELANDMULTI", "ELANDEXPORT", "BOWTIE", "BAMPE", "BEDPE"] = "AUTO", + keep_dup: Union[str, int] = "auto", + verbose: int = 2, +) -> dict: + """Filter or remove duplicate reads.""" + # Input validation + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + # Create output directory if it doesn't exist + output_file.parent.mkdir(parents=True, exist_ok=True) + + # Command construction + cmd = [ + "macs2", "filterdup", + "-i", str(input_file), + "-f", format, + "-g", gsize, + "--keep-dup", str(keep_dup), + "-o", str(output_file), + "-v", str(verbose), + ] + + # Execute command + command_str = " ".join(cmd) + logging.info(f"Executing command: {command_str}") + 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": [str(output_file)], + } + except subprocess.CalledProcessError as e: + logging.error(f"MACS2 filterdup failed: {e.stderr}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "MACS2 filterdup execution failed.", + "return_code": e.returncode, + } + + +@mcp.tool() +def macs2_predictd( + input_file: Path, + gsize: str, + format: Literal["AUTO", "BAM", "SAM", "BED", "ELAND", "ELANDMULTI", "ELANDEXPORT", "BOWTIE"] = "AUTO", + m_fold_lower: int = 10, + m_fold_upper: int = 30, + outdir: Optional[Path] = None, + randsample: int = 100000, + verbose: int = 2, +) -> dict: + """Predict fragment size 'd' from single-end sequencing data.""" + # Input validation + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + # Command construction + cmd = [ + "macs2", "predictd", + "-i", str(input_file), + "-f", format, + "-g", gsize, + "--mfold", str(m_fold_lower), str(m_fold_upper), + "--randsample", str(randsample), + "-v", str(verbose), + ] + + output_files = [] + if outdir: + outdir.mkdir(parents=True, exist_ok=True) + cmd.extend(["--outdir", str(outdir)]) + # predictd creates a model R script and a PDF plot + output_files.append(str(outdir / f"{input_file.stem}_model.r")) + output_files.append(str(outdir / f"{input_file.stem}_model.pdf")) + + # Execute command + command_str = " ".join(cmd) + logging.info(f"Executing command: {command_str}") + 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": output_files, + } + except subprocess.CalledProcessError as e: + logging.error(f"MACS2 predictd failed: {e.stderr}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "MACS2 predictd execution failed.", + "return_code": e.returncode, + } + + +@mcp.tool() +def macs2_pileup( + input_file: Path, + output_file: Path, + format: Literal["AUTO", "BAM", "SAM", "BED", "ELAND", "ELANDMULTI", "ELANDEXPORT", "BOWTIE", "BAMPE", "BEDPE"] = "AUTO", + extsize: Optional[int] = None, + both_direction: bool = False, +) -> dict: + """Pileup reads from a given alignment file into a bedGraph file.""" + # Input validation + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + # Command construction + cmd = [ + "macs2", "pileup", + "-i", str(input_file), + "-f", format, + "-o", str(output_file), + ] + if extsize is not None: + cmd.extend(["--extsize", str(extsize)]) + if both_direction: + cmd.append("-B") + + # Execute command + command_str = " ".join(cmd) + logging.info(f"Executing command: {command_str}") + 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": [str(output_file)], + } + except subprocess.CalledProcessError as e: + logging.error(f"MACS2 pileup failed: {e.stderr}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "MACS2 pileup execution failed.", + "return_code": e.returncode, + } + + +@mcp.tool() +def macs2_randsample( + input_file: Path, + output_file: Path, + format: Literal["AUTO", "BAM", "SAM", "BED", "ELAND", "ELANDMULTI", "ELANDEXPORT", "BOWTIE", "BAMPE", "BEDPE"] = "AUTO", + percentage: Optional[float] = None, + number: Optional[int] = None, + seed: int = 12345, +) -> dict: + """Randomly sample a specified number or percentage of reads.""" + # Input validation + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if (percentage is None and number is None) or (percentage is not None and number is not None): + raise ValueError("Exactly one of 'percentage' or 'number' must be specified.") + if percentage is not None and not (0 < percentage <= 100): + raise ValueError("Percentage must be between 0 and 100.") + if number is not None and number <= 0: + raise ValueError("Number must be a positive integer.") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + # Command construction + cmd = [ + "macs2", "randsample", + "-i", str(input_file), + "-f", format, + "-o", str(output_file), + "--seed", str(seed), + ] + if percentage is not None: + cmd.extend(["-p", str(percentage)]) + if number is not None: + cmd.extend(["-n", str(number)]) + + # Execute command + command_str = " ".join(cmd) + logging.info(f"Executing command: {command_str}") + 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": [str(output_file)], + } + except subprocess.CalledProcessError as e: + logging.error(f"MACS2 randsample failed: {e.stderr}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "MACS2 randsample execution failed.", + "return_code": e.returncode, + } + + +@mcp.tool() +def macs2_refinepeak( + peak_bed: Path, + read_bed: Path, + output_file: Path, + window_size: int = 200, +) -> dict: + """Refine peak summits by looking for consensus of tag-shifting.""" + # Input validation + if not peak_bed.exists(): + raise FileNotFoundError(f"Peak BED file not found: {peak_bed}") + if not read_bed.exists(): + raise FileNotFoundError(f"Read BED file not found: {read_bed}") + if window_size <= 0: + raise ValueError("Window size must be a positive integer.") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + # Command construction + cmd = [ + "macs2", "refinepeak", + "-i", str(peak_bed), + "-b", str(read_bed), + "-w", str(window_size), + "-o", str(output_file), + ] + + # Execute command + command_str = " ".join(cmd) + logging.info(f"Executing command: {command_str}") + 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": [str(output_file)], + } + except subprocess.CalledProcessError as e: + logging.error(f"MACS2 refinepeak failed: {e.stderr}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "MACS2 refinepeak execution failed.", + "return_code": e.returncode, + } + + +@mcp.tool() +def macs2_hmmratac( + input_file: Path, + name: str, + outdir: Path, + gsize: str = "hs", + format: Literal["AUTO", "BAM", "BED", "BAMPE"] = "AUTO", + p_value: Optional[float] = None, + q_value: float = 0.05, + train: bool = False, + model_file: Optional[Path] = None, + extsize: int = 200, + shift: int = -100, + buffer_size: int = 100000, + verbose: int = 2, +) -> dict: + """Call peaks from ATAC-seq data using a Hidden Markov Model.""" + # Input validation + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if train and model_file: + raise ValueError("Cannot train a new model and use a pre-existing model simultaneously.") + if model_file and not model_file.exists(): + raise FileNotFoundError(f"Model file not found: {model_file}") + if p_value is not None and q_value != 0.05: + raise ValueError("p_value and q_value are mutually exclusive. Please provide only one.") + + outdir.mkdir(parents=True, exist_ok=True) + + # Command construction + cmd = [ + "macs2", "hmmratac", + "-i", str(input_file), + "-n", name, + "--outdir", str(outdir), + "-g", gsize, + "-f", format, + "--extsize", str(extsize), + "--shift", str(shift), + "--buffer-size", str(buffer_size), + "-v", str(verbose), + ] + + if p_value is not None: + cmd.extend(["--pvalue", str(p_value)]) + else: + cmd.extend(["--qvalue", str(q_value)]) + + if train: + cmd.append("--train") + if model_file: + cmd.extend(["--model", str(model_file)]) + + # Execute command + command_str = " ".join(cmd) + logging.info(f"Executing command: {command_str}") + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + output_files = [ + str(outdir / f"{name}_peaks.bed"), + str(outdir / f"{name}_accessible_regions.bed"), + ] + if train: + output_files.append(str(outdir / f"{name}_model.json")) + + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + logging.error(f"MACS2 hmmratac failed: {e.stderr}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "MACS2 hmmratac execution failed.", + "return_code": e.returncode, + } + + +@mcp.tool() +def macs2_diffpeak( + t1_peak: Path, + t2_peak: Path, + d1_bam: Path, + d2_bam: Path, + outdir: Path, + prefix: str, + d_min: int = 200, + d_max: int = 10000, + log_fold: float = 1.0, + p_value: float = 1e-05, + verbose: int = 2, +) -> dict: + """Find differential binding regions from two peak sets and their corresponding read alignment files.""" + # Input validation + if not t1_peak.exists(): + raise FileNotFoundError(f"Treatment 1 peak file not found: {t1_peak}") + if not t2_peak.exists(): + raise FileNotFoundError(f"Treatment 2 peak file not found: {t2_peak}") + if not d1_bam.exists(): + raise FileNotFoundError(f"Condition 1 BAM file not found: {d1_bam}") + if not d2_bam.exists(): + raise FileNotFoundError(f"Condition 2 BAM file not found: {d2_bam}") + + outdir.mkdir(parents=True, exist_ok=True) + output_prefix = outdir / prefix + + # Command construction + cmd = [ + "macs2", "diffpeak", + "-t", str(t1_peak), + "-c", str(t2_peak), + "--d1", str(d1_bam), + "--d2", str(d2_bam), + "--outdir", str(outdir), + "--prefix", prefix, + "--d-min", str(d_min), + "--d-max", str(d_max), + "--log-fold", str(log_fold), + "--pvalue", str(p_value), + "-v", str(verbose), + ] + + # Execute command + command_str = " ".join(cmd) + logging.info(f"Executing command: {command_str}") + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + output_files = [ + str(f"{output_prefix}_cond1.bed"), + str(f"{output_prefix}_cond2.bed"), + str(f"{output_prefix}_common.bed"), + str(f"{output_prefix}_diff.xls"), + ] + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + logging.error(f"MACS2 diffpeak failed: {e.stderr}") + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": "MACS2 diffpeak execution failed.", + "return_code": e.returncode, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_macs2/app/macs2_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_macs2/app/macs2_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..c71b1b6ce0cba8b6be740406ac98ae8f4eb109e8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_macs2/app/macs2_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_macs2/app/macs2_server.py') +SERVER_NAME = 'biosci_macs2' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_macs2/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_macs2/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_macs2/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_macs2/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_macs2/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..398a9f162633109399a3ad86de92e41fe5904d43 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_macs2/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-macs2: + build: . + image: mcp-macs2:latest + container_name: mcp-macs2 + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=macs2 + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_macs2/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_macs2/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d427c2ed79d1a0fe938fa4a079ba87b8acceaafe --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_macs2/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - macs2 + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_macs2/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_macs2/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_macs2/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mafft/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mafft/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..c10a3d9828c29e1b54eab65d532cc6fb0e433815 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mafft/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install mafft via conda (e.g., from bioconda) +RUN conda install -c bioconda mafft -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/mafft_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/mafft_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/mafft_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mafft/app/mafft_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mafft/app/mafft_server.py new file mode 100644 index 0000000000000000000000000000000000000000..176c43f762c85341372273bcbe5f1b23ff3de728 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mafft/app/mafft_server.py @@ -0,0 +1,289 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, Literal, Dict, List +import shlex + +# No mcp import is needed as per the instructions. + +# @mcp.tool() decorator is assumed to be present in the execution environment. + +def _run_mafft_command(cmd: List[str], output_file: Optional[Path]) -> Dict: + """Helper function to execute a MAFFT command and handle I/O.""" + command_str = shlex.join(cmd) + + # MAFFT writes the main output to stdout, so we redirect it to a file. + if output_file: + final_output_path = output_file + # Ensure parent directory exists + final_output_path.parent.mkdir(parents=True, exist_ok=True) + else: + # Create a temporary file if no output path is given + with tempfile.NamedTemporaryFile(mode="w", suffix=".fasta", delete=False) as tmp_out: + final_output_path = Path(tmp_out.name) + + try: + with open(final_output_path, "w") as output_handle: + process = subprocess.run( + cmd, + stdout=output_handle, + stderr=subprocess.PIPE, + text=True, + check=True + ) + + stdout_msg = f"Alignment successfully written to {final_output_path}." + + return { + "command_executed": command_str, + "stdout": stdout_msg, + "stderr": process.stderr, + "output_files": {"alignment": str(final_output_path)} + } + + except FileNotFoundError: + return { + "command_executed": command_str, + "stdout": "", + "stderr": "mafft command not found. Please ensure MAFFT is installed and in your system's PATH.", + "output_files": {} + } + except subprocess.CalledProcessError as e: + # If the process fails, the output file might be empty or incomplete, but we still report its path. + return { + "command_executed": command_str, + "stdout": e.stdout or "", + "stderr": e.stderr or f"MAFFT execution failed with return code {e.returncode}.", + "output_files": {"alignment": str(final_output_path)} + } + +@mcp.tool() +def mafft_align( + input_file: Path, + output_file: Optional[Path] = None, + strategy: Literal[ + "auto", "fftns1", "fftns2", "fftnsi", "linsi", "ginsi", "einsi", "parttree" + ] = "auto", + sequence_type: Literal["auto", "amino", "nuc"] = "auto", + retree: int = 2, + maxiterate: int = 0, + scoring_matrix: Optional[Literal[ + "blosum30", "blosum45", "blosum62", "blosum80", + "jtt100", "jtt200", "tm200" + ]] = None, + op: float = 1.53, + ep: float = 0.0, + threads: int = 1, + output_format: Literal["fasta", "clustal", "phylip"] = "fasta", + reorder: bool = False, + quiet: bool = False, +) -> Dict: + """ + Performs de novo multiple sequence alignment on a set of sequences using MAFFT. + + This function wraps the main alignment functionalities of MAFFT, allowing the user + to select from various strategies for speed and accuracy. + + Args: + input_file: Path to the input FASTA file containing unaligned sequences. + output_file: Optional path to save the output alignment. If not provided, a temporary file is created. + strategy: The alignment strategy to use. + 'auto': Automatically selects an appropriate strategy (FFT-NS-2 or L-INS-i). + 'fftns1': FFT-NS-1; the fastest method, one-pass. + 'fftns2': FFT-NS-2; fast, two-pass. Default for 'auto' with >200 sequences. + 'fftnsi': FFT-NS-i; iterative refinement method. + 'linsi': L-INS-i; accurate for alignments of <200 sequences with local homology. + 'ginsi': G-INS-i; accurate for alignments of <200 sequences with global homology. + 'einsi': E-INS-i; suitable for sequences with N/C-terminal extensions. + 'parttree': PartTree algorithm; very fast for a large number of sequences. + sequence_type: The type of sequences. 'auto' lets MAFFT decide. + retree: Number of times to rebuild the guide tree in iterative refinement. + maxiterate: Maximum number of iterations for refinement (0 means auto). + scoring_matrix: The scoring matrix for amino acid sequences. If None, MAFFT's default is used. + op: Gap opening penalty. + ep: Gap extension penalty (offset value). + threads: Number of threads to use. + output_format: The format for the output alignment file. + reorder: Reorder sequences according to the guide tree. + quiet: Suppress progress messages. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a dictionary of output files. + """ + # --- Input Validation --- + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if threads <= 0: + raise ValueError("Number of threads must be a positive integer.") + if retree < 0: + raise ValueError("'retree' must be a non-negative integer.") + if maxiterate < 0: + raise ValueError("'maxiterate' must be a non-negative integer.") + + # --- Command Construction --- + cmd = ["mafft"] + + # Strategy + strategy_map = { + "fftns1": "--fftns1", "fftns2": "--fftns2", "fftnsi": "--fftnsi", + "linsi": "--linsi", "ginsi": "--ginsi", "einsi": "--einsi", + "parttree": "--parttree", + } + if strategy != "auto": + cmd.append(strategy_map[strategy]) + + # Sequence Type + if sequence_type == "amino": + cmd.append("--amino") + elif sequence_type == "nuc": + cmd.append("--nuc") + + # Iteration and Refinement (applicable to iterative methods) + if strategy in ["auto", "fftnsi", "linsi", "ginsi", "einsi"]: + cmd.extend(["--retree", str(retree)]) + if maxiterate > 0: + cmd.extend(["--maxiterate", str(maxiterate)]) + + # Scoring Matrix + if scoring_matrix: + if scoring_matrix.startswith("blosum"): + cmd.extend(["--bl", scoring_matrix[6:]]) + elif scoring_matrix.startswith("jtt"): + cmd.extend(["--jtt", scoring_matrix[3:]]) + elif scoring_matrix.startswith("tm"): + cmd.extend(["--tm", scoring_matrix[2:]]) + + # Gap Penalties + cmd.extend(["--op", str(op)]) + cmd.extend(["--ep", str(ep)]) + + # Performance + if threads > 1: + cmd.extend(["--thread", str(threads)]) + + # Output Format + if output_format == "clustal": + cmd.append("--clustalout") + elif output_format == "phylip": + cmd.append("--phylipout") + + if reorder: + cmd.append("--reorder") + if quiet: + cmd.append("--quiet") + + # Input file must be the last argument before redirection + cmd.append(str(input_file)) + + return _run_mafft_command(cmd, output_file) + +@mcp.tool() +def mafft_add( + existing_alignment: Path, + new_sequences: Path, + output_file: Optional[Path] = None, + mode: Literal["add", "addfragments", "addfull"] = "add", + threads: int = 1, + reorder: bool = False, + keeplength: bool = False, + quiet: bool = False, +) -> Dict: + """ + Adds new sequences or fragments to an existing MAFFT alignment. + + This function is for profile alignment, where you have a trusted existing alignment + and want to add new sequences to it without re-aligning everything from scratch. + + Args: + existing_alignment: Path to the FASTA file of the pre-aligned sequences. + new_sequences: Path to the FASTA file with new sequences to add. + output_file: Optional path to save the final combined alignment. + mode: The method for adding sequences. + 'add': General purpose for adding new sequences. + 'addfragments': Optimized for adding short fragment sequences. + 'addfull': For adding full-length sequences (less common). + threads: Number of threads to use. + reorder: Reorder all sequences according to the newly built guide tree. + keeplength: Keep the alignment length the same as the existing alignment. + quiet: Suppress progress messages. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # --- Input Validation --- + if not existing_alignment.is_file(): + raise FileNotFoundError(f"Existing alignment file not found: {existing_alignment}") + if not new_sequences.is_file(): + raise FileNotFoundError(f"File with new sequences not found: {new_sequences}") + if threads <= 0: + raise ValueError("Number of threads must be a positive integer.") + + # --- Command Construction --- + cmd = ["mafft"] + + # Mode + cmd.append(f"--{mode}") + + # Performance + if threads > 1: + cmd.extend(["--thread", str(threads)]) + + if reorder: + cmd.append("--reorder") + if keeplength: + cmd.append("--keeplength") + if quiet: + cmd.append("--quiet") + + # For --add modes, the argument order is `mafft --add new_seqs existing_aln` + cmd.append(str(new_sequences)) + cmd.append(str(existing_alignment)) + + return _run_mafft_command(cmd, output_file) + +@mcp.tool() +def mafft_adjust_direction( + input_file: Path, + output_file: Optional[Path] = None, + accurate: bool = False, + threads: int = 1, + quiet: bool = False, +) -> Dict: + """ + Adjusts the direction of nucleotide sequences in a FASTA file. + + This utility is useful for correcting the orientation of sequences (e.g., reverse + complements) in a set of unaligned nucleotide sequences before alignment. + + Args: + input_file: Path to the input FASTA file with unaligned nucleotide sequences. + output_file: Optional path to save the direction-adjusted sequences. + accurate: Use a more accurate but slower method for direction adjustment. + threads: Number of threads to use. + quiet: Suppress progress messages. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # --- Input Validation --- + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if threads <= 0: + raise ValueError("Number of threads must be a positive integer.") + + # --- Command Construction --- + cmd = ["mafft"] + + if accurate: + cmd.append("--adjustdirectionaccurately") + else: + cmd.append("--adjustdirection") + + if threads > 1: + cmd.extend(["--thread", str(threads)]) + if quiet: + cmd.append("--quiet") + + cmd.append(str(input_file)) + + return _run_mafft_command(cmd, output_file) \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mafft/app/mafft_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mafft/app/mafft_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..6faa1411130cc3d721e54e0c2b7d12ae5d570335 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mafft/app/mafft_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mafft/app/mafft_server.py') +SERVER_NAME = 'biosci_mafft' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mafft/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mafft/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mafft/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mafft/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mafft/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..10e61ed3da5a2cf7e808eb5d2c7825ed857ad9bc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mafft/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-mafft: + build: . + image: mcp-mafft:latest + container_name: mcp-mafft + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=mafft + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mafft/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mafft/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..528cfdd78e184f76a33f79fa8788cc6913ac0285 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mafft/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - mafft + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mafft/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mafft/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mafft/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mageck/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mageck/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4cf7afbb0214ab52f8cd6b6edf2d42fd9151ec22 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mageck/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install mageck via conda (e.g., from bioconda) +RUN conda install -c bioconda mageck -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/mageck_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/mageck_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/mageck_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mageck/app/mageck_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mageck/app/mageck_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2d09a74aa26a69206cdb188c620f1c067224a73d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mageck/app/mageck_server.py @@ -0,0 +1,646 @@ +import subprocess +import logging +from pathlib import Path +from typing import List, Optional, Literal + +# Set up a logger for better feedback +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) + +# This is a mock decorator. In a real MCP environment, this would be provided by the MCP framework. +class mcp: + @staticmethod + def tool(): + def decorator(f): + return f + return decorator + +@mcp.tool() +def mageck_count( + library_file: Path, + fastq_files: List[Path], + sample_labels: List[str], + output_prefix: str, + sgrna_len: int = 20, + trim_5: int = 0, + count_n: bool = False, + unmapped_to_file: bool = False, + pdf_report: bool = False, + norm_method: Literal['median', 'total', 'none'] = 'median', + day0_label: Optional[str] = None, + gmt_file: Optional[Path] = None, + additional_id: bool = False, + threads: int = 1 +) -> dict: + """ + Run the MAGeCK 'count' command to generate a read count table from FASTQ files. + + Args: + library_file: The library file used in the screen. + fastq_files: A list of FASTQ files for read counting. + sample_labels: The labels for samples, corresponding to the FASTQ files. + output_prefix: The prefix for the output file(s). + sgrna_len: The length of the sgRNA sequence. + trim_5: The number of base pairs to be trimmed from the 5' end. + count_n: If True, count sgRNAs containing 'N' bases. + unmapped_to_file: If True, save unmapped reads to a file. + pdf_report: If True, generate a PDF report of the quality control. + norm_method: Method for normalization ('median', 'total', 'none'). + day0_label: The sample label for day 0. Must be in the sample_labels list. + gmt_file: The GMT file for pathway analysis on QC results. + additional_id: If True, add an additional column for gene IDs in the count table. + threads: The number of threads to use. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # Input validation + if not library_file.is_file(): + raise FileNotFoundError(f"Library file not found: {library_file}") + if not fastq_files: + raise ValueError("At least one FASTQ file must be provided.") + for fq in fastq_files: + if not fq.is_file(): + raise FileNotFoundError(f"FASTQ file not found: {fq}") + if len(fastq_files) != len(sample_labels): + raise ValueError("The number of FASTQ files must match the number of sample labels.") + if day0_label and day0_label not in sample_labels: + raise ValueError(f"day0_label '{day0_label}' not found in sample_labels.") + if gmt_file and not gmt_file.is_file(): + raise FileNotFoundError(f"GMT file not found: {gmt_file}") + if threads < 1: + raise ValueError("Number of threads must be at least 1.") + + # Command construction + cmd = [ + "mageck", "count", + "-l", str(library_file), + "-r" + ] + cmd.extend([str(f) for f in fastq_files]) + cmd.extend(["--sample-label", ",".join(sample_labels)]) + cmd.extend(["-n", output_prefix]) + cmd.extend(["--sgrna-len", str(sgrna_len)]) + cmd.extend(["--trim-5", str(trim_5)]) + cmd.extend(["--norm-method", norm_method]) + cmd.extend(["--threads", str(threads)]) + + if count_n: + cmd.append("--count-n") + if unmapped_to_file: + cmd.append("--unmapped-to-file") + if pdf_report: + cmd.append("--pdf-report") + if day0_label: + cmd.extend(["--day0-label", day0_label]) + if gmt_file: + cmd.extend(["--gmt-file", str(gmt_file)]) + if additional_id: + cmd.append("--additional-id") + + # Execute command + command_executed = " ".join(cmd) + logger.info(f"Executing command: {command_executed}") + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True + ) + + # Define expected output files + output_files = [ + f"{output_prefix}.count.txt", + f"{output_prefix}.log", + f"{output_prefix}.countsummary.txt" + ] + if pdf_report: + output_files.append(f"{output_prefix}.QC.pdf") + if unmapped_to_file: + output_files.extend([f"{label}.unmapped.fastq" for label in sample_labels]) + + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(Path(f)) for f in output_files if Path(f).exists()] + } + except subprocess.CalledProcessError as e: + logger.error(f"MAGeCK count failed with exit code {e.returncode}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Process failed with exit code {e.returncode}" + } + +@mcp.tool() +def mageck_test( + count_table: Path, + treatment_samples: List[str], + control_samples: List[str], + output_prefix: str, + sgrna_len: int = 20, + adjust_method: Literal['fdr', 'holm', 'pounds'] = 'fdr', + sort_by: Literal['pos', 'neg'] = 'pos', + variance_estimation_samples: Optional[List[str]] = None, + remove_zero: Literal['none', 'control', 'all', 'both'] = 'none', + remove_zero_threshold: int = 0, + norm_method: Literal['median', 'total', 'control', 'none'] = 'median', + control_sgrna: Optional[Path] = None, + paired: bool = False, + permutation_round: int = 10000, + pdf_plot: bool = False, + gene_lfc_method: Literal['alphamean', 'mean'] = 'alphamean', + gene_test_fdr_threshold: float = 0.25, + cnv_norm: Optional[Path] = None, + cell_line: Optional[str] = None, + control_gene: Optional[Path] = None +) -> dict: + """ + Run the MAGeCK 'test' command to perform statistical tests on a count table. + + Args: + count_table: The read count table from 'mageck count'. + treatment_samples: A list of treatment sample labels. + control_samples: A list of control sample labels. + output_prefix: The prefix for the output file(s). + sgrna_len: The length of the sgRNA sequence. + adjust_method: Method for multiple testing correction. + sort_by: Sort gene summary by positive ('pos') or negative ('neg') selection. + variance_estimation_samples: Sample labels for variance estimation. + remove_zero: Method to remove zero counts. + remove_zero_threshold: Threshold for removing zero counts. + norm_method: Method for normalization. + control_sgrna: A file containing a list of control sgRNAs. + paired: If True, perform a paired test. + permutation_round: The number of permutations. + pdf_plot: If True, generate PDF plots. + gene_lfc_method: Method to calculate gene Log Fold Change (LFC). + gene_test_fdr_threshold: The FDR threshold for gene testing. + cnv_norm: The Copy Number Variation (CNV) normalization file. + cell_line: The cell line for CNV normalization. + control_gene: The control gene file for normalization. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # Input validation + if not count_table.is_file(): + raise FileNotFoundError(f"Count table not found: {count_table}") + if not treatment_samples: + raise ValueError("At least one treatment sample must be provided.") + if not control_samples: + raise ValueError("At least one control sample must be provided.") + if paired and len(treatment_samples) != len(control_samples): + raise ValueError("For paired tests, the number of treatment and control samples must be equal.") + if control_sgrna and not control_sgrna.is_file(): + raise FileNotFoundError(f"Control sgRNA file not found: {control_sgrna}") + if cnv_norm and not cnv_norm.is_file(): + raise FileNotFoundError(f"CNV normalization file not found: {cnv_norm}") + if control_gene and not control_gene.is_file(): + raise FileNotFoundError(f"Control gene file not found: {control_gene}") + + # Command construction + cmd = [ + "mageck", "test", + "-k", str(count_table), + "-t", ",".join(treatment_samples), + "-c", ",".join(control_samples), + "-n", output_prefix, + "--sgrna-len", str(sgrna_len), + "--adjust-method", adjust_method, + "--sort-by", sort_by, + "--remove-zero", remove_zero, + "--remove-zero-threshold", str(remove_zero_threshold), + "--norm-method", norm_method, + "--permutation-round", str(permutation_round), + "--gene-lfc-method", gene_lfc_method, + "--gene-test-fdr-threshold", str(gene_test_fdr_threshold) + ] + + if variance_estimation_samples: + cmd.extend(["--variance-estimation-samples", ",".join(variance_estimation_samples)]) + if control_sgrna: + cmd.extend(["--control-sgrna", str(control_sgrna)]) + if paired: + cmd.append("--paired") + if pdf_plot: + cmd.append("--pdf-plot") + if cnv_norm: + cmd.extend(["--cnv-norm", str(cnv_norm)]) + if cell_line: + cmd.extend(["--cell-line", cell_line]) + if control_gene: + cmd.extend(["--control-gene", str(control_gene)]) + + # Execute command + command_executed = " ".join(cmd) + logger.info(f"Executing command: {command_executed}") + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True + ) + + output_files = [ + f"{output_prefix}.gene_summary.txt", + f"{output_prefix}.sgrna_summary.txt", + f"{output_prefix}.log" + ] + if pdf_plot: + output_files.append(f"{output_prefix}.plot.pdf") + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(Path(f)) for f in output_files if Path(f).exists()] + } + except subprocess.CalledProcessError as e: + logger.error(f"MAGeCK test failed with exit code {e.returncode}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Process failed with exit code {e.returncode}" + } + +@mcp.tool() +def mageck_mle( + count_table: Path, + design_matrix: Path, + output_prefix: str, + sgrna_len: int = 20, + norm_method: Literal['median', 'total', 'control', 'none'] = 'median', + control_sgrna: Optional[Path] = None, + threads: int = 1, + permutation_round: int = 10000, + pdf_plot: bool = False, + gene_lfc_method: Literal['alphamean', 'mean'] = 'alphamean', + gene_test_fdr_threshold: float = 0.25, + cnv_norm: Optional[Path] = None, + cell_line: Optional[str] = None, + control_gene: Optional[Path] = None, + beta_labels: Optional[List[str]] = None +) -> dict: + """ + Run the MAGeCK 'mle' command for Maximum-Likelihood Estimation based analysis. + + Args: + count_table: The read count table from 'mageck count'. + design_matrix: The design matrix file. + output_prefix: The prefix for the output file(s). + sgrna_len: The length of the sgRNA sequence. + norm_method: Method for normalization. + control_sgrna: A file containing a list of control sgRNAs. + threads: The number of threads to use. + permutation_round: The number of permutations. + pdf_plot: If True, generate PDF plots. + gene_lfc_method: Method to calculate gene Log Fold Change (LFC). + gene_test_fdr_threshold: The FDR threshold for gene testing. + cnv_norm: The Copy Number Variation (CNV) normalization file. + cell_line: The cell line for CNV normalization. + control_gene: The control gene file for normalization. + beta_labels: Labels for beta scores, separated by comma. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # Input validation + if not count_table.is_file(): + raise FileNotFoundError(f"Count table not found: {count_table}") + if not design_matrix.is_file(): + raise FileNotFoundError(f"Design matrix file not found: {design_matrix}") + if control_sgrna and not control_sgrna.is_file(): + raise FileNotFoundError(f"Control sgRNA file not found: {control_sgrna}") + if cnv_norm and not cnv_norm.is_file(): + raise FileNotFoundError(f"CNV normalization file not found: {cnv_norm}") + if control_gene and not control_gene.is_file(): + raise FileNotFoundError(f"Control gene file not found: {control_gene}") + if threads < 1: + raise ValueError("Number of threads must be at least 1.") + + # Command construction + cmd = [ + "mageck", "mle", + "-k", str(count_table), + "-d", str(design_matrix), + "-n", output_prefix, + "--sgrna-len", str(sgrna_len), + "--norm-method", norm_method, + "--threads", str(threads), + "--permutation-round", str(permutation_round), + "--gene-lfc-method", gene_lfc_method, + "--gene-test-fdr-threshold", str(gene_test_fdr_threshold) + ] + + if control_sgrna: + cmd.extend(["--control-sgrna", str(control_sgrna)]) + if pdf_plot: + cmd.append("--pdf-plot") + if cnv_norm: + cmd.extend(["--cnv-norm", str(cnv_norm)]) + if cell_line: + cmd.extend(["--cell-line", cell_line]) + if control_gene: + cmd.extend(["--control-gene", str(control_gene)]) + if beta_labels: + cmd.extend(["--beta-labels", ",".join(beta_labels)]) + + # Execute command + command_executed = " ".join(cmd) + logger.info(f"Executing command: {command_executed}") + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True + ) + + output_files = [ + f"{output_prefix}.gene_summary.txt", + f"{output_prefix}.sgrna_summary.txt", + f"{output_prefix}.log" + ] + if pdf_plot: + output_files.append(f"{output_prefix}.plot.pdf") + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(Path(f)) for f in output_files if Path(f).exists()] + } + except subprocess.CalledProcessError as e: + logger.error(f"MAGeCK mle failed with exit code {e.returncode}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Process failed with exit code {e.returncode}" + } + +@mcp.tool() +def mageck_pathway( + gene_ranking: Path, + output_prefix: str, + gmt_file: Optional[Path] = None, + permutation: int = 1000, + fdr_method: Literal['fdr', 'holm'] = 'fdr', + pathway_size_min: int = 10, + pathway_size_max: int = 500 +) -> dict: + """ + Run the MAGeCK 'pathway' command for pathway enrichment analysis. + + Args: + gene_ranking: The gene summary file from 'mageck test' or 'mageck mle'. + output_prefix: The prefix for the output file(s). + gmt_file: The GMT file for pathway analysis. + permutation: The number of permutations. + fdr_method: The method for multiple testing correction. + pathway_size_min: The minimum size of a pathway. + pathway_size_max: The maximum size of a pathway. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # Input validation + if not gene_ranking.is_file(): + raise FileNotFoundError(f"Gene ranking file not found: {gene_ranking}") + if gmt_file and not gmt_file.is_file(): + raise FileNotFoundError(f"GMT file not found: {gmt_file}") + if pathway_size_min < 1: + raise ValueError("pathway_size_min must be at least 1.") + if pathway_size_max < pathway_size_min: + raise ValueError("pathway_size_max must be greater than or equal to pathway_size_min.") + + # Command construction + cmd = [ + "mageck", "pathway", + "--gene-ranking", str(gene_ranking), + "-n", output_prefix, + "--permutation", str(permutation), + "--fdr-method", fdr_method, + "--pathway-size-min", str(pathway_size_min), + "--pathway-size-max", str(pathway_size_max) + ] + + if gmt_file: + cmd.extend(["--gmt-file", str(gmt_file)]) + + # Execute command + command_executed = " ".join(cmd) + logger.info(f"Executing command: {command_executed}") + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True + ) + + output_files = [f"{output_prefix}.pathway_summary.txt"] + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(Path(f)) for f in output_files if Path(f).exists()] + } + except subprocess.CalledProcessError as e: + logger.error(f"MAGeCK pathway failed with exit code {e.returncode}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Process failed with exit code {e.returncode}" + } + +@mcp.tool() +def mageck_flute( + gene_summary: Path, + output_prefix: str, + treatment_id: Optional[List[str]] = None, + control_id: Optional[List[str]] = None, + top: int = 5, + remove_prefix: bool = False, + x_axis: Optional[str] = None, + y_axis: Optional[str] = None, + label_column: Optional[str] = None, + width: float = 8.0, + height: float = 6.0, + plot_type: Literal['volcano', 'rank', 'square'] = 'volcano', + scale_by_size: bool = False, + day0: bool = False +) -> dict: + """ + Run the MAGeCK 'flute' command for visualizing MAGeCK results. + + Args: + gene_summary: The gene summary file from 'mageck test'. + output_prefix: The prefix for the output file(s). + treatment_id: The treatment sample label(s). + control_id: The control sample label(s). + top: The number of top-ranked genes to label in the plot. + remove_prefix: If True, remove prefix in the gene names. + x_axis: The column name for the x-axis. + y_axis: The column name for the y-axis. + label_column: The column name for labels. + width: The width of the plot. + height: The height of the plot. + plot_type: The type of the plot. + scale_by_size: If True, scale the plot by size. + day0: If True, indicates the screen is a day 0 screen. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # Input validation + if not gene_summary.is_file(): + raise FileNotFoundError(f"Gene summary file not found: {gene_summary}") + + # Command construction + cmd = [ + "mageck", "flute", + str(gene_summary), + "-n", output_prefix, + "--top", str(top), + "--width", str(width), + "--height", str(height), + "--plot-type", plot_type + ] + + if treatment_id: + cmd.extend(["--treatment-id", ",".join(treatment_id)]) + if control_id: + cmd.extend(["--control-id", ",".join(control_id)]) + if remove_prefix: + cmd.append("--remove-prefix") + if x_axis: + cmd.extend(["--x-axis", x_axis]) + if y_axis: + cmd.extend(["--y-axis", y_axis]) + if label_column: + cmd.extend(["--label", label_column]) + if scale_by_size: + cmd.append("--scale-by-size") + if day0: + cmd.append("--day0") + + # Execute command + command_executed = " ".join(cmd) + logger.info(f"Executing command: {command_executed}") + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True + ) + + # Flute can generate multiple plots. This is a best-effort guess. + output_files = [ + f"{output_prefix}_volcano.pdf", + f"{output_prefix}_rank.pdf", + f"{output_prefix}_square.pdf", + f"{output_prefix}_summary.txt" + ] + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(Path(f)) for f in output_files if Path(f).exists()] + } + except subprocess.CalledProcessError as e: + logger.error(f"MAGeCK flute failed with exit code {e.returncode}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Process failed with exit code {e.returncode}" + } + +@mcp.tool() +def mageck_vispr( + count_table: Path, + sample_labels: List[str], + design_matrix: Path, + output_prefix: str, + sgrna_len: int = 20, + norm_method: Literal['median', 'total', 'none'] = 'median', + project_name: Optional[str] = None +) -> dict: + """ + Run the MAGeCK 'vispr' command to generate files for VISPR visualization. + + Args: + count_table: The read count table from 'mageck count'. + sample_labels: The labels for samples, separated by comma. + design_matrix: The design matrix file. + output_prefix: The prefix for the output file(s) and directory. + sgrna_len: The length of the sgRNA sequence. + norm_method: Method for normalization. + project_name: The name of the project. + + Returns: + A dictionary containing the executed command, stdout, stderr, and the output directory. + """ + # Input validation + if not count_table.is_file(): + raise FileNotFoundError(f"Count table not found: {count_table}") + if not design_matrix.is_file(): + raise FileNotFoundError(f"Design matrix file not found: {design_matrix}") + if not sample_labels: + raise ValueError("At least one sample label must be provided.") + + # Command construction + cmd = [ + "mageck", "vispr", + "-k", str(count_table), + "-l", ",".join(sample_labels), + "-d", str(design_matrix), + "-n", output_prefix, + "--sgrna-len", str(sgrna_len), + "--norm-method", norm_method + ] + + if project_name: + cmd.extend(["--project-name", project_name]) + + # Execute command + command_executed = " ".join(cmd) + logger.info(f"Executing command: {command_executed}") + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True + ) + + # VISPR creates a directory with the name of the output prefix + output_dir = Path(output_prefix) + output_files = [str(output_dir)] if output_dir.is_dir() else [] + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + logger.error(f"MAGeCK vispr failed with exit code {e.returncode}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"Process failed with exit code {e.returncode}" + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mageck/app/mageck_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mageck/app/mageck_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9b9f7e5a22b01340d4e970668c5c632e850beee0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mageck/app/mageck_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mageck/app/mageck_server.py') +SERVER_NAME = 'biosci_mageck' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mageck/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mageck/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mageck/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mageck/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mageck/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..d39a5c9a98465156717134e3088326949a552872 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mageck/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-mageck: + build: . + image: mcp-mageck:latest + container_name: mcp-mageck + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=mageck + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mageck/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mageck/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..25dc251f7006cda5958506e42743c56b191db135 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mageck/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - mageck + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mageck/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mageck/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mageck/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mameshiba/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mameshiba/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..16bc9bd789d83360694a6fb3809a49c40ed3c0f5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mameshiba/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install mameshiba via conda (e.g., from bioconda) +RUN conda install -c bioconda mameshiba -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/mameshiba_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/mameshiba_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/mameshiba_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mameshiba/app/mameshiba_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mameshiba/app/mameshiba_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2cc18c3b0a6fdec2ddcaed9b0c7763ceafcd708d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mameshiba/app/mameshiba_server.py @@ -0,0 +1,151 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# MCP-standard mock decorator. +# In a real MCP environment, this would be provided by the mcp_sdk. +def tool(name=None, description=None, docker_image=None): + def decorator(func): + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + return wrapper + return decorator + +mcp = type('mcp', (), {'tool': tool}) + + +@mcp.tool() +def mameshiba( + config_yaml: Path, + processes: int = 4, +): + """ + Runs MameShiba, a lightweight version of Shiba, for splicing analysis. + + MameShiba is designed for users who want to perform only splicing analysis + using pre-existing alignment files (BAMs), thus skipping the initial + transcript assembly steps. It relies on a YAML configuration file to specify + input files and parameters. + + Args: + config_yaml: Path to the YAML configuration file. This file contains all + the necessary parameters and paths for the analysis. + processes: The number of processes (threads) to use for the analysis. + Defaults to 4. + + Returns: + A dictionary containing the execution details, including the command, + stdout, stderr, and a list of output files (if any can be determined). + """ + # Input validation + if not config_yaml.is_file(): + raise FileNotFoundError(f"Configuration file not found at: {config_yaml}") + + if processes <= 0: + raise ValueError("The number of processes must be a positive integer.") + + command = [ + "shiba.py", + "--mame", + "-p", + str(processes), + str(config_yaml), + ] + + command_executed = " ".join(command) + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + # Output files are defined within the config.yaml and cannot be + # determined from the command line arguments. Returning an empty list. + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'shiba.py' executable not found. Please ensure Shiba is installed and in your PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } + + +@mcp.tool() +def scshiba( + config_yaml: Path, + processes: int = 4, +): + """ + Runs scShiba to quantify and identify differential splicing events from single-cell RNA-seq data. + + scShiba is the single-cell RNA-seq version of the Shiba pipeline. It uses a + YAML configuration file to manage inputs, outputs, and analysis parameters. + + Args: + config_yaml: Path to the YAML configuration file for the single-cell analysis. + processes: The number of processes (threads) to use for the analysis. + Defaults to 4. + + Returns: + A dictionary containing the execution details, including the command, + stdout, stderr, and a list of output files (if any can be determined). + """ + # Input validation + if not config_yaml.is_file(): + raise FileNotFoundError(f"Configuration file not found at: {config_yaml}") + + if processes <= 0: + raise ValueError("The number of processes must be a positive integer.") + + command = [ + "scshiba.py", + "-p", + str(processes), + str(config_yaml), + ] + + command_executed = " ".join(command) + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + # Output files are defined within the config.yaml and cannot be + # determined from the command line arguments. Returning an empty list. + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'scshiba.py' executable not found. Please ensure Shiba is installed and in your PATH.", + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [] + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mameshiba/app/mameshiba_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mameshiba/app/mameshiba_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..96907039ac5a4ca74b33dec3df3e2fee9202fe1f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mameshiba/app/mameshiba_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mameshiba/app/mameshiba_server.py') +SERVER_NAME = 'biosci_mameshiba' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mameshiba/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mameshiba/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mameshiba/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mameshiba/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mameshiba/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..52ef877ce20954d3cb6f90784c28066d5cd395bb --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mameshiba/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-mameshiba: + build: . + image: mcp-mameshiba:latest + container_name: mcp-mameshiba + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=mameshiba + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mameshiba/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mameshiba/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..331eb6c82393e4534a0bc104d14ef7c1df25809e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mameshiba/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - mameshiba + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mameshiba/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mameshiba/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mameshiba/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mappy/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mappy/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8630abc23df676d0240d181bc5ea4b63d53009f7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mappy/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install mappy via conda (e.g., from bioconda) +RUN conda install -c bioconda mappy -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/mappy_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/mappy_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/mappy_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mappy/app/mappy_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mappy/app/mappy_server.py new file mode 100644 index 0000000000000000000000000000000000000000..a5218b7a5d7478b6dbdfa8f9211b00cc31f936ac --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mappy/app/mappy_server.py @@ -0,0 +1,334 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Literal, Dict, Any +import os + +# IMPORTANT NOTE: +# The provided documentation for "mappy" indicates it is a "Minimap2 Python binding" +# and explicitly states that `python -m mappy --help` fails with "No code object available for mappy". +# This means 'mappy' itself does not have a command-line interface that can be converted +# into an MCP tool using `subprocess.run`. +# +# However, the "URL Docs Extract" provided is entirely about the command-line usage of `minimap2`, +# which 'mappy' is a binding for. +# +# Therefore, this MCP tool definition assumes the intent was to create MCP tools for the +# `minimap2` command-line executable, based on the detailed usage examples and options +# described in the provided documentation. The functions are named `minimap2_...` accordingly. + +# Define common presets as an Enum or Literal for clarity and validation +Minimap2Preset = Literal[ + "map-pb", "map-ont", "map-iclr", "splice", "splice:hq", "splice:sr", + "ava-pb", "ava-ont", "sr", "asm5" +] + +# Define output formats +Minimap2OutputFormat = Literal["paf", "sam"] + +# Define strand options for splice +Minimap2Strand = Literal["f", "r", "n"] + +@mcp.tool() +def minimap2_index( + reference_file: Path, + output_index_file: Path, + kmer_size: Optional[int] = None, + window_size: Optional[int] = None, + homopolymer_compressed: bool = False, + batch_size: Optional[str] = None, # e.g., "4G" + threads: int = 3, +) -> Dict[str, Any]: + """ + Creates a minimap2 index (.mmi) from a reference FASTA/FASTQ file. + + This function wraps the `minimap2 -d` command to build a reference index. + Once built, this index can be used in subsequent alignment calls to speed up mapping. + + Args: + reference_file: Path to the input reference FASTA or FASTQ file. + (e.g., `ref.fa`) + output_index_file: Path to save the generated minimap2 index (.mmi) file. + (e.g., `ref.mmi`) + kmer_size: k-mer size. Default varies by preset (e.g., 15 for map-ont, 19 for map-pb). + If not specified, minimap2's internal default for indexing will be used. + Must be a positive integer if provided. + window_size: Minimizer window size. Default varies by preset (e.g., 10 for map-ont). + If not specified, minimap2's internal default for indexing will be used. + Must be a positive integer if provided. + homopolymer_compressed: If True, use homopolymer-compressed k-mers. Default is False. + Typically used for PacBio CLR reads (map-pb preset) to improve + performance and sensitivity. + batch_size: Batch size for indexing, e.g., "4G". This controls memory usage during indexing. + threads: Number of threads to use for indexing. Default is 3. Must be a positive integer. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + On success, `output_files` will contain the path to the generated `.mmi` file. + """ + # Input validation + if not reference_file.is_file(): + raise FileNotFoundError(f"Reference file not found: {reference_file}") + if output_index_file.suffix != ".mmi": + raise ValueError(f"Output index file must have .mmi extension: {output_index_file}") + output_index_file.parent.mkdir(parents=True, exist_ok=True) + + if kmer_size is not None and kmer_size <= 0: + raise ValueError("kmer_size must be a positive integer.") + if window_size is not None and window_size <= 0: + raise ValueError("window_size must be a positive integer.") + if threads <= 0: + raise ValueError("threads must be a positive integer.") + + command = ["minimap2", "-d", str(output_index_file)] + + if kmer_size is not None: + command.extend(["-k", str(kmer_size)]) + if window_size is not None: + command.extend(["-w", str(window_size)]) + if homopolymer_compressed: + command.append("-H") + if batch_size is not None: + command.extend(["-I", batch_size]) + + command.extend(["-t", str(threads)]) + + command.append(str(reference_file)) + + try: + process = subprocess.run(command, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(command), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": [str(output_index_file)], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "output_files": [], + } + +@mcp.tool() +def minimap2_align( + reference_input: Path, + query_files: List[Path], + output_file: Path, + output_format: Minimap2OutputFormat = "paf", + preset: Optional[Minimap2Preset] = None, + output_cigar_paf: bool = False, + num_secondary_alignments: int = 5, + secondary_ratio: float = 0.8, + long_cigar_tag: bool = False, + cs_tag: Optional[Literal[True, "long"]] = None, # True for --cs, "long" for --cs=long + force_strand: Optional[Minimap2Strand] = None, + splice_flank_no: bool = False, + junction_bed_file: Optional[Path] = None, + junction_bonus: int = 9, + max_intron_length: int = 200000, + write_junctions_file: Optional[Path] = None, + pass1_junctions_file: Optional[Path] = None, + threads: int = 3, +) -> Dict[str, Any]: + """ + Performs sequence alignment using minimap2. + + This function wraps the `minimap2` command for various alignment tasks. + It aligns query sequences (FASTA/FASTQ) against a reference genome (FASTA/FASTQ) + or a pre-built minimap2 index (.mmi). + + Args: + reference_input: Path to the reference FASTA/FASTQ file or a pre-built .mmi index. + (e.g., `ref.fa` or `ref.mmi`) + query_files: A list of paths to one or more query FASTA/FASTQ files. + For paired-end reads, provide two files (e.g., `[read1.fq, read2.fq]`). + Minimap2 will internally interleave them if they are adjacent and have same names. + output_file: Path to save the alignment output. The format is determined by `output_format`. + (e.g., `alignment.paf` or `alignment.sam`) + output_format: The desired output format: "paf" (default) or "sam". + preset: Pre-defined option set for specific data types. + Examples: "map-ont" (Oxford Nanopore genomic reads, default if no preset is given), + "splice" (spliced long reads), "sr" (short genomic reads), + "asm5" (assembly-to-assembly alignment). + If not specified, minimap2's default behavior is equivalent to "map-ont". + output_cigar_paf: If True, output CIGAR string in the 'cg' tag for PAF format. + Only applicable if `output_format` is "paf". Default is False. + num_secondary_alignments: Output up to this many secondary alignments. Default is 5. + Set to 0 to disable secondary alignments. Must be non-negative. + secondary_ratio: Minimum secondary-to-primary score ratio to retain secondary alignments. + Only secondary alignments with a score higher than this ratio of their + corresponding primary alignment's score will be kept. Default is 0.8. + Must be between 0.0 and 1.0. + long_cigar_tag: If True, move long CIGAR strings (those with >65535 operations) to the 'CG' tag + and leave a fully clipped CIGAR at the SAM CIGAR column. + Recommended for ultra-long reads if the output SAM/CRAM will be converted to BAM. + Default is False. + cs_tag: If True, output the 'cs' tag encoding bases at mismatches and INDELs. + If "long", output the long form of the 'cs' tag, which includes identical sequences. + Default is None (no cs tag). + force_strand: For spliced alignment, force minimap2 to consider only 'f' (forward), + 'r' (reverse), or 'n' (unknown, default) transcript strand. + Only applicable with 'splice', 'splice:hq', or 'splice:sr' presets. + splice_flank_no: If True, for spliced alignment, minimap2 will only model GT..AG splicing signals, + ignoring the additional base. Recommended for SIRV control data. + Only applicable with 'splice' presets. Default is False. + junction_bed_file: Path to a BED12 or 5-column BED file with annotated splice junctions. + Minimap2 will add a bonus score if an aligned junction matches an annotation. + Only applicable with 'splice' presets. + junction_bonus: Bonus score added if an aligned junction matches an annotated junction. Default is 9. + Only applicable with 'splice' presets when `junction_bed_file` is provided. + Must be a positive integer. + max_intron_length: Maximum intron length allowed. Default is 200000 (200kb). + Only applicable with 'splice' presets. Must be a positive integer. + write_junctions_file: Path to a BED file to write detected junctions. + Used for 2-pass RNA-seq alignment (first pass). + Only applicable with 'splice:sr' preset. + pass1_junctions_file: Path to a BED file containing junctions from a first pass. + Used for 2-pass RNA-seq alignment (second pass). + Only applicable with 'splice:sr' preset. + threads: Number of threads to use for alignment. Default is 3. Must be a positive integer. + + Returns: + A dictionary containing the command executed, stdout (empty as output is redirected), + stderr, and a list of output files. + On success, `output_files` will contain the path to the main alignment file + and optionally the `write_junctions_file`. + """ + # Input validation + if not reference_input.is_file(): + raise FileNotFoundError(f"Reference input file/index not found: {reference_input}") + if not query_files: + raise ValueError("At least one query file must be provided.") + for q_file in query_files: + if not q_file.is_file(): + raise FileNotFoundError(f"Query file not found: {q_file}") + + output_file.parent.mkdir(parents=True, exist_ok=True) + + if output_format == "paf" and output_file.suffix not in [".paf", ".txt", ""]: + # PAF files typically don't have a specific suffix, but .paf is common. + # An empty suffix is also possible if the user just provides a name. + pass + elif output_format == "sam" and output_file.suffix not in [".sam", ".bam", ""]: + # If SAM output, typically .sam or .bam (if converted later). + # This tool outputs SAM text, so .sam is appropriate. + pass + + if output_format == "sam" and output_cigar_paf: + raise ValueError("output_cigar_paf is only applicable when output_format is 'paf'.") + + if not (0 <= num_secondary_alignments): + raise ValueError("num_secondary_alignments must be a non-negative integer.") + if not (0.0 <= secondary_ratio <= 1.0): + raise ValueError("secondary_ratio must be between 0.0 and 1.0.") + if threads <= 0: + raise ValueError("threads must be a positive integer.") + + is_splice_preset = preset in ["splice", "splice:hq", "splice:sr"] + if force_strand is not None and not is_splice_preset: + raise ValueError("force_strand is only applicable with 'splice' presets.") + if splice_flank_no and not is_splice_preset: + raise ValueError("splice_flank_no is only applicable with 'splice' presets.") + if junction_bed_file is not None and not is_splice_preset: + raise ValueError("junction_bed_file is only applicable with 'splice' presets.") + if junction_bonus <= 0: + raise ValueError("junction_bonus must be a positive integer.") + if max_intron_length <= 0: + raise ValueError("max_intron_length must be a positive integer.") + + if write_junctions_file is not None and preset != "splice:sr": + raise ValueError("write_junctions_file is only applicable with 'splice:sr' preset.") + if pass1_junctions_file is not None and preset != "splice:sr": + raise ValueError("pass1_junctions_file is only applicable with 'splice:sr' preset.") + + if write_junctions_file: + write_junctions_file.parent.mkdir(parents=True, exist_ok=True) + if write_junctions_file.suffix != ".bed": + raise ValueError(f"write_junctions_file must have .bed extension: {write_junctions_file}") + if pass1_junctions_file and not pass1_junctions_file.is_file(): + raise FileNotFoundError(f"Pass1 junctions file not found: {pass1_junctions_file}") + if pass1_junctions_file and pass1_junctions_file.suffix != ".bed": + raise ValueError(f"pass1_junctions_file must have .bed extension: {pass1_junctions_file}") + if junction_bed_file and not junction_bed_file.is_file(): + raise FileNotFoundError(f"Junction BED file not found: {junction_bed_file}") + if junction_bed_file and junction_bed_file.suffix != ".bed": + raise ValueError(f"junction_bed_file must have .bed extension: {junction_bed_file}") + + + command = ["minimap2"] + + if preset: + command.extend(["-x", preset]) + + if output_format == "sam": + command.append("-a") + elif output_format == "paf" and output_cigar_paf: + command.append("-c") + + if num_secondary_alignments != 5: # Default is 5 + command.extend(["-N", str(num_secondary_alignments)]) + if secondary_ratio != 0.8: # Default is 0.8 + command.extend(["-p", str(secondary_ratio)]) + if long_cigar_tag: + command.append("-L") + if cs_tag: + if cs_tag == "long": + command.append("--cs=long") + else: # cs_tag is True + command.append("--cs") + + if is_splice_preset: + if force_strand: + command.extend(["-u", force_strand]) + if splice_flank_no: + command.append("--splice-flank=no") + if junction_bed_file: + command.extend(["--junc-bed", str(junction_bed_file)]) + if junction_bonus != 9: # Default is 9 + command.extend(["--junc-bonus", str(junction_bonus)]) + if max_intron_length != 200000: # Default is 200k + command.extend(["-G", str(max_intron_length)]) + if preset == "splice:sr": + if write_junctions_file: + command.extend(["--write-junc", str(write_junctions_file)]) + if pass1_junctions_file: + command.extend(["--pass1", str(pass1_junctions_file)]) + + command.extend(["-t", str(threads)]) + + command.append(str(reference_input)) + command.extend([str(q) for q in query_files]) + + # Execute minimap2 and redirect stdout to output_file + try: + with open(output_file, "w") as outfile: + process = subprocess.run(command, stdout=outfile, stderr=subprocess.PIPE, text=True, check=True) + + output_files = [str(output_file)] + if write_junctions_file: + output_files.append(str(write_junctions_file)) + + return { + "command_executed": " ".join(command) + f" > {output_file}", + "stdout": "", # stdout is redirected to file + "stderr": process.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + # If an error occurs, the output_file might be partially written or empty. + # We should still report it if it exists and has content, but indicate an error. + output_files_on_error = [] + if output_file.exists() and output_file.stat().st_size > 0: + output_files_on_error.append(str(output_file)) + if write_junctions_file and write_junctions_file.exists() and write_junctions_file.stat().st_size > 0: + output_files_on_error.append(str(write_junctions_file)) + + return { + "command_executed": " ".join(command) + f" > {output_file}", + "stdout": e.stdout, # In case of error, stdout might contain partial output + "stderr": e.stderr, + "error": str(e), + "output_files": output_files_on_error, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mappy/app/mappy_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mappy/app/mappy_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2d008f920583220d7471e15dc93e551a7636b6d2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mappy/app/mappy_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mappy/app/mappy_server.py') +SERVER_NAME = 'biosci_mappy' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mappy/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mappy/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mappy/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mappy/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mappy/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..2838122e383361154fc122d87668eb26622fcf41 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mappy/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-mappy: + build: . + image: mcp-mappy:latest + container_name: mcp-mappy + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=mappy + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mappy/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mappy/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..2397f57a9e3157b3bf14b412a873ded857f6c39e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mappy/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - mappy + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mappy/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mappy/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mappy/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_markerrepo/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_markerrepo/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e4521ee58f2375efde7c4c17f946c47c932d40fc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_markerrepo/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install markerrepo via conda (e.g., from bioconda) +RUN conda install -c bioconda markerrepo -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/markerrepo_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/markerrepo_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/markerrepo_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_markerrepo/app/markerrepo_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_markerrepo/app/markerrepo_server.py new file mode 100644 index 0000000000000000000000000000000000000000..04bc5373598a329211a4c49739bde5aeb4f881d7 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_markerrepo/app/markerrepo_server.py @@ -0,0 +1,221 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import Optional, List + +# MCP decorator is assumed to be defined elsewhere +# For local testing, you can use a dummy decorator: +# def mcp_tool_dummy(*args, **kwargs): +# def decorator(func): +# return func +# return decorator +# mcp = type("MCP", (), {"tool": mcp_tool_dummy}) + + +@mcp.tool() +def markerrepo_clone(url: str, path: Path): + """ + Clones a marker repository from a given git URL to a specified local path. + + Args: + url: URL of the git repository to clone. + path: Path to clone the repository to. This directory will be created. + """ + # Input validation + if path.exists(): + raise ValueError(f"Output path '{path}' already exists. Please specify a non-existent directory.") + path.parent.mkdir(parents=True, exist_ok=True) + + command = [ + "markerrepo", + "clone", + url, + str(path), + ] + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + # The output is the directory itself. We can list its contents or just return the path. + output_files = [str(p) for p in path.rglob('*') if p.is_file()] + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": { + "cloned_repo_dir": str(path) + } + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "error": "MarkerRepo clone failed", + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + } + + +@mcp.tool() +def markerrepo_update(path: Path): + """ + Updates a local marker repository by pulling the latest changes from the remote. + + Args: + path: Path to the existing local marker repository. + """ + # Input validation + if not path.is_dir(): + raise FileNotFoundError(f"The specified repository path '{path}' does not exist or is not a directory.") + if not (path / ".git").is_dir(): + raise ValueError(f"The path '{path}' does not appear to be a git repository.") + + command = [ + "markerrepo", + "update", + str(path), + ] + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "error": "MarkerRepo update failed", + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + } + + +@mcp.tool() +def markerrepo_list( + repo_path: Path, + species: Optional[str] = None, + tissue: Optional[str] = None, +): + """ + Lists available markers in a local repository, with optional filtering. + + Args: + repo_path: Path to the local marker repository. + species: Optional species to filter by (e.g., 'human', 'mouse'). + tissue: Optional tissue to filter by. + """ + # Input validation + if not repo_path.is_dir(): + raise FileNotFoundError(f"The specified repository path '{repo_path}' does not exist or is not a directory.") + + command = [ + "markerrepo", + "list", + str(repo_path), + ] + if species: + command.extend(["--species", species]) + if tissue: + command.extend(["--tissue", tissue]) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "error": "MarkerRepo list failed", + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + } + + +@mcp.tool() +def markerrepo_annotate( + repo_path: Path, + adata_path: Path, + output_path: Path, + groupby: str = "leiden", + species: str = "human", + tissue: Optional[str] = None, + key_added: str = "cell_type", +): + """ + Annotates a scanpy AnnData object (.h5ad) using markers from a repository. + + Args: + repo_path: Path to the local marker repository. + adata_path: Path to the input AnnData object (.h5ad). + output_path: Path to save the annotated AnnData object. + groupby: Column in adata.obs to group by for annotation. + species: Species to use for annotation (e.g., 'human', 'mouse'). + tissue: Optional tissue to use for annotation. + key_added: Key to add the annotation to in adata.obs. + """ + # Input validation + if not repo_path.is_dir(): + raise FileNotFoundError(f"The specified repository path '{repo_path}' does not exist or is not a directory.") + if not adata_path.is_file(): + raise FileNotFoundError(f"The input AnnData file '{adata_path}' does not exist.") + if output_path.exists(): + raise ValueError(f"Output path '{output_path}' already exists. Please specify a new file path.") + output_path.parent.mkdir(parents=True, exist_ok=True) + + command = [ + "markerrepo", + "annotate", + str(repo_path), + str(adata_path), + str(output_path), + "--groupby", groupby, + "--species", species, + "--key_added", key_added, + ] + if tissue: + command.extend(["--tissue", tissue]) + + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + ) + return { + "command_executed": " ".join(command), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": { + "annotated_adata": str(output_path) + } + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "error": "MarkerRepo annotate failed", + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode, + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_markerrepo/app/markerrepo_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_markerrepo/app/markerrepo_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9cc048278fde9f0116192305313ac5b322a3ebce --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_markerrepo/app/markerrepo_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_markerrepo/app/markerrepo_server.py') +SERVER_NAME = 'biosci_markerrepo' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_markerrepo/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_markerrepo/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_markerrepo/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_markerrepo/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_markerrepo/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..2a8efecd77a6ba457e223fb0c2d251f3bbdf4485 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_markerrepo/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-markerrepo: + build: . + image: mcp-markerrepo:latest + container_name: mcp-markerrepo + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=markerrepo + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_markerrepo/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_markerrepo/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..a590b4269fe0d9edb40a00ea6baaab6f2f0c3aa8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_markerrepo/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - markerrepo + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_markerrepo/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_markerrepo/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_markerrepo/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mash/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mash/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..9ea3dcd4e7f0095f435acdd947c521c320e017f9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mash/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install mash via conda (e.g., from bioconda) +RUN conda install -c bioconda mash -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/mash_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/mash_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/mash_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mash/app/mash_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mash/app/mash_server.py new file mode 100644 index 0000000000000000000000000000000000000000..527ed42e3cf594fb74ee2baecaf03aa2706e66dc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mash/app/mash_server.py @@ -0,0 +1,655 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# MCP decorator is not imported as per instructions. +# It is assumed to be available in the execution environment. + +# @mcp.tool() +def mash_sketch( + files: List[Path], + output_file: Optional[Path] = None, + kmer_size: int = 21, + sketch_size: int = 1000, + threads: int = 1, + file_list: Optional[Path] = None, + individual_sequences: bool = False, + reads: bool = False, + min_copies: int = 1, + min_coverage: int = 1, + genome_size: Optional[int] = None, + warning_threshold: float = 0.01, + buffer_size: Optional[str] = None, + verbose: bool = False, + seed: int = 42, + non_canonical: bool = False, + amino_acid: bool = False, + amino_acid_01: bool = False, + comment: Optional[str] = None, + concatenated: bool = False, +) -> dict: + """ + Create sketches (reduced representations for fast operations) from sequence files. + + Args: + files: One or more FASTA/FASTQ file(s) to sketch. + output_file: Output file for the sketch. If not provided, sketches are written to stdout. + kmer_size: k-mer size (must be <= 32). + sketch_size: Number of hashes per sketch. + threads: Number of parallel threads to use. + file_list: A file containing a list of input files, one per line. + individual_sequences: Sketch individual sequences (e.g., contigs) instead of whole files. + reads: Input files are sequence reads. This is required for coverage filtering. + min_copies: Minimum copies of each k-mer to include (k-mer filtering). + min_coverage: Minimum coverage for k-mers from reads to be considered (requires 'reads' to be True). + genome_size: Target genome size for p-value calculation. If not set, it's estimated. + warning_threshold: Probability of a random match for p-value calculation. + buffer_size: Input buffer size. Suffixes K, M, G are allowed (e.g., '100M'). + verbose: Print verbose messages to stderr. + seed: Seed for the hash function. + non_canonical: Use non-canonical k-mers. + amino_acid: Use amino acid alphabet (k <= 16). + amino_acid_01: Use amino acid alphabet with 0-1 encoding (k <= 16). + comment: Set a comment for the sketch. + concatenated: Create a sketch from a single, concatenated sequence. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # Input validation + if not files and not file_list: + raise ValueError("Either 'files' or 'file_list' must be provided.") + if files and file_list: + raise ValueError("'files' and 'file_list' are mutually exclusive.") + if kmer_size > 32 or kmer_size < 1: + raise ValueError("'kmer_size' must be between 1 and 32.") + if sketch_size <= 0: + raise ValueError("'sketch_size' must be a positive integer.") + if threads <= 0: + raise ValueError("'threads' must be a positive integer.") + if min_copies <= 0: + raise ValueError("'min_copies' must be a positive integer.") + if min_coverage > 1 and not reads: + raise ValueError("'min_coverage' > 1 requires 'reads' to be True.") + if amino_acid and amino_acid_01: + raise ValueError("'amino_acid' and 'amino_acid_01' are mutually exclusive.") + if (amino_acid or amino_acid_01) and kmer_size > 16: + raise ValueError("For amino acid sketches, 'kmer_size' must be <= 16.") + + cmd = ["mash", "sketch"] + + cmd.extend(["-k", str(kmer_size)]) + cmd.extend(["-s", str(sketch_size)]) + cmd.extend(["-p", str(threads)]) + cmd.extend(["-S", str(seed)]) + + if output_file: + cmd.extend(["-o", str(output_file)]) + if file_list: + cmd.extend(["-l", str(file_list)]) + if individual_sequences: + cmd.append("-i") + if reads: + cmd.append("-r") + if min_copies > 1: + cmd.extend(["-m", str(min_copies)]) + if min_coverage > 1: + cmd.extend(["-c", str(min_coverage)]) + if genome_size is not None: + cmd.extend(["-g", str(genome_size)]) + if warning_threshold != 0.01: + cmd.extend(["-w", str(warning_threshold)]) + if buffer_size: + cmd.extend(["-b", buffer_size]) + if verbose: + cmd.append("-v") + if non_canonical: + cmd.append("-n") + if amino_acid: + cmd.append("-a") + if amino_acid_01: + cmd.append("-A") + if comment: + cmd.extend(["-I", comment]) + if concatenated: + cmd.append("-C") + + if files: + for file_path in files: + if not file_path.exists(): + raise FileNotFoundError(f"Input file not found: {file_path}") + cmd.append(str(file_path)) + + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True + ) + output_files = [str(output_file)] if output_file else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Mash sketch failed", + "return_code": e.returncode, + } + +# @mcp.tool() +def mash_dist( + reference_sketch: Path, + query_files: List[Path], + query_list: Optional[Path] = None, + threads: int = 1, + tabular: bool = False, + max_distance: float = 1.0, + max_p_value: float = 1.0, + sketch_size: Optional[int] = None, + kmer_size: Optional[int] = None, + seed: int = 42, + top_pair_only: bool = False, + amino_acid: bool = False, + amino_acid_01: bool = False, + individual_sequences: bool = False, + write_comments: Optional[Path] = None, + read_comments: Optional[Path] = None, +) -> dict: + """ + Estimate the distance of query sequences to references. + + Args: + reference_sketch: The reference sketch file (.msh). + query_files: One or more query files (FASTA/FASTQ or .msh). + query_list: A file containing a list of query files, one per line. + threads: Number of parallel threads to use. + tabular: Output in a tab-separated format. + max_distance: Maximum distance to report. + max_p_value: Maximum p-value to report. + sketch_size: Override sketch size from the sketch file. + kmer_size: Override k-mer size from the sketch file. + seed: Seed for the hash function. + top_pair_only: For pairwise distances, only write the top pair by distance. + amino_acid: Use amino acid alphabet (k <= 16). + amino_acid_01: Use amino acid alphabet with 0-1 encoding (k <= 16). + individual_sequences: Sketch individual sequences if query files are not sketches. + write_comments: Write comments to the specified file. + read_comments: Read comments from the specified file. + + Returns: + A dictionary containing the executed command, stdout, and stderr. + """ + # Input validation + if not reference_sketch.exists(): + raise FileNotFoundError(f"Reference sketch not found: {reference_sketch}") + if not query_files and not query_list: + raise ValueError("Either 'query_files' or 'query_list' must be provided.") + if query_files and query_list: + raise ValueError("'query_files' and 'query_list' are mutually exclusive.") + if threads <= 0: + raise ValueError("'threads' must be a positive integer.") + if amino_acid and amino_acid_01: + raise ValueError("'amino_acid' and 'amino_acid_01' are mutually exclusive.") + + cmd = ["mash", "dist"] + cmd.extend(["-p", str(threads)]) + cmd.extend(["-S", str(seed)]) + + if tabular: + cmd.append("-t") + if max_distance < 1.0: + cmd.extend(["-d", str(max_distance)]) + if max_p_value < 1.0: + cmd.extend(["-v", str(max_p_value)]) + if sketch_size is not None: + if sketch_size <= 0: + raise ValueError("'sketch_size' must be a positive integer.") + cmd.extend(["-s", str(sketch_size)]) + if kmer_size is not None: + if kmer_size <= 0 or kmer_size > 32: + raise ValueError("'kmer_size' must be between 1 and 32.") + cmd.extend(["-k", str(kmer_size)]) + if top_pair_only: + cmd.append("-w") + if amino_acid: + cmd.append("-a") + if amino_acid_01: + cmd.append("-A") + if individual_sequences: + cmd.append("-i") + if write_comments: + cmd.extend(["-c", str(write_comments)]) + if read_comments: + cmd.extend(["-C", str(read_comments)]) + if query_list: + cmd.extend(["-l", str(query_list)]) + + cmd.append(str(reference_sketch)) + + if query_files: + for file_path in query_files: + if not file_path.exists(): + raise FileNotFoundError(f"Query file not found: {file_path}") + cmd.append(str(file_path)) + + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True + ) + output_files = [str(write_comments)] if write_comments else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Mash dist failed", + "return_code": e.returncode, + } + +# @mcp.tool() +def mash_screen( + reference_sketch: Path, + query_files: List[Path], + threads: int = 1, + p_value_threshold: float = 0.01, + winner_takes_all: bool = False, + identity_threshold: float = 0.95, + bloom_filter_size: Optional[str] = None, + no_bloom_filter: bool = False, + amino_acid: bool = False, + amino_acid_01: bool = False, + seed: int = 42, +) -> dict: + """ + Determine whether query sequences are within a larger mixture of sequences. + + Args: + reference_sketch: The reference sketch file (.msh). + query_files: One or more query FASTA/FASTQ files. + threads: Number of parallel threads to use. + p_value_threshold: p-value threshold for winning. + winner_takes_all: Only report the best match for each query. + identity_threshold: Identity threshold for winning (0 to 1). + bloom_filter_size: Bloom filter size. Suffixes K, M, G are allowed. + no_bloom_filter: Do not use a Bloom filter (slower). + amino_acid: Use amino acid alphabet (k <= 16). + amino_acid_01: Use amino acid alphabet with 0-1 encoding (k <= 16). + seed: Seed for the hash function. + + Returns: + A dictionary containing the executed command, stdout, and stderr. + """ + # Input validation + if not reference_sketch.exists(): + raise FileNotFoundError(f"Reference sketch not found: {reference_sketch}") + if not query_files: + raise ValueError("'query_files' must be provided and not empty.") + if threads <= 0: + raise ValueError("'threads' must be a positive integer.") + if not (0.0 <= identity_threshold <= 1.0): + raise ValueError("'identity_threshold' must be between 0 and 1.") + if bloom_filter_size and no_bloom_filter: + raise ValueError("'bloom_filter_size' and 'no_bloom_filter' are mutually exclusive.") + if amino_acid and amino_acid_01: + raise ValueError("'amino_acid' and 'amino_acid_01' are mutually exclusive.") + + cmd = ["mash", "screen"] + cmd.extend(["-p", str(threads)]) + cmd.extend(["-S", str(seed)]) + + if p_value_threshold != 0.01: + cmd.extend(["-v", str(p_value_threshold)]) + if winner_takes_all: + cmd.append("-w") + if identity_threshold != 0.95: + cmd.extend(["-i", str(identity_threshold)]) + if bloom_filter_size: + cmd.extend(["-b", bloom_filter_size]) + if no_bloom_filter: + cmd.append("-n") + if amino_acid: + cmd.append("-a") + if amino_acid_01: + cmd.append("-A") + + cmd.append(str(reference_sketch)) + + for file_path in query_files: + if not file_path.exists(): + raise FileNotFoundError(f"Query file not found: {file_path}") + cmd.append(str(file_path)) + + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Mash screen failed", + "return_code": e.returncode, + } + +# @mcp.tool() +def mash_triangle( + sketches: Path, + output_file: Optional[Path] = None, + threads: int = 1, + list_names_only: bool = False, + omit_query_vs_query: bool = False, + max_distance: float = 1.0, + max_p_value: float = 1.0, + write_comments: Optional[Path] = None, + read_comments: Optional[Path] = None, +) -> dict: + """ + Estimate a lower-triangular distance matrix from a single sketch file. + + Args: + sketches: A single sketch file (.msh) containing multiple sketches. + output_file: Output file for the distance matrix. Defaults to stdout. + threads: Number of parallel threads to use. + list_names_only: List sequence names only. + omit_query_vs_query: Omit query-vs-query distances. + max_distance: Maximum distance to report. + max_p_value: Maximum p-value to report. + write_comments: Write comments to the specified file. + read_comments: Read comments from the specified file. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # Input validation + if not sketches.exists(): + raise FileNotFoundError(f"Sketch file not found: {sketches}") + if threads <= 0: + raise ValueError("'threads' must be a positive integer.") + + cmd = ["mash", "triangle"] + cmd.extend(["-p", str(threads)]) + + if output_file: + cmd.extend(["-o", str(output_file)]) + if list_names_only: + cmd.append("-l") + if omit_query_vs_query: + cmd.append("-E") + if max_distance < 1.0: + cmd.extend(["-d", str(max_distance)]) + if max_p_value < 1.0: + cmd.extend(["-v", str(max_p_value)]) + if write_comments: + cmd.extend(["-c", str(write_comments)]) + if read_comments: + cmd.extend(["-C", str(read_comments)]) + + cmd.append(str(sketches)) + + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True + ) + output_files = [] + if output_file: + output_files.append(str(output_file)) + if write_comments: + output_files.append(str(write_comments)) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Mash triangle failed", + "return_code": e.returncode, + } + +# @mcp.tool() +def mash_paste( + output_name: str, + sketch_files: List[Path], + sketch_list_file: Optional[Path] = None, +) -> dict: + """ + Create a single sketch file from multiple sketch files. + + Args: + output_name: The name/prefix for the output sketch file. '.msh' will be appended. + sketch_files: One or more sketch files to combine. + sketch_list_file: A file containing a list of sketch files, one per line. + + Returns: + A dictionary containing the executed command, stdout, stderr, and the path to the output sketch file. + """ + # Input validation + if not sketch_files and not sketch_list_file: + raise ValueError("Either 'sketch_files' or 'sketch_list_file' must be provided.") + if sketch_files and sketch_list_file: + raise ValueError("'sketch_files' and 'sketch_list_file' are mutually exclusive.") + + cmd = ["mash", "paste", output_name] + + if sketch_list_file: + if not sketch_list_file.exists(): + raise FileNotFoundError(f"Sketch list file not found: {sketch_list_file}") + cmd.extend(["-l", str(sketch_list_file)]) + + if sketch_files: + for file_path in sketch_files: + if not file_path.exists(): + raise FileNotFoundError(f"Sketch file not found: {file_path}") + cmd.append(str(file_path)) + + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True + ) + output_file = f"{output_name}.msh" + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Mash paste failed", + "return_code": e.returncode, + } + +# @mcp.tool() +def mash_info( + sketch_files: List[Path], + tabular: bool = False, + show_comments: bool = False, + show_data: bool = False, +) -> dict: + """ + Display information about sketch files. + + Args: + sketch_files: One or more sketch files to inspect. + tabular: Output in a tab-separated format. + show_comments: Show comments within the sketch files. + show_data: Show sketch data (hashes). + + Returns: + A dictionary containing the executed command, stdout, and stderr. + """ + # Input validation + if not sketch_files: + raise ValueError("'sketch_files' must be provided and not empty.") + + cmd = ["mash", "info"] + + if tabular: + cmd.append("-t") + if show_comments: + cmd.append("-c") + if show_data: + cmd.append("-d") + + for file_path in sketch_files: + if not file_path.exists(): + raise FileNotFoundError(f"Sketch file not found: {file_path}") + cmd.append(str(file_path)) + + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Mash info failed", + "return_code": e.returncode, + } + +# @mcp.tool() +def mash_bounds() -> dict: + """ + Print a table of Mash error bounds. This command takes no arguments. + + Returns: + A dictionary containing the executed command, stdout, and stderr. + """ + cmd = ["mash", "bounds"] + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True + ) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Mash bounds failed", + "return_code": e.returncode, + } + +# @mcp.tool() +def mash_taxscreen( + taxonomy_map: Path, + screen_output: Path, + output_file: Optional[Path] = None, + threads: int = 1, + taxonomy_tree: Optional[Path] = None, + taxonomy_names: Optional[Path] = None, + min_identity: float = 0.95, + min_hashes: int = 10, + rank: str = "species", + report_unclassified: bool = False, + report_zeroes: bool = False, +) -> dict: + """ + Create a Kraken-style taxonomic report based on mash screen output. + + Args: + taxonomy_map: A file mapping sequence IDs to tax IDs. + screen_output: The output file from 'mash screen'. + output_file: Output file for the report. Defaults to stdout. + threads: Number of parallel threads to use. + taxonomy_tree: Taxonomy tree file (e.g., nodes.dmp). + taxonomy_names: Taxonomy names file (e.g., names.dmp). + min_identity: Minimum identity to consider a hit. + min_hashes: Minimum number of hashes to consider a hit. + rank: Rank to report (e.g., species, genus). + report_unclassified: Report unclassified reads. + report_zeroes: Report taxa with zero hits. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output files. + """ + # Input validation + if not taxonomy_map.exists(): + raise FileNotFoundError(f"Taxonomy map file not found: {taxonomy_map}") + if not screen_output.exists(): + raise FileNotFoundError(f"Mash screen output file not found: {screen_output}") + if threads <= 0: + raise ValueError("'threads' must be a positive integer.") + if not (0.0 <= min_identity <= 1.0): + raise ValueError("'min_identity' must be between 0 and 1.") + if min_hashes <= 0: + raise ValueError("'min_hashes' must be a positive integer.") + + cmd = ["mash", "taxscreen"] + + if output_file: + cmd.extend(["-o", str(output_file)]) + if threads > 1: + cmd.extend(["-p", str(threads)]) + if taxonomy_tree: + cmd.extend(["-t", str(taxonomy_tree)]) + if taxonomy_names: + cmd.extend(["-n", str(taxonomy_names)]) + if min_identity != 0.95: + cmd.extend(["-m", str(min_identity)]) + if min_hashes != 10: + cmd.extend(["-l", str(min_hashes)]) + if rank != "species": + cmd.extend(["-r", rank]) + if report_unclassified: + cmd.append("--report-unclassified") + if report_zeroes: + cmd.append("--report-zeroes") + + cmd.append(str(taxonomy_map)) + cmd.append(str(screen_output)) + + try: + result = subprocess.run( + cmd, check=True, capture_output=True, text=True + ) + output_files = [str(output_file)] if output_file else [] + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Mash taxscreen failed", + "return_code": e.returncode, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mash/app/mash_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mash/app/mash_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..64de5517f93a5f91cf492d2f3581a896cbc25e17 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mash/app/mash_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mash/app/mash_server.py') +SERVER_NAME = 'biosci_mash' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mash/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mash/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mash/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mash/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mash/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..59aa6986d816e37f0633fc7e61f2b5d48e83ad7f --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mash/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-mash: + build: . + image: mcp-mash:latest + container_name: mcp-mash + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=mash + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mash/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mash/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..bad3fd0f70c2665f4210fece911e36ba15aa78c2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mash/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - mash + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mash/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mash/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mash/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_maxquant/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_maxquant/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e72b341c8c466abc09772fd3bfc0de085516d393 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_maxquant/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install maxquant via conda (e.g., from bioconda) +RUN conda install -c bioconda maxquant -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/maxquant_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/maxquant_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/maxquant_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_maxquant/app/maxquant_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_maxquant/app/maxquant_server.py new file mode 100644 index 0000000000000000000000000000000000000000..931952348db226d4f0ac212edaa18a8e6f558a56 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_maxquant/app/maxquant_server.py @@ -0,0 +1,242 @@ +import subprocess +import sys +import os +import shutil +import xml.etree.ElementTree as ET +from pathlib import Path +from typing import List, Optional + +# MCP decorator is commented out as per instructions, +# but would be present in a real MCP environment. +# from mcp import mcp + +@mcp.tool() +def maxquant_run( + mqpar_xml_file: Path, + maxquant_cmd_path: Path, + num_threads: Optional[int] = None, +) -> dict: + """ + Runs the MaxQuant analysis pipeline using a specified mqpar.xml configuration file. + + This tool executes the main MaxQuant quantification and identification workflow. + It intelligently locates the output 'combined/txt' directory by parsing the + mqpar.xml file to provide accurate output file paths. + + Args: + mqpar_xml_file: Path to the configured MaxQuant parameter file (mqpar.xml). + maxquant_cmd_path: Path to the MaxQuant command-line executable (MaxQuantCmd.exe). + num_threads: Optional number of threads for processing. If not set, MaxQuant + will use the maximum available. + + Returns: + A dictionary containing the execution details, including the command, + stdout, stderr, and a list of discovered output files. + """ + # 1. Input Validation + if not maxquant_cmd_path.is_file(): + raise FileNotFoundError(f"MaxQuant executable not found at: {maxquant_cmd_path}") + if not mqpar_xml_file.is_file(): + raise FileNotFoundError(f"MaxQuant parameter file not found at: {mqpar_xml_file}") + if num_threads is not None and num_threads <= 0: + raise ValueError("num_threads must be a positive integer.") + + # 2. Command Construction + base_command = ["mono"] if sys.platform != "win32" else [] + command = base_command + [str(maxquant_cmd_path), str(mqpar_xml_file)] + if num_threads is not None: + command.append(str(num_threads)) + command_str = " ".join(command) + + # 3. Subprocess Execution + working_dir = mqpar_xml_file.parent + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True, + cwd=working_dir + ) + stdout = result.stdout + stderr = result.stderr + + # 4. Output File Discovery (parsing mqpar.xml for accuracy) + output_files = [] + output_dir = None + try: + tree = ET.parse(mqpar_xml_file) + root = tree.getroot() + fixed_folder_node = root.find('.//fixedCombinedFolder') + + if fixed_folder_node is not None and fixed_folder_node.text: + output_dir = Path(fixed_folder_node.text) + else: + first_raw_file_node = root.find('.//filePaths/string[1]') + if first_raw_file_node is not None and first_raw_file_node.text: + first_raw_file_path = Path(first_raw_file_node.text) + if not first_raw_file_path.is_absolute(): + first_raw_file_path = mqpar_xml_file.parent / first_raw_file_path + output_dir = first_raw_file_path.parent + except ET.ParseError: + stderr += "\n[MCP Tool Warning] Could not parse mqpar.xml to determine exact output folder. Searching relative to the parameter file." + output_dir = working_dir + + if output_dir: + combined_dir = output_dir / "combined" + if combined_dir.is_dir(): + txt_dir = combined_dir / "txt" + if txt_dir.is_dir(): + output_files = [str(p) for p in txt_dir.glob("*.*")] + + # 5. Structured Return + return { + "command_executed": command_str, + "stdout": stdout, + "stderr": stderr, + "output_files": sorted(output_files) + } + + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"MaxQuant execution failed with return code {e.returncode}", + "output_files": [] + } + +@mcp.tool() +def maxquant_create_mqpar( + output_xml_path: Path, + fasta_files: List[Path], + maxquant_cmd_path: Path, +) -> dict: + """ + Creates a template MaxQuant parameter file (mqpar.xml) from FASTA files. + + This tool is a convenient way to bootstrap a MaxQuant analysis by generating + a configuration file that can be further customized. + + Args: + output_xml_path: The full path where the new mqpar.xml file will be saved. + fasta_files: A list of paths to FASTA database files. + maxquant_cmd_path: Path to the MaxQuant command-line executable (MaxQuantCmd.exe). + + Returns: + A dictionary containing the execution details and the path to the created file. + """ + # 1. Input Validation + if not maxquant_cmd_path.is_file(): + raise FileNotFoundError(f"MaxQuant executable not found at: {maxquant_cmd_path}") + if not fasta_files: + raise ValueError("At least one FASTA file must be provided.") + for f_path in fasta_files: + if not f_path.is_file(): + raise FileNotFoundError(f"FASTA file not found: {f_path}") + + output_xml_path.parent.mkdir(parents=True, exist_ok=True) + + # 2. Command Construction + base_command = ["mono"] if sys.platform != "win32" else [] + command = base_command + [str(maxquant_cmd_path), "--create-mqpar", str(output_xml_path)] + command.extend([str(f) for f in fasta_files]) + command_str = " ".join(command) + + # 3. Subprocess Execution + try: + result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + + output_files = [str(output_xml_path)] if output_xml_path.is_file() else [] + + return { + "command_executed": command_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"MaxQuant mqpar creation failed with return code {e.returncode}", + "output_files": [] + } + +@mcp.tool() +def maxquant_change_folder( + mqpar_xml_file: Path, + new_data_folder: Path, + maxquant_cmd_path: Path, + output_xml_path: Optional[Path] = None, +) -> dict: + """ + Updates all file paths in a mqpar.xml file to point to a new data folder. + + This is useful for making a MaxQuant project portable or reusing a configuration + template with a new dataset. The tool works on a copy to prevent accidental + modification of the original file. + + Args: + mqpar_xml_file: Path to the source MaxQuant parameter file (mqpar.xml). + new_data_folder: Path to the new root folder containing the raw data files. + maxquant_cmd_path: Path to the MaxQuant command-line executable (MaxQuantCmd.exe). + output_xml_path: Optional path for the modified mqpar.xml file. If not provided, + a new file with an '_updated' suffix is created. + + Returns: + A dictionary containing execution details and the path to the modified file. + """ + # 1. Input Validation + if not maxquant_cmd_path.is_file(): + raise FileNotFoundError(f"MaxQuant executable not found at: {maxquant_cmd_path}") + if not mqpar_xml_file.is_file(): + raise FileNotFoundError(f"Input mqpar.xml file not found at: {mqpar_xml_file}") + if not new_data_folder.is_dir(): + raise NotADirectoryError(f"The new data folder does not exist or is not a directory: {new_data_folder}") + + # Work on a copy to avoid modifying the original file in-place + if output_xml_path: + target_xml_file = output_xml_path + else: + target_xml_file = mqpar_xml_file.with_name(f"{mqpar_xml_file.stem}_updated.xml") + + target_xml_file.parent.mkdir(parents=True, exist_ok=True) + shutil.copy(mqpar_xml_file, target_xml_file) + + # 2. Command Construction + base_command = ["mono"] if sys.platform != "win32" else [] + command = base_command + [str(maxquant_cmd_path), "--change-folder", str(target_xml_file), str(new_data_folder)] + command_str = " ".join(command) + + # 3. Subprocess Execution + 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(target_xml_file)] + } + except subprocess.CalledProcessError as e: + if target_xml_file.exists(): + os.remove(target_xml_file) + return { + "command_executed": command_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"MaxQuant change-folder failed with return code {e.returncode}", + "output_files": [] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_maxquant/app/maxquant_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_maxquant/app/maxquant_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..1004535aa3b47298ec86a02f0eca0da0b94b96c9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_maxquant/app/maxquant_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_maxquant/app/maxquant_server.py') +SERVER_NAME = 'biosci_maxquant' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_maxquant/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_maxquant/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_maxquant/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_maxquant/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_maxquant/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..6c94bbafedd3d791c30c5b2c738f99d9c6c10e04 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_maxquant/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-maxquant: + build: . + image: mcp-maxquant:latest + container_name: mcp-maxquant + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=maxquant + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_maxquant/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_maxquant/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9dce32e0462ee702a898b3be3c77bcf371ccc543 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_maxquant/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - maxquant + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_maxquant/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_maxquant/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_maxquant/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mcl/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mcl/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mcl/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_medaka/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_medaka/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5ae0731bf52a3b96391cd25de5fcb35fa0c875a0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_medaka/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install medaka via conda (e.g., from bioconda) +RUN conda install -c bioconda medaka -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/medaka_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/medaka_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/medaka_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_medaka/app/medaka_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_medaka/app/medaka_server.py new file mode 100644 index 0000000000000000000000000000000000000000..99e191e385134d3094c4b648b1b1c79d79c7847d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_medaka/app/medaka_server.py @@ -0,0 +1,372 @@ +import subprocess +from pathlib import Path +from typing import List, Optional, Union + +# No need to import mcp, as per instructions. + +def _run_command(cmd: List[str], cwd: Optional[Path] = None): + """Helper function to run a shell command and handle errors.""" + cmd_str = " ".join(map(str, cmd)) + try: + result = subprocess.run( + cmd, + cwd=cwd, + check=True, + capture_output=True, + text=True + ) + return { + "command_executed": cmd_str, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": cmd_str, + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e), + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": cmd_str, + "stdout": "", + "stderr": f"Error: medaka or one of its dependencies not found. " + f"Please ensure 'medaka' is installed and in your PATH.", + "error": "Executable not found", + "output_files": [] + } + +@mcp.tool() +def medaka_consensus( + input_basecalls: Path, + draft_assembly: Path, + output_directory: Path, + threads: int = 1, + batch_size: Optional[int] = None, + use_bacterial_model: bool = False, +) -> dict: + """ + Creates consensus sequences and variant calls from nanopore sequencing data using neural networks. + + This program uses both samtools and minimap2. If medaka has been installed using + the from-source method these will be present within the medaka environment, + otherwise they will need to be provided by the user. + + Args: + input_basecalls: Path to input basecalls (reads) in .fasta or .fastq format. + draft_assembly: Path to input draft assembly in .fasta format. + output_directory: Path to the output directory where consensus.fasta will be saved. + threads: Number of CPU threads to use. Must be a positive integer. + batch_size: Inference batch size. A value of 100 is suitable for 11Gb GPUs. + Must be a positive integer if provided. + use_bacterial_model: Flag to select the bacterial model if compatible. + A legacy default model will be used if not compatible. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + if not input_basecalls.is_file(): + raise FileNotFoundError(f"Input basecalls file not found: {input_basecalls}") + if not draft_assembly.is_file(): + raise FileNotFoundError(f"Draft assembly file not found: {draft_assembly}") + + output_directory.mkdir(parents=True, exist_ok=True) + + if threads <= 0: + raise ValueError("Number of threads must be a positive integer.") + + cmd = [ + "medaka_consensus", + "-i", str(input_basecalls), + "-d", str(draft_assembly), + "-o", str(output_directory), + "-t", str(threads), + ] + + if batch_size is not None: + if batch_size <= 0: + raise ValueError("Batch size must be a positive integer.") + cmd.extend(["-b", str(batch_size)]) + + if use_bacterial_model: + cmd.append("--bacteria") + + result = _run_command(cmd) + if "error" not in result: + # The documentation explicitly states: "When medaka_consensus has finished running, + # the consensus will be saved to ${OUTDIR}/consensus.fasta." + result["output_files"].append(str(output_directory / "consensus.fasta")) + return result + + +@mcp.tool() +def medaka_variant( + input_reads: Path, + reference_fasta: Path, + output_directory: Path, + threads: int = 1, +) -> dict: + """ + Performs haploid variant calling from nanopore sequencing data. + + Requires reads as a .fasta or .fastq and a reference sequence as a .fasta file. + This function infers the use of an output directory and threads based on + the similar `medaka_consensus` helper script, as the documentation for + `medaka_variant` is less explicit on these parameters. + + Args: + input_reads: Path to input reads in .fasta or .fastq format. Must exist. + reference_fasta: Path to the reference sequence in .fasta format. Must exist. + output_directory: Path to the output directory for variant calling results. + Expected to contain files like variants.vcf.gz. + threads: Number of CPU threads to use. Must be a positive integer. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + if not input_reads.is_file(): + raise FileNotFoundError(f"Input reads file not found: {input_reads}") + if not reference_fasta.is_file(): + raise FileNotFoundError(f"Reference FASTA file not found: {reference_fasta}") + + output_directory.mkdir(parents=True, exist_ok=True) + + if threads <= 0: + raise ValueError("Number of threads must be a positive integer.") + + cmd = [ + "medaka_variant", + "-i", str(input_reads), + "-r", str(reference_fasta), + "-o", str(output_directory), # Inferred from medaka_consensus pattern + "-t", str(threads), # Inferred from medaka_consensus pattern + ] + + result = _run_command(cmd) + if "error" not in result: + # Common output for variant calling is variants.vcf.gz, but not explicitly stated. + # Assuming this pattern for a "workflow" tool. + result["output_files"].append(str(output_directory / "variants.vcf.gz")) + return result + + +@mcp.tool() +def medaka_inference( + input_bam: Path, + output_hdf: Path, + model: Optional[str] = None, + regions: Optional[List[str]] = None, + threads: int = 1, # Recommended not to exceed 2, but allow user to specify. + batch_size: Optional[int] = None, +) -> dict: + """ + Runs the medaka inference algorithm across assembly regions. + + This is a component step of medaka_consensus, useful for parallelization. + It is not recommended to specify a value of --threads greater than 2 for medaka inference + since the compute scaling efficiency is poor beyond this. + + Args: + input_bam: Path to the input BAM file (e.g., from mini_align). Must exist. + output_hdf: Path to the output HDF file. Its parent directory will be created if it doesn't exist. + model: Specify the basecaller model (e.g., 'dna_r10.4.1_e8.2_400bps_hac@v4.1.0:variant'). + If not provided, medaka will attempt to auto-determine. + regions: List of assembly sequence names to restrict action to. + threads: Number of threads to use. Must be a positive integer. + batch_size: Inference batch size. Must be a positive integer if provided. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + if not input_bam.is_file(): + raise FileNotFoundError(f"Input BAM file not found: {input_bam}") + + output_hdf.parent.mkdir(parents=True, exist_ok=True) + + if threads <= 0: + raise ValueError("Number of threads must be a positive integer.") + if threads > 2: + # This is a warning/recommendation, not a hard error. + print(f"Warning: medaka inference performance scales poorly beyond 2 threads. " + f"You specified {threads} threads.") + + cmd = [ + "medaka", "inference", + str(input_bam), + str(output_hdf), + "--threads", str(threads), + ] + + if model: + cmd.extend(["--model", model]) + + if regions: + cmd.append("--region") + cmd.extend(regions) + + if batch_size is not None: + if batch_size <= 0: + raise ValueError("Batch size must be a positive integer.") + cmd.extend(["-b", str(batch_size)]) + + result = _run_command(cmd) + if "error" not in result: + result["output_files"].append(str(output_hdf)) + return result + + +@mcp.tool() +def medaka_sequence( + input_h5_files: List[Path], + assembly_fasta: Path, + polished_assembly_fasta: Path, +) -> dict: + """ + Aggregates results from medaka inference to create consensus sequences. + + This is the final step in the parallel medaka_consensus workflow. + + Args: + input_h5_files: List of one or more HDF files output by medaka inference. + Each path must point to an existing file. + assembly_fasta: Path to the input assembly FASTA file. Must exist. + polished_assembly_fasta: Path to the output polished assembly FASTA file. + Its parent directory will be created if it doesn't exist. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + if not input_h5_files: + raise ValueError("At least one input HDF file must be provided.") + for h5_file in input_h5_files: + if not h5_file.is_file(): + raise FileNotFoundError(f"Input HDF file not found: {h5_file}") + + if not assembly_fasta.is_file(): + raise FileNotFoundError(f"Assembly FASTA file not found: {assembly_fasta}") + + polished_assembly_fasta.parent.mkdir(parents=True, exist_ok=True) + + cmd = [ + "medaka", "sequence", + ] + cmd.extend(map(str, input_h5_files)) + cmd.extend([ + str(assembly_fasta), + str(polished_assembly_fasta), + ]) + + result = _run_command(cmd) + if "error" not in result: + result["output_files"].append(str(polished_assembly_fasta)) + return result + + +@mcp.tool() +def medaka_tools_list_models() -> dict: + """ + Lists all allowed inference models available in medaka. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + cmd = ["medaka", "tools", "list_models"] + result = _run_command(cmd) + return result + + +@mcp.tool() +def medaka_tools_resolve_model( + auto_model_type: str, + input_file: Path, +) -> dict: + """ + Prints the model that automatic model selection will use for a given input file. + + Args: + auto_model_type: Type of auto-model to resolve. Must be one of "consensus", + "variant", or "consensus_bacteria". + input_file: Path to the input BAM or FASTQ file. Must exist. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + if auto_model_type not in ["consensus", "variant", "consensus_bacteria"]: + raise ValueError( + f"Invalid auto_model_type: '{auto_model_type}'. " + "Must be 'consensus', 'variant', or 'consensus_bacteria'." + ) + if not input_file.is_file(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + cmd = [ + "medaka", "tools", "resolve_model", + "--auto_model", auto_model_type, + str(input_file), + ] + + result = _run_command(cmd) + return result + + +@mcp.tool() +def mini_align( + input_basecalls: Path, + reference_fasta: Path, + output_bam: Path, + threads: int = 1, + flag_P: bool = False, + flag_m: bool = False, +) -> dict: + """ + Aligns reads to an input assembly using minimap2 (via mini_align). + + This is a component step of medaka_consensus, useful for parallelization. + + Args: + input_basecalls: Path to input basecalls (reads) in .fasta or .fastq format. Must exist. + reference_fasta: Path to input assembly in .fasta format. Must exist. + output_bam: Path to the output BAM file. Its parent directory will be created if it doesn't exist. + threads: Number of threads to use. Must be a positive integer. + flag_P: Optional flag, meaning not specified in docs but present in example. + flag_m: Optional flag, meaning not specified in docs but present in example. + + Returns: + A dictionary containing the command executed, stdout, stderr, and output files. + """ + # Input validation + if not input_basecalls.is_file(): + raise FileNotFoundError(f"Input basecalls file not found: {input_basecalls}") + if not reference_fasta.is_file(): + raise FileNotFoundError(f"Reference FASTA file not found: {reference_fasta}") + + output_bam.parent.mkdir(parents=True, exist_ok=True) + + if threads <= 0: + raise ValueError("Number of threads must be a positive integer.") + + cmd = [ + "mini_align", + "-i", str(input_basecalls), + "-r", str(reference_fasta), + "-p", str(output_bam), + "-t", str(threads), + ] + + if flag_P: + cmd.append("-P") + if flag_m: + cmd.append("-m") + + result = _run_command(cmd) + if "error" not in result: + result["output_files"].append(str(output_bam)) + return result \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_medaka/app/medaka_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_medaka/app/medaka_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8d5d7d3182b8609e78d9c3f84f53ab4c43069fb8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_medaka/app/medaka_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_medaka/app/medaka_server.py') +SERVER_NAME = 'biosci_medaka' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_medaka/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_medaka/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_medaka/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_medaka/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_medaka/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..075875f5a0824da689e2e6f12efaca712b5797c0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_medaka/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-medaka: + build: . + image: mcp-medaka:latest + container_name: mcp-medaka + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=medaka + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_medaka/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_medaka/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5b574a717527c3bb00979054d53105ba89f166ae --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_medaka/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - medaka + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_medaka/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_medaka/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_medaka/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_megahit/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_megahit/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6548f1499a4590d2054c528e4ec666ea1df68e0a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_megahit/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install megahit via conda (e.g., from bioconda) +RUN conda install -c bioconda megahit -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/megahit_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/megahit_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/megahit_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_megahit/app/megahit_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_megahit/app/megahit_server.py new file mode 100644 index 0000000000000000000000000000000000000000..4928c93789765595a3ab9a052c20ea5b916e0974 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_megahit/app/megahit_server.py @@ -0,0 +1,230 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Union +import tempfile + +@mcp.tool() +def megahit_assemble( + pe1: Optional[str] = None, + pe2: Optional[str] = None, + pe12: Optional[str] = None, + read: Optional[str] = None, + out_dir: str = "./megahit_out", + out_prefix: Optional[str] = None, + min_count: int = 2, + k_list: Optional[str] = None, + k_min: int = 21, + k_max: int = 141, + k_step: int = 12, + no_mercy: bool = False, + bubble_level: int = 2, + merge_level: str = "20,0.95", + prune_level: int = 2, + prune_depth: int = 2, + disconnect_ratio: float = 0.1, + low_local_ratio: float = 0.2, + max_tip_len: Optional[int] = None, + cleaning_rounds: int = 5, + no_local: bool = False, + kmin_1pass: bool = False, + presets: Optional[str] = None, + memory: float = 0.9, + mem_flag: int = 1, + num_cpu_threads: Optional[int] = None, + no_hw_accel: bool = False, + min_contig_len: int = 200, + keep_tmp_files: bool = False, + tmp_dir: Optional[str] = None, + continue_run: bool = False, + test: bool = False, +): + """ + MEGAHIT: An ultra-fast single-node solution for large and complex metagenomics assembly. + + Args: + pe1: Comma-separated list of fasta/q paired-end #1 files, paired with pe2. + pe2: Comma-separated list of fasta/q paired-end #2 files, paired with pe1. + pe12: Comma-separated list of interleaved fasta/q paired-end files. + read: Comma-separated list of fasta/q single-end files. + out_dir: Output directory. + out_prefix: Output prefix (contig file will be OUT_DIR/OUT_PREFIX.contigs.fa). + min_count: Minimum multiplicity for filtering (k_min+1)-mers. + k_list: Comma-separated list of kmer sizes (all must be odd, 15-255, increment <= 28). + k_min: Minimum kmer size (<= 255), must be odd number. + k_max: Maximum kmer size (<= 255), must be odd number. + k_step: Increment of kmer size of each iteration (<= 28), must be even number. + no_mercy: Do not add mercy kmers. + bubble_level: Intensity of bubble merging (0-2), 0 to disable. + merge_level: Merge complex bubbles of length <= l*kmer_size and similarity >= s (format: l,s). + prune_level: Strength of low depth pruning (0-3). + prune_depth: Remove unitigs with avg kmer depth less than this value. + disconnect_ratio: Disconnect unitigs if depth ratio is less than this. + low_local_ratio: Remove unitigs if depth ratio to neighborhood is less than this. + max_tip_len: Remove tips less than this value (default 2*k). + cleaning_rounds: Number of rounds for graph cleaning. + no_local: Disable local assembly. + kmin_1pass: Use 1pass mode to build SdBG of k_min. + presets: Override parameters (e.g., 'meta-sensitive', 'meta-large'). + memory: Max memory in byte (if 0-1, fraction of total machine memory). + mem_flag: SdBG builder memory mode (0: min, 1: moderate, others: use all). + num_cpu_threads: Number of CPU threads. + no_hw_accel: Run without BMI2 and POPCNT hardware instructions. + min_contig_len: Minimum length of contigs to output. + keep_tmp_files: Keep all temporary files. + tmp_dir: Set temp directory. + continue_run: Continue a MEGAHIT run from its last available check point. + test: Run MEGAHIT on a toy test dataset. + """ + cmd = ["megahit"] + + # Input Validation + if not test and not continue_run: + if not any([pe1, pe12, read]): + return {"error": "Must provide at least one input type (-1/-2, --12, or -r) unless --test or --continue is used."} + if pe1 and not pe2: + return {"error": "pe1 (-1) requires pe2 (-2)."} + if pe2 and not pe1: + return {"error": "pe2 (-2) requires pe1 (-1)."} + + # File existence checks for inputs + def check_files(file_str: Optional[str]): + if file_str: + for f in file_str.split(','): + if not Path(f).exists(): + raise FileNotFoundError(f"Input file not found: {f}") + + try: + check_files(pe1) + check_files(pe2) + check_files(pe12) + check_files(read) + except FileNotFoundError as e: + return {"error": str(e)} + + # Build Command + if pe1: cmd.extend(["-1", pe1]) + if pe2: cmd.extend(["-2", pe2]) + if pe12: cmd.extend(["--12", pe12]) + if read: cmd.extend(["-r", read]) + + cmd.extend(["-o", out_dir]) + if out_prefix: cmd.extend(["--out-prefix", out_prefix]) + + cmd.extend(["--min-count", str(min_count)]) + + if k_list: + cmd.extend(["--k-list", k_list]) + else: + cmd.extend(["--k-min", str(k_min)]) + cmd.extend(["--k-max", str(k_max)]) + cmd.extend(["--k-step", str(k_step)]) + + if no_mercy: cmd.append("--no-mercy") + + if not (0 <= bubble_level <= 2): + return {"error": "bubble_level must be between 0 and 2."} + cmd.extend(["--bubble-level", str(bubble_level)]) + + cmd.extend(["--merge-level", merge_level]) + + if not (0 <= prune_level <= 3): + return {"error": "prune_level must be between 0 and 3."} + cmd.extend(["--prune-level", str(prune_level)]) + + cmd.extend(["--prune-depth", str(prune_depth)]) + cmd.extend(["--disconnect-ratio", str(disconnect_ratio)]) + cmd.extend(["--low-local-ratio", str(low_local_ratio)]) + + if max_tip_len is not None: + cmd.extend(["--max-tip-len", str(max_tip_len)]) + + cmd.extend(["--cleaning-rounds", str(cleaning_rounds)]) + + if no_local: cmd.append("--no-local") + if kmin_1pass: cmd.append("--kmin-1pass") + if presets: cmd.extend(["--presets", presets]) + + cmd.extend(["--memory", str(memory)]) + cmd.extend(["--mem-flag", str(mem_flag)]) + + if num_cpu_threads is not None: + cmd.extend(["--num-cpu-threads", str(num_cpu_threads)]) + + if no_hw_accel: cmd.append("--no-hw-accel") + cmd.extend(["--min-contig-len", str(min_contig_len)]) + + if keep_tmp_files: cmd.append("--keep-tmp-files") + if tmp_dir: cmd.extend(["--tmp-dir", tmp_dir]) + if continue_run: cmd.append("--continue") + if test: cmd.append("--test") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + # Identify output contig file + prefix = out_prefix if out_prefix else "final" + contig_file = Path(out_dir) / f"{prefix}.contigs.fa" + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(contig_file)] if contig_file.exists() else [] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": "MEGAHIT execution failed", + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode + } + +@mcp.tool() +def megahit_core_contig2fastg( + k_size: int, + contig_fa: str, + output_fastg: Optional[str] = None +): + """ + Convert MEGAHIT intermediate contigs to FASTG format. + + Args: + k_size: Kmer size of the intermediate contig file. + contig_fa: Path to the intermediate contig file (e.g., k119.contig.fa). + output_fastg: Path to save the FASTG output. If None, returns content in stdout. + """ + contig_path = Path(contig_fa) + if not contig_path.exists(): + return {"error": f"Contig file not found: {contig_fa}"} + + cmd = ["megahit_core", "contig2fastg", str(k_size), str(contig_path)] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + if output_fastg: + out_path = Path(output_fastg) + out_path.write_text(result.stdout) + return { + "command_executed": " ".join(cmd), + "stdout": "FASTG written to file", + "stderr": result.stderr, + "output_files": [str(out_path)] + } + else: + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [] + } + + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": "megahit_core contig2fastg failed", + "stdout": e.stdout, + "stderr": e.stderr, + "return_code": e.returncode + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_megahit/app/megahit_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_megahit/app/megahit_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..fde6574ee6bd1ada0971a4fe4a1551ff382e1303 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_megahit/app/megahit_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_megahit/app/megahit_server.py') +SERVER_NAME = 'biosci_megahit' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_megahit/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_megahit/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_megahit/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_megahit/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_megahit/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..ec644ca19b52b58c93c5ae2294443dcff8b4403b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_megahit/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-megahit: + build: . + image: mcp-megahit:latest + container_name: mcp-megahit + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=megahit + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_megahit/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_megahit/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..565fb2b9b37977c6dd7b759b0200899f36be805e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_megahit/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - megahit + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_megahit/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_megahit/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_megahit/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_meme/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_meme/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..24b807ae1a0c5e40854b89954683c231446d5cf4 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_meme/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install meme via conda (e.g., from bioconda) +RUN conda install -c bioconda meme -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/meme_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/meme_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/meme_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_meme/app/meme_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_meme/app/meme_server.py new file mode 100644 index 0000000000000000000000000000000000000000..845ce492e8b854744db31a3f1da0e9729698ad46 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_meme/app/meme_server.py @@ -0,0 +1,291 @@ +import subprocess +import tempfile +from pathlib import Path +import shutil +from typing import Optional, List + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, this would be provided by the MCP framework. +def tool(func): + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + return wrapper + +mcp = type('mcp', (), {'tool': tool}) + + +@mcp.tool() +def meme( + dataset: Path, + output_dir: Optional[Path] = None, + clobber: bool = False, + background_file: Optional[Path] = None, + alphabet_file: Optional[Path] = None, + fafasta: Optional[Path] = None, + consensus_sequence: Optional[str] = None, + count_file: Optional[Path] = None, + prior_file: Optional[Path] = None, + prior_library: Optional[Path] = None, + beta: Optional[float] = None, + use_llr: bool = False, + negative_seq_file: Optional[Path] = None, + revcomp: bool = False, + sequence_type: Optional[str] = None, + time_limit: Optional[int] = None, + max_dataset_size: Optional[int] = None, + max_iterations: Optional[int] = None, + no_status: bool = False, + brief: bool = False, + print_fasta_max: Optional[int] = None, + print_pred_max: Optional[int] = None, + print_full_pred_seqs: bool = False, + print_helices: bool = False, + print_pvals: bool = False, + print_reasons: bool = False, + print_residues: bool = False, + print_starts: bool = False, + print_strands: bool = False, + print_uniform: bool = False, + print_version: bool = False, + psp_file: Optional[Path] = None, + pssm_file: Optional[Path] = None, + fimo_format: bool = False, + mast_format: bool = False, + mod: str = "zoops", + nmotifs: Optional[int] = None, + evt: Optional[float] = None, + w: Optional[int] = None, + minw: Optional[int] = None, + maxw: Optional[int] = None, + ws: Optional[int] = None, + no_w_in_log: bool = False, + wg: Optional[int] = None, + w_dist: Optional[Path] = None, + nsites: Optional[int] = None, + minsites: Optional[int] = None, + maxsites: Optional[int] = None, + pal: bool = False, + nomatrim: bool = False, + noendgaps: bool = False, + wg_dist: Optional[Path] = None, + wns: Optional[float] = None, + wpen: Optional[float] = None, + spmap: Optional[str] = None, + spfuzz: Optional[float] = None, + cons_dist: Optional[Path] = None, + heapsize: Optional[int] = None, + seed: Optional[int] = None, + tcm_file: Optional[Path] = None, + markov_order: int = 0, + p: Optional[int] = None, + host: Optional[str] = None, +): + """ + Runs the MEME tool for motif discovery in a set of sequences. + + MEME discovers ungapped motifs in a group of related DNA, RNA, or protein sequences. + It represents motifs as position-dependent letter-probability matrices. + + Args: + dataset: Path to the input FASTA file containing sequences. + output_dir: Directory to save output files. If not provided, a temporary directory is used. + clobber: If True, allows overwriting the contents of an existing output directory. + background_file: Path to a file containing a 0-order background model. + alphabet_file: Path to a file defining a custom alphabet. + fafasta: Use FASTA format for sequence ids in count file. + consensus_sequence: Use a consensus sequence for starting point. + count_file: Use a count file for starting point. + prior_file: Path to a file containing position-specific priors (PSPs). + prior_library: Path to a directory containing a library of PSPs. + beta: Beta value for Dirichlet mixture prior. + use_llr: Use LLR for prior. + negative_seq_file: Path to a FASTA file of negative sequences for discriminative motif discovery. + revcomp: Allow motifs to occur on the reverse complement strand of DNA sequences. + sequence_type: Type of sequences. Must be one of 'dna', 'rna', or 'protein'. + time_limit: Maximum running time in seconds. + max_dataset_size: Maximum dataset size in characters. + max_iterations: Maximum number of EM iterations. + no_status: Do not print progress reports. + brief: Brief output. + print_fasta_max: Maximum number of sequences to print in FASTA format. + print_pred_max: Maximum number of predicted sites to print. + print_full_pred_seqs: Print full predicted sequences. + print_helices: Print helix probabilities. + print_pvals: Print p-values. + print_reasons: Print reasons for stopping. + print_residues: Print residue counts. + print_starts: Print start sites. + print_strands: Print strand information. + print_uniform: Print uniform background. + print_version: Print version and exit. + psp_file: Path to a file with position-specific priors. + pssm_file: Path to a file with a position-specific scoring matrix. + fimo_format: Output in FIMO format. + mast_format: Output in MAST format. + mod: Distribution of motifs. One of 'oops', 'zoops', 'anr'. + nmotifs: Number of motifs to find. + evt: E-value threshold for reporting motifs. + w: Exact width of motifs to find. + minw: Minimum width of motifs to find. + maxw: Maximum width of motifs to find. + ws: Site width for ANR model. + no_w_in_log: Do not include width in log-likelihood. + wg: Gap width for ANR model. + w_dist: Path to a file with width distribution. + nsites: Exact number of sites for each motif. + minsites: Minimum number of sites for each motif. + maxsites: Maximum number of sites for each motif. + pal: Force motifs to be palindromic (DNA/RNA only). + nomatrim: Do not perform matrix trimming. + noendgaps: Do not allow end gaps. + wg_dist: Path to a file with gap width distribution. + wns: Probability of no site. + wpen: Width penalty. + spmap: Starting point map type. One of 'uni', 'pam'. + spfuzz: Starting point fuzziness. + cons_dist: Path to a file with consensus distribution. + heapsize: Heap size for ANR model. + seed: Random seed for reproducible results. + tcm_file: Path to a file with a transition count matrix. + markov_order: Order of the Markov background model. + p: Number of processors to use for parallel execution. + host: Hostname for parallel execution. + + Returns: + A dictionary containing the executed command, stdout, stderr, and a list of output file paths. + """ + # --- Input Validation --- + if not dataset.is_file(): + raise FileNotFoundError(f"Input dataset file not found: {dataset}") + + for file_path in [ + background_file, alphabet_file, fafasta, count_file, prior_file, + negative_seq_file, psp_file, pssm_file, w_dist, wg_dist, cons_dist, tcm_file + ]: + if file_path and not Path(file_path).is_file(): + raise FileNotFoundError(f"Input file not found: {file_path}") + + if prior_library and not Path(prior_library).is_dir(): + raise NotADirectoryError(f"Prior library directory not found: {prior_library}") + + if sequence_type and sequence_type not in ["dna", "rna", "protein"]: + raise ValueError("sequence_type must be one of 'dna', 'rna', or 'protein'.") + + if mod not in ["oops", "zoops", "anr"]: + raise ValueError("mod must be one of 'oops', 'zoops', or 'anr'.") + + if spmap and spmap not in ["uni", "pam"]: + raise ValueError("spmap must be one of 'uni' or 'pam'.") + + if w is not None and (minw is not None or maxw is not None): + raise ValueError("Specify 'w', or 'minw' and 'maxw', but not both.") + if (minw is not None and maxw is None) or (minw is None and maxw is not None): + raise ValueError("'minw' and 'maxw' must be specified together.") + + if nsites is not None and (minsites is not None or maxsites is not None): + raise ValueError("Specify 'nsites', or 'minsites' and 'maxsites', but not both.") + if (minsites is not None and maxsites is None) or (minsites is None and maxsites is not None): + raise ValueError("'minsites' and 'maxsites' must be specified together.") + + # --- Command Construction --- + meme_executable = "meme" + if not shutil.which(meme_executable): + raise RuntimeError(f"{meme_executable} executable not found in PATH.") + + cmd = [meme_executable, str(dataset)] + + # Handle output directory + temp_dir_manager = None + if output_dir: + final_output_dir = output_dir + else: + temp_dir_manager = tempfile.TemporaryDirectory() + final_output_dir = Path(temp_dir_manager.name) + + if clobber: + cmd.extend(["-oc", str(final_output_dir)]) + else: + cmd.extend(["-o", str(final_output_dir)]) + + # Add optional arguments + arg_map = { + "bfile": background_file, "alph": alphabet_file, "fafasta": fafasta, + "cons": consensus_sequence, "ctf": count_file, "prior": prior_file, + "plib": prior_library, "b": beta, "neg": negative_seq_file, + "time": time_limit, "maxsize": max_dataset_size, "maxiter": max_iterations, + "print_fasta_max": print_fasta_max, "print_pred_max": print_pred_max, + "psp": psp_file, "pssm": pssm_file, "mod": mod, "nmotifs": nmotifs, + "evt": evt, "w": w, "minw": minw, "maxw": maxw, "ws": ws, "wg": wg, + "w_dist": w_dist, "nsites": nsites, "minsites": minsites, "maxsites": maxsites, + "wg_dist": wg_dist, "wns": wns, "wpen": wpen, "spmap": spmap, + "spfuzz": spfuzz, "cons_dist": cons_dist, "heapsize": heapsize, + "seed": seed, "tcm": tcm_file, "markov_order": markov_order, + "p": p, "host": host + } + for flag, value in arg_map.items(): + if value is not None and value != "zoops" and value != 0: # Exclude defaults + cmd.extend([f"-{flag}", str(value)]) + + # Add boolean flags + bool_flags = { + "use_llr": use_llr, "revcomp": revcomp, "nostatus": no_status, + "brief": brief, "print_full_pred_seqs": print_full_pred_seqs, + "print_helices": print_helices, "print_pvals": print_pvals, + "print_reasons": print_reasons, "print_residues": print_residues, + "print_starts": print_starts, "print_strands": print_strands, + "print_uniform": print_uniform, "print_version": print_version, + "fimo_format": fimo_format, "mast_format": mast_format, + "no_w_in_log": no_w_in_log, "pal": pal, "nomatrim": nomatrim, + "noendgaps": noendgaps + } + for flag, value in bool_flags.items(): + if value: + cmd.append(f"-{flag}") + + if sequence_type: + cmd.append(f"-{sequence_type}") + + # --- Subprocess Execution --- + try: + process = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + + output_files = { + "html_report": final_output_dir / "meme.html", + "text_report": final_output_dir / "meme.txt", + "xml_report": final_output_dir / "meme.xml", + "gff_report": final_output_dir / "meme.gff", + "output_directory": final_output_dir + } + + # Keep only existing files + existing_output_files = { + key: str(path) for key, path in output_files.items() if path.exists() + } + + result = { + "command_executed": " ".join(cmd), + "stdout": process.stdout, + "stderr": process.stderr, + "output_files": existing_output_files, + "return_code": process.returncode + } + + except subprocess.CalledProcessError as e: + result = { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error_message": f"MEME failed with return code {e.returncode}", + "return_code": e.returncode, + "output_files": {} + } + finally: + if temp_dir_manager: + temp_dir_manager.cleanup() + + return result \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_meme/app/meme_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_meme/app/meme_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..901c8819e4badb6d7db97f46f0e99b480875580c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_meme/app/meme_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_meme/app/meme_server.py') +SERVER_NAME = 'biosci_meme' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_meme/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_meme/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_meme/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_meme/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_meme/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..5530eeefa0d19f3edd38466a220e67f4bcb99816 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_meme/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-meme: + build: . + image: mcp-meme:latest + container_name: mcp-meme + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=meme + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_meme/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_meme/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b013bd9e2751b4ce8edcf9428f597ce812ad3568 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_meme/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - meme + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_meme/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_meme/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_meme/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mentalist/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mentalist/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8b7032cdbdf31b34ab9b5ac1de82de8b331b8bc5 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mentalist/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install mentalist via conda (e.g., from bioconda) +RUN conda install -c bioconda mentalist -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/mentalist_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/mentalist_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/mentalist_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mentalist/app/mentalist_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mentalist/app/mentalist_server.py new file mode 100644 index 0000000000000000000000000000000000000000..d9dab14f42cd2478c5e501eb52fc1e627ae684bd --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mentalist/app/mentalist_server.py @@ -0,0 +1,297 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# @mcp.tool() - This decorator is commented out as per the instructions. +# In a real MCP environment, it would be active. + +def build_db( + output_file: Path, + kmer_size: int, + fasta_files: List[Path], + profile: Optional[Path] = None, + compress: bool = False, +): + """ + Build a MentaLiST database from allele sequences. + + Args: + output_file: Path to the output file for the MentaLiST database. + kmer_size: The k-mer size to use for building the database. + fasta_files: A list of FASTA files containing the allele sequences. + profile: Optional path to a profile file for known Sequence Types (STs). + compress: If True, compress the database by finding a covering set of alleles. + """ + # Input validation + if kmer_size <= 0: + raise ValueError("kmer_size must be a positive integer.") + + if not fasta_files: + raise ValueError("At least one FASTA file must be provided in fasta_files.") + + for f_path in fasta_files: + if not f_path.is_file(): + raise FileNotFoundError(f"Input FASTA file not found: {f_path}") + + if profile and not profile.is_file(): + raise FileNotFoundError(f"Profile file not found: {profile}") + + # Ensure output directory exists + output_file.parent.mkdir(parents=True, exist_ok=True) + + # Command construction + cmd = [ + "mentalist", "build_db", + "-o", str(output_file), + "-k", str(kmer_size), + "--fasta_files", + ] + cmd.extend([str(f) for f in fasta_files]) + + if profile: + cmd.extend(["--profile", str(profile)]) + + if compress: + cmd.append("-c") + + command_executed = " ".join(cmd) + + # Subprocess execution + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"database": str(output_file)} + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"MentaLiST build_db failed with exit code {e.returncode}", + "output_files": {} + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "mentalist command not found. Please ensure it is in your PATH.", + "error": "Executable not found.", + "output_files": {} + } + + +# @mcp.tool() +def call( + output_file: Path, + sample_name: str, + input_reads: List[Path], + database: Path, + report_novel: bool = False, + create_novel_fasta: bool = False, + threads: int = 1, +): + """ + Perform MLST calling on sequencing reads against a MentaLiST database. + + Args: + output_file: Path to the output file for the MLST call results. + sample_name: The name of the sample being analyzed. + input_reads: A list of input FASTA/FASTQ files (can be gzipped). + database: Path to the MentaLiST database file. + report_novel: If True, report novel alleles. + create_novel_fasta: If True, create a FASTA file with novel alleles. + threads: Number of threads to use for the analysis. + """ + # Input validation + if not sample_name.strip(): + raise ValueError("sample_name cannot be empty.") + + if not input_reads: + raise ValueError("At least one input reads file must be provided.") + + for read_file in input_reads: + if not read_file.is_file(): + raise FileNotFoundError(f"Input reads file not found: {read_file}") + + if not database.is_file(): + raise FileNotFoundError(f"MentaLiST database not found: {database}") + + if threads <= 0: + raise ValueError("threads must be a positive integer.") + + # Ensure output directory exists + output_file.parent.mkdir(parents=True, exist_ok=True) + + # Command construction + cmd = [ + "mentalist", "call", + "-o", str(output_file), + "-s", sample_name, + "-k", str(database), + "-t", str(threads), + "-i", + ] + cmd.extend([str(f) for f in input_reads]) + + if report_novel: + cmd.append("--novel") + + if create_novel_fasta: + cmd.append("--fasta") + + command_executed = " ".join(cmd) + + # Subprocess execution + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + # Note: The name of the novel fasta file is not explicitly defined. + # We return the primary output file. The user should be aware of + # how MentaLiST names its auxiliary outputs if create_novel_fasta is used. + 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": f"MentaLiST call failed with exit code {e.returncode}", + "output_files": {} + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "mentalist command not found. Please ensure it is in your PATH.", + "error": "Executable not found.", + "output_files": {} + } + + +# @mcp.tool() +def list_pubmlst( + url: str = "https://pubmlst.org/data/dbases.xml", +): + """ + List all available MLST schemes from pubmlst.org. + + Args: + url: The URL to the PubMLST databases XML file. + """ + # Command construction + cmd = [ + "mentalist", "list_pubmlst", + "--url", url, + ] + command_executed = " ".join(cmd) + + # Subprocess execution + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {} + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"MentaLiST list_pubmlst failed with exit code {e.returncode}", + "output_files": {} + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "mentalist command not found. Please ensure it is in your PATH.", + "error": "Executable not found.", + "output_files": {} + } + + +# @mcp.tool() +def download_pubmlst( + output_folder: Path, + scheme_name: str, + url: str = "https://pubmlst.org/data/dbases.xml", +): + """ + Download an MLST scheme from pubmlst.org. + + Args: + output_folder: The folder where the scheme files will be downloaded. + scheme_name: The name of the scheme to download. + url: The URL to the PubMLST databases XML file. + """ + # Input validation + if not scheme_name.strip(): + raise ValueError("scheme_name cannot be empty.") + + # Create output directory if it doesn't exist + output_folder.mkdir(parents=True, exist_ok=True) + + # Command construction + cmd = [ + "mentalist", "download_pubmlst", + "-o", str(output_folder), + "-s", scheme_name, + "--url", url, + ] + command_executed = " ".join(cmd) + + # Subprocess execution + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + # The tool downloads files into the specified folder. We return the folder path. + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": {"scheme_folder": str(output_folder)} + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"MentaLiST download_pubmlst failed with exit code {e.returncode}", + "output_files": {} + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "mentalist command not found. Please ensure it is in your PATH.", + "error": "Executable not found.", + "output_files": {} + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mentalist/app/mentalist_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mentalist/app/mentalist_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..7b92cc717383f0fb72f3f3f28e96a660199e9797 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mentalist/app/mentalist_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mentalist/app/mentalist_server.py') +SERVER_NAME = 'biosci_mentalist' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mentalist/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mentalist/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mentalist/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mentalist/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mentalist/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..bf704f5feb2a08475db7566d8a60dcb3257be79a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mentalist/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-mentalist: + build: . + image: mcp-mentalist:latest + container_name: mcp-mentalist + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=mentalist + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mentalist/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mentalist/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..52a80cbd937dd5b841c71dc9855757de25d774a1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mentalist/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - mentalist + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mentalist/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mentalist/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mentalist/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metagenome-atlas/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metagenome-atlas/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d755e161b7b6fd2926ac9db2ca95fdc51437c8d9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metagenome-atlas/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install metagenome-atlas via conda (e.g., from bioconda) +RUN conda install -c bioconda metagenome-atlas -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/metagenome-atlas_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/metagenome-atlas_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/metagenome-atlas_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metagenome-atlas/app/metagenome-atlas_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metagenome-atlas/app/metagenome-atlas_server.py new file mode 100644 index 0000000000000000000000000000000000000000..17c2a3e5279572b5f5088c454e2053e1898c3daa --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metagenome-atlas/app/metagenome-atlas_server.py @@ -0,0 +1,232 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# @mcp.tool() decorator is commented out as per instructions +# but would be present in a real MCP environment. + + +# @mcp.tool() +def atlas_init( + samples: List[Path], + db_dir: Path, + working_dir: Path, + configfile: Optional[Path] = None, + threads: int = 8, + assembler: str = "megahit", + binner: str = "metabat2", + no_conda: bool = False, +) -> dict: + """ + Initializes a new metagenome-atlas project. + + This command sets up the working directory, creates a samples.tsv file from the + input FASTQ files, and generates a default config.yaml. It also downloads + the necessary databases to the specified database directory. + """ + # --- Input Validation --- + if not samples: + raise ValueError("At least one sample FASTQ file must be provided.") + for sample_path in samples: + if not sample_path.is_file(): + raise FileNotFoundError(f"Input sample file not found: {sample_path}") + + if threads < 1: + raise ValueError("The number of threads must be at least 1.") + + allowed_assemblers = ["megahit", "spades"] + if assembler not in allowed_assemblers: + raise ValueError( + f"Invalid assembler '{assembler}'. Must be one of {allowed_assemblers}." + ) + + allowed_binners = ["metabat2", "maxbin2", "concoct", "all"] + if binner not in allowed_binners: + raise ValueError( + f"Invalid binner '{binner}'. Must be one of {allowed_binners}." + ) + + if configfile and not configfile.is_file(): + raise FileNotFoundError(f"Custom config file not found: {configfile}") + + # --- Command Construction --- + cmd = [ + "atlas", + "init", + "--db-dir", + str(db_dir), + "--working-dir", + str(working_dir), + "--threads", + str(threads), + "--assembler", + assembler, + "--binner", + binner, + ] + + if configfile: + cmd.extend(["--configfile", str(configfile)]) + + if no_conda: + cmd.append("--no-conda") + + cmd.extend([str(p) for p in samples]) + + command_executed = " ".join(cmd) + + # --- Subprocess Execution --- + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + stdout = result.stdout + stderr = result.stderr + + # Define expected output files + output_files = [ + str(working_dir / "samples.tsv"), + str(working_dir / "config.yaml"), + str(working_dir / "Snakefile"), + ] + + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'atlas' command not found. Make sure metagenome-atlas is installed and in your PATH.", + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + + # --- Return Structured Output --- + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } + + +# @mcp.tool() +def atlas_run( + working_dir: Path, + targets: Optional[List[str]] = None, + configfile: Optional[Path] = None, + cores: int = 8, + jobs: Optional[int] = None, + profile: Optional[str] = None, + use_conda: bool = False, + conda_prefix: Optional[Path] = None, + snake_args: Optional[str] = None, +) -> dict: + """ + Executes the metagenome-atlas workflow on an initialized project. + + This command invokes Snakemake to run the pipeline based on the config.yaml + and samples.tsv in the specified working directory. + """ + # --- Input Validation --- + if not working_dir.is_dir(): + raise FileNotFoundError( + f"Working directory not found: {working_dir}. Please run 'atlas_init' first." + ) + if not (working_dir / "config.yaml").is_file(): + raise FileNotFoundError( + f"Project not initialized in '{working_dir}'. 'config.yaml' is missing." + ) + + if cores < 1: + raise ValueError("The number of cores must be at least 1.") + if jobs is not None and jobs < 1: + raise ValueError("The number of jobs must be at least 1 if specified.") + + if configfile and not configfile.is_file(): + raise FileNotFoundError(f"Custom config file not found: {configfile}") + + # --- Command Construction --- + cmd = [ + "atlas", + "run", + "--working-dir", + str(working_dir), + "--cores", + str(cores), + ] + + if configfile: + cmd.extend(["--configfile", str(configfile)]) + if jobs: + cmd.extend(["--jobs", str(jobs)]) + if profile: + cmd.extend(["--profile", profile]) + if use_conda: + cmd.append("--use-conda") + if conda_prefix: + cmd.extend(["--conda-prefix", str(conda_prefix)]) + if snake_args: + cmd.extend(snake_args.split()) + + if targets: + cmd.extend(targets) + else: + # Default target is 'all' if not specified + cmd.append("all") + + command_executed = " ".join(cmd) + + # --- Subprocess Execution --- + try: + # The 'run' command can take a long time. + # It's executed within the context of the working directory. + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + stdout = result.stdout + stderr = result.stderr + + # Define representative output directories/files + output_files = [ + str(working_dir / "ASSEMBLY"), + str(working_dir / "BINNING"), + str(working_dir / "QC"), + str(working_dir / "genomes"), + str(working_dir / "annotations"), + str(working_dir / "reports"), + ] + + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'atlas' command not found. Make sure metagenome-atlas is installed and in your PATH.", + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": [], + } + + # --- Return Structured Output --- + return { + "command_executed": command_executed, + "stdout": stdout, + "stderr": stderr, + "output_files": output_files, + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metagenome-atlas/app/metagenome-atlas_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metagenome-atlas/app/metagenome-atlas_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..76745700b675e268db0064106a64f0cea251314e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metagenome-atlas/app/metagenome-atlas_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metagenome-atlas/app/metagenome-atlas_server.py') +SERVER_NAME = 'biosci_metagenome_atlas' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metagenome-atlas/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metagenome-atlas/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metagenome-atlas/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metagenome-atlas/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metagenome-atlas/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..204256fa812e776c98aecae7152e596879b282e6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metagenome-atlas/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-metagenome-atlas: + build: . + image: mcp-metagenome-atlas:latest + container_name: mcp-metagenome-atlas + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=metagenome-atlas + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metagenome-atlas/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metagenome-atlas/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..0d7cf10169e660b59b7d47c7ec88f222833b2732 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metagenome-atlas/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - metagenome-atlas + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metagenome-atlas/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metagenome-atlas/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metagenome-atlas/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ded0789ff7664bfa73835199482c300e491f80b1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install metaphlan via conda (e.g., from bioconda) +RUN conda install -c bioconda metaphlan -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/metaphlan_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/metaphlan_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/metaphlan_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan/app/metaphlan_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan/app/metaphlan_server.py new file mode 100644 index 0000000000000000000000000000000000000000..5577111d9e1ffa7f93224d20cdc719415b281f84 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan/app/metaphlan_server.py @@ -0,0 +1,246 @@ +import subprocess +import logging +from pathlib import Path +from typing import List, Optional, Literal + +# It is assumed that the mcp package is available in the environment. +# Since the user requested not to import it, we define a dummy decorator +# to allow the code to be syntactically valid. +class mcp: + def tool(func=None, **kwargs): + if func: + return func + return lambda f: f + +logger = logging.getLogger(__name__) + +@mcp.tool() +def metaphlan( + input_file: Path, + bowtie2db: Path, + output_file: Path, + mpa_pkl: Optional[Path] = None, + bowtie2_exe: Optional[Path] = None, + bowtie2out: Optional[Path] = None, + no_map: bool = False, + tmp_dir: Optional[Path] = None, + graphlan_out: Optional[Path] = None, + save_intermediate_files: bool = False, + nproc: int = 1, + read_min_len: Optional[int] = None, + min_cu_len: Optional[int] = None, + min_alignment_len: Optional[int] = None, + ignore_archaea: bool = False, + ignore_eukaryotes: bool = False, + ignore_viruses: bool = False, + ignore_bacteria: bool = False, + stat_q: Optional[float] = None, + min_cl_marker: Optional[int] = None, + avoid_discards: bool = False, + stat: Optional[Literal["avg_g", "avg_l", "tavg_g", "tavg_l", "wavg_g", "wavg_l", "med"]] = None, + unknown_estimation: bool = False, + add_viruses: bool = False, + index: Optional[str] = None, + input_type: Optional[Literal["fastq", "fasta", "bowtie2out", "sam"]] = None, + profile_v30_bugs: bool = False, + subclade_estimation: bool = False, + sample_id_key: Optional[str] = None, + use_group_separator: bool = False, + biom_output_file: Optional[Path] = None, + legacy_biom_output: bool = False, + mdelim: Optional[str] = None, + min_ab: Optional[float] = None, + force: bool = False, + force_download: bool = False, + blast_db: Optional[Path] = None, + blast_exe: Optional[Path] = None, + blast_output_file: Optional[Path] = None, + unclassified_estimation: bool = False, + cami_format_output: bool = False, + verbose: bool = False, +): + """ + Runs MetaPhlAn for taxonomic profiling of metagenomic shotgun sequencing data. + + This tool takes a metagenomic sample (in various formats) and produces a profile + of the clades present in the sample and their relative abundances. + """ + # Input validation + if not input_file.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + if not bowtie2db.is_dir(): + raise NotADirectoryError(f"Bowtie2 database path is not a valid directory: {bowtie2db}") + if nproc < 1: + raise ValueError("--nproc must be a positive integer.") + + # Command construction + cmd = [ + "metaphlan", + str(input_file), + "--output_file", str(output_file), + "--bowtie2db", str(bowtie2db), + "--nproc", str(nproc), + ] + + # Add optional parameters if they are provided + if mpa_pkl: cmd.extend(["--mpa_pkl", str(mpa_pkl)]) + if bowtie2_exe: cmd.extend(["--bowtie2_exe", str(bowtie2_exe)]) + if bowtie2out: cmd.extend(["--bowtie2out", str(bowtie2out)]) + if tmp_dir: cmd.extend(["--tmp_dir", str(tmp_dir)]) + if graphlan_out: cmd.extend(["--graphlan_out", str(graphlan_out)]) + if read_min_len is not None: cmd.extend(["--read_min_len", str(read_min_len)]) + if min_cu_len is not None: cmd.extend(["--min_cu_len", str(min_cu_len)]) + if min_alignment_len is not None: cmd.extend(["--min_alignment_len", str(min_alignment_len)]) + if stat_q is not None: cmd.extend(["--stat_q", str(stat_q)]) + if min_cl_marker is not None: cmd.extend(["--min_cl_marker", str(min_cl_marker)]) + if stat: cmd.extend(["--stat", stat]) + if index: cmd.extend(["--index", index]) + if input_type: cmd.extend(["--input_type", input_type]) + if sample_id_key: cmd.extend(["--sample_id_key", sample_id_key]) + if biom_output_file: cmd.extend(["--biom_output_file", str(biom_output_file)]) + if mdelim: cmd.extend(["--mdelim", mdelim]) + if min_ab is not None: cmd.extend(["--min_ab", str(min_ab)]) + if blast_db: cmd.extend(["--blast_db", str(blast_db)]) + if blast_exe: cmd.extend(["--blast_exe", str(blast_exe)]) + if blast_output_file: cmd.extend(["--blast_output_file", str(blast_output_file)]) + + # Add boolean flags + if no_map: cmd.append("--no_map") + if save_intermediate_files: cmd.append("--save_intermediate_files") + if ignore_archaea: cmd.append("--ignore_archaea") + if ignore_eukaryotes: cmd.append("--ignore_eukaryotes") + if ignore_viruses: cmd.append("--ignore_viruses") + if ignore_bacteria: cmd.append("--ignore_bacteria") + if avoid_discards: cmd.append("--avoid_discards") + if unknown_estimation: cmd.append("--unknown_estimation") + if add_viruses: cmd.append("--add_viruses") + if profile_v30_bugs: cmd.append("--profile_v30_bugs") + if subclade_estimation: cmd.append("--subclade_estimation") + if use_group_separator: cmd.append("--use_group_separator") + if legacy_biom_output: cmd.append("--legacy_biom_output") + if force: cmd.append("--force") + if force_download: cmd.append("--force_download") + if unclassified_estimation: cmd.append("--unclassified_estimation") + if cami_format_output: cmd.append("--CAMI_format_output") + if verbose: cmd.append("--verbose") + + command_executed = " ".join(cmd) + logger.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'metaphlan' command not found. Please ensure it is in your PATH.", + "output_files": {}, + "return_code": 1 + } + except subprocess.CalledProcessError as e: + logger.error(f"MetaPhlAn execution failed with return code {e.returncode}") + logger.error(f"Stderr: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": {}, + "return_code": e.returncode + } + + output_files = {} + if output_file.exists(): + output_files["profiled_output"] = str(output_file) + if biom_output_file and biom_output_file.exists(): + output_files["biom_output"] = str(biom_output_file) + if graphlan_out and graphlan_out.exists(): + output_files["graphlan_output"] = str(graphlan_out) + if blast_output_file and blast_output_file.exists(): + output_files["blast_output"] = str(blast_output_file) + if bowtie2out and bowtie2out.exists(): + output_files["bowtie2_output"] = str(bowtie2out) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + "return_code": 0 + } + + +@mcp.tool() +def merge_metaphlan_tables( + input_files: List[Path], + output_file: Optional[Path] = None, + legacy_out: bool = False, +): + """ + Merges multiple MetaPhlAn output files into a single table. + + This utility script combines abundance tables from multiple samples into a + single matrix, which is useful for downstream comparative analysis. + """ + # Input validation + if not input_files: + raise ValueError("At least one input file must be provided.") + for f in input_files: + if not f.exists(): + raise FileNotFoundError(f"Input file not found: {f}") + + # Command construction + cmd = ["merge_metaphlan_tables.py"] + cmd.extend([str(f) for f in input_files]) + + if output_file: + cmd.extend(["-o", str(output_file)]) + if legacy_out: + cmd.append("--legacy_out") + + command_executed = " ".join(cmd) + logger.info(f"Executing command: {command_executed}") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'merge_metaphlan_tables.py' command not found. Please ensure it is in your PATH.", + "output_files": {}, + "return_code": 1 + } + except subprocess.CalledProcessError as e: + logger.error(f"merge_metaphlan_tables.py execution failed with return code {e.returncode}") + logger.error(f"Stderr: {e.stderr}") + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "output_files": {}, + "return_code": e.returncode + } + + output_files = {} + if output_file and output_file.exists(): + output_files["merged_table"] = str(output_file) + + # If output_file is not specified, the result is in stdout + # The MCP server would handle this stdout as the primary output. + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + "return_code": 0 + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan/app/metaphlan_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan/app/metaphlan_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..8376dca64ccdfa1cf354712a6d0ad23423cdea5a --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan/app/metaphlan_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan/app/metaphlan_server.py') +SERVER_NAME = 'biosci_metaphlan' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..b1317c9d038ac532a35856962c5e7da551edc08b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-metaphlan: + build: . + image: mcp-metaphlan:latest + container_name: mcp-metaphlan + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=metaphlan + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..484b506d73ac8084829fa4a39e18f433dd08aa3e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - metaphlan + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan2/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan2/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..8b3f5d366c7e6fc56d00f77c193b2d404c33a1b2 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan2/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install metaphlan2 via conda (e.g., from bioconda) +RUN conda install -c bioconda metaphlan2 -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/metaphlan2_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/metaphlan2_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/metaphlan2_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan2/app/metaphlan2_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan2/app/metaphlan2_server.py new file mode 100644 index 0000000000000000000000000000000000000000..2e50c9727b99069d2ac99e5c9f4e6db73eab8682 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan2/app/metaphlan2_server.py @@ -0,0 +1,258 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Union + +@mcp.tool() +def metaphlan2_profile( + input_file: str, + output_file: str, + input_type: str = "fastq", + bowtie2out: Optional[str] = None, + bowtie2db: Optional[str] = None, + mpa_pkl: Optional[str] = None, + nproc: int = 1, + tax_lev: str = "a", + min_cu_len: int = 2000, + min_alignment_len: Optional[int] = None, + ignore_eukaryotes: bool = False, + ignore_bacteria: bool = False, + ignore_archaea: bool = False, + stat: str = "avg_g", + biom_output_file: Optional[str] = None, + tmp_dir: Optional[str] = None, +): + """ + Perform metagenomic phylogenetic profiling using MetaPhlAn2. + + Args: + input_file: The input file (fastq, fasta, sam, or bowtie2out). + output_file: The tab-separated output file containing the profiling results. + input_type: Type of input file. Choices: 'fastq', 'fasta', 'bowtie2out', 'sam'. + bowtie2out: Path to the file where the bowtie2 alignment results will be stored. + bowtie2db: The path to the folder containing the Bowtie2 database. + mpa_pkl: The metadata pickle file associated with the database. + nproc: Number of CPUs to use for parallelizing the mapping. + tax_lev: Taxonomic level to report. 'a' (all), 'k' (kingdom), 'p' (phylum), 'c' (class), 'o' (order), 'f' (family), 'g' (genus), 's' (species), 't' (strain). + min_cu_len: Minimum total nucleotide length for the markers of a clade to be considered present. + min_alignment_len: The minimum alignment length to consider a read as mapped. + ignore_eukaryotes: If True, do not profile eukaryotic organisms. + ignore_bacteria: If True, do not profile bacterial organisms. + ignore_archaea: If True, do not profile archaeal organisms. + stat: Statistical metric to use. Choices: 'avg_g', 'avg_l', 'tavg_g', 'tavg_l', 'wavg_g', 'wavg_l', 'med'. + biom_output_file: If provided, output the results in BIOM format to this file. + tmp_dir: Directory for temporary files. + """ + # Input validation + input_path = Path(input_file) + if not input_path.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + valid_input_types = ["fastq", "fasta", "bowtie2out", "sam"] + if input_type not in valid_input_types: + raise ValueError(f"input_type must be one of {valid_input_types}") + + valid_stats = ["avg_g", "avg_l", "tavg_g", "tavg_l", "wavg_g", "wavg_l", "med"] + if stat not in valid_stats: + raise ValueError(f"stat must be one of {valid_stats}") + + valid_tax_levs = ["a", "k", "p", "c", "o", "f", "g", "s", "t"] + if tax_lev not in valid_tax_levs: + raise ValueError(f"tax_lev must be one of {valid_tax_levs}") + + # Build command + cmd = ["metaphlan2.py", str(input_path), str(output_file)] + + cmd.extend(["--input_type", input_type]) + cmd.extend(["--nproc", str(nproc)]) + cmd.extend(["--tax_lev", tax_lev]) + cmd.extend(["--min_cu_len", str(min_cu_len)]) + cmd.extend(["--stat", stat]) + + if bowtie2out: + cmd.extend(["--bowtie2out", bowtie2out]) + + if bowtie2db: + cmd.extend(["--bowtie2db", bowtie2db]) + + if mpa_pkl: + cmd.extend(["--mpa_pkl", mpa_pkl]) + + if min_alignment_len is not None: + cmd.extend(["--min_alignment_len", str(min_alignment_len)]) + + if ignore_eukaryotes: + cmd.append("--ignore_eukaryotes") + + if ignore_bacteria: + cmd.append("--ignore_bacteria") + + if ignore_archaea: + cmd.append("--ignore_archaea") + + if biom_output_file: + cmd.extend(["--biom", biom_output_file]) + + if tmp_dir: + cmd.extend(["--tmp_dir", tmp_dir]) + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file] + ([biom_output_file] if biom_output_file else []) + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def merge_metaphlan_tables( + input_files: List[str], + output_file: str, +): + """ + Merge multiple MetaPhlAn2 output tables into a single abundance matrix. + + Args: + input_files: List of paths to MetaPhlAn2 output files to be merged. + output_file: Path to the merged output table. + """ + # Validate input files + validated_inputs = [] + for f in input_files: + p = Path(f) + if not p.exists(): + raise FileNotFoundError(f"Input file not found: {f}") + validated_inputs.append(str(p)) + + # merge_metaphlan_tables.py usually takes files as positional arguments + cmd = ["merge_metaphlan_tables.py"] + validated_inputs + + try: + # This script typically outputs to stdout, so we capture it and write to file + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + + with open(output_file, "w") as f_out: + f_out.write(result.stdout) + + return { + "command_executed": " ".join(cmd) + f" > {output_file}", + "stdout": "Merging complete.", + "stderr": result.stderr, + "output_files": [output_file] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def metaphlan_hclust_heatmap( + input_file: str, + output_file: str, + top_taxa: int = 25, + min_abundance: float = 0.0, + tax_lev: str = "s", + clustering_method: str = "average", + distance_metric: str = "euclidean", + color_map: str = "jet", + log_scale: bool = False, +): + """ + Generate a hierarchical clustering heatmap from a merged MetaPhlAn2 table. + + Args: + input_file: Path to the merged MetaPhlAn2 abundance table. + output_file: Path to the output image file (e.g., .png, .pdf, .svg). + top_taxa: Number of most abundant taxa to display. + min_abundance: Minimum abundance threshold for including a taxon. + tax_lev: Taxonomic level to display. 'k', 'p', 'c', 'o', 'f', 'g', 's'. + clustering_method: Method for hierarchical clustering (e.g., 'average', 'single', 'complete'). + distance_metric: Metric for distance calculation (e.g., 'euclidean', 'braycurtis'). + color_map: Matplotlib color map to use for the heatmap. + log_scale: Whether to use a log scale for abundances. + """ + input_path = Path(input_file) + if not input_path.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + cmd = [ + "metaphlan_hclust_heatmap.py", + "-i", str(input_path), + "-o", output_file, + "--top", str(top_taxa), + "--minv", str(min_abundance), + "-l", tax_lev, + "-m", clustering_method, + "-d", distance_metric, + "-c", color_map + ] + + if log_scale: + cmd.append("--log") + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_file] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": str(e) + } + +@mcp.tool() +def metaphlan2_to_biom( + input_file: str, + output_biom: str, +): + """ + Convert a MetaPhlAn2 output table to BIOM format. + + Args: + input_file: Path to the MetaPhlAn2 output table. + output_biom: Path to the output BIOM file. + """ + input_path = Path(input_file) + if not input_path.exists(): + raise FileNotFoundError(f"Input file not found: {input_file}") + + # MetaPhlAn2 provides a specific script for this or uses the --biom flag in the main script. + # If using the standalone conversion script: + cmd = [ + "metaphlan2biom.py", + str(input_path), + "--biom_file", output_biom + ] + + try: + result = subprocess.run(cmd, capture_output=True, text=True, check=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_biom] + } + except subprocess.CalledProcessError as e: + # Fallback: Some versions might not have metaphlan2biom.py but use biom-format directly + return { + "command_executed": " ".join(cmd), + "stdout": e.stdout, + "stderr": e.stderr, + "error": "Failed to convert to BIOM. Ensure metaphlan2biom.py is in your PATH." + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan2/app/metaphlan2_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan2/app/metaphlan2_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..578b94f554de6c998db4cb1e3b544040f967eda9 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan2/app/metaphlan2_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan2/app/metaphlan2_server.py') +SERVER_NAME = 'biosci_metaphlan2' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan2/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan2/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan2/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan2/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan2/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..58da1eb2cb2146dde51eda1fddc94239272854a0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan2/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-metaphlan2: + build: . + image: mcp-metaphlan2:latest + container_name: mcp-metaphlan2 + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=metaphlan2 + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan2/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan2/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..c281590d429c6d4f8215a3968af3959c6002c2d1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan2/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - metaphlan2 + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan2/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan2/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_metaphlan2/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mikado/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mikado/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4a86b54822351d724ec57dd4385403125bb9da77 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mikado/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install mikado via conda (e.g., from bioconda) +RUN conda install -c bioconda mikado -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/mikado_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/mikado_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/mikado_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mikado/app/mikado_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mikado/app/mikado_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f6cf9195a5073e6a049f22474f22ffce9cc04753 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mikado/app/mikado_server.py @@ -0,0 +1,688 @@ +import subprocess +import tempfile +from pathlib import Path +from typing import List, Optional + +# @mcp.tool() +def mikado_configure( + scoring_file: Path, + requirements_file: Path, + preset: str = "standard", + copy_json: Optional[Path] = None, + force: bool = False, +): + """ + Creates template configuration files (scoring and requirements) for Mikado. + + Args: + scoring_file: Path to the scoring file to create (e.g., scoring.yaml). + requirements_file: Path to the requirements file to create (e.g., requirements.yaml). + preset: The preset configuration to use. + copy_json: Path to copy the default JSON schema to. + force: If True, overwrite existing files. + """ + preset_choices = ["standard", "sensitive", "cautious", "mag", "pacbio-isoseq"] + if preset not in preset_choices: + raise ValueError(f"Invalid preset '{preset}'. Choose from {preset_choices}.") + + cmd = [ + "mikado", "configure", + str(scoring_file), + str(requirements_file), + "--preset", preset, + ] + + if copy_json: + cmd.extend(["--copy-json", str(copy_json)]) + if force: + cmd.append("--force") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Mikado configure failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\nStdout: {e.stdout}" + ) from e + + output_files = [str(scoring_file), str(requirements_file)] + if copy_json: + output_files.append(str(copy_json)) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + + +# @mcp.tool() +def mikado_prepare( + json_conf: Path, + reference: Path, + transcripts: Path, + output_prefix: str = "mikado", + log_file: Optional[Path] = None, + log_level: str = "INFO", + cpus: int = 1, + seed: Optional[int] = None, + no_cds_validation: bool = False, + write_invalid: Optional[Path] = None, + tempdir: Optional[Path] = None, +): + """ + Prepares transcript data for Mikado by creating a consolidated GFF3 file and transcript sequences. + + Args: + json_conf: Path to the configuration file in JSON format listing input GFF/GTF files. + reference: Path to the reference genome FASTA file. + transcripts: Path to the transcript sequences in FASTA format. + output_prefix: Prefix for the output files. + log_file: Path to the log file. + log_level: Logging level. + cpus: Number of CPUs to use. + seed: Random seed for reproducibility. + no_cds_validation: If True, disables CDS validation against the reference genome. + write_invalid: Path to write invalid transcripts to. + tempdir: Path to a temporary directory. + """ + if not json_conf.exists(): + raise FileNotFoundError(f"Configuration file not found: {json_conf}") + if not reference.exists(): + raise FileNotFoundError(f"Reference genome not found: {reference}") + if not transcripts.exists(): + raise FileNotFoundError(f"Transcripts FASTA not found: {transcripts}") + + log_level_choices = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] + if log_level.upper() not in log_level_choices: + raise ValueError(f"Invalid log level '{log_level}'. Choose from {log_level_choices}.") + + if cpus < 1: + raise ValueError("Number of CPUs must be at least 1.") + + cmd = [ + "mikado", "prepare", + "--json-conf", str(json_conf), + "--reference", str(reference), + "--transcripts", str(transcripts), + "-o", output_prefix, + "--log-level", log_level.upper(), + "--cpus", str(cpus), + ] + + if log_file: + cmd.extend(["--log-file", str(log_file)]) + if seed is not None: + cmd.extend(["--seed", str(seed)]) + if no_cds_validation: + cmd.append("--no-cds-validation") + if write_invalid: + cmd.extend(["--write-invalid", str(write_invalid)]) + if tempdir: + cmd.extend(["--tempdir", str(tempdir)]) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Mikado prepare failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\nStdout: {e.stdout}" + ) from e + + output_files_paths = [ + Path(f"{output_prefix}.loci.gff3"), + Path(f"{output_prefix}.transcripts.fasta"), + ] + if log_file: + output_files_paths.append(log_file) + if write_invalid: + output_files_paths.append(write_invalid) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(p) for p in output_files_paths if p.exists()], + } + + +# @mcp.tool() +def mikado_serialise( + json_conf: Path, + output_file: Path = Path("mikado.db"), + blast_xml: Optional[List[Path]] = None, + blast_targets: Optional[Path] = None, + orfs: Optional[List[Path]] = None, + junctions: Optional[List[Path]] = None, + quantification: Optional[List[str]] = None, + db_type: str = "sqlite", + db_name: Optional[str] = None, + db_user: Optional[str] = None, + db_password: Optional[str] = None, + db_host: Optional[str] = None, + db_port: Optional[int] = None, + log_file: Optional[Path] = None, + log_level: str = "INFO", + cpus: int = 1, + chunk_size: int = 10000, + force: bool = False, +): + """ + Loads prepared data and external evidence (BLAST, ORFs, junctions) into a Mikado database. + + Args: + json_conf: Path to the configuration file in JSON format. + output_file: Path to the output database file (for sqlite). + blast_xml: List of paths to BLAST XML results. + blast_targets: Path to a file listing BLAST targets. + orfs: List of paths to ORF predictions in GFF3 format. + junctions: List of paths to Portcullis junctions files in GFF3 format. + quantification: List of quantification files in 'name:path' format. + db_type: Type of database to use. + db_name: Database name (for mysql/postgresql). + db_user: Database user (for mysql/postgresql). + db_password: Database password (for mysql/postgresql). + db_host: Database host (for mysql/postgresql). + db_port: Database port (for mysql/postgresql). + log_file: Path to the log file. + log_level: Logging level. + cpus: Number of CPUs to use. + chunk_size: Number of records to process per chunk. + force: If True, overwrite an existing database. + """ + if not json_conf.exists(): + raise FileNotFoundError(f"Configuration file not found: {json_conf}") + + log_level_choices = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] + if log_level.upper() not in log_level_choices: + raise ValueError(f"Invalid log level '{log_level}'. Choose from {log_level_choices}.") + + db_type_choices = ["sqlite", "mysql", "postgresql"] + if db_type not in db_type_choices: + raise ValueError(f"Invalid db_type '{db_type}'. Choose from {db_type_choices}.") + + cmd = [ + "mikado", "serialise", + "--json-conf", str(json_conf), + "--db-type", db_type, + "--log-level", log_level.upper(), + "--cpus", str(cpus), + "--chunk_size", str(chunk_size), + ] + + if db_type == "sqlite": + cmd.extend(["-o", str(output_file)]) + else: + if not all([db_name, db_user, db_host]): + raise ValueError("For mysql/postgresql, db_name, db_user, and db_host must be provided.") + cmd.extend(["--db-name", db_name, "--db-user", db_user, "--db-host", db_host]) + if db_password: + cmd.extend(["--db-password", db_password]) + if db_port: + cmd.extend(["--db-port", str(db_port)]) + + if blast_xml: + for xml_file in blast_xml: + if not xml_file.exists(): + raise FileNotFoundError(f"BLAST XML file not found: {xml_file}") + cmd.extend(["--xml", str(xml_file)]) + if blast_targets: + if not blast_targets.exists(): + raise FileNotFoundError(f"BLAST targets file not found: {blast_targets}") + cmd.extend(["--blast_targets", str(blast_targets)]) + if orfs: + for orf_file in orfs: + if not orf_file.exists(): + raise FileNotFoundError(f"ORF file not found: {orf_file}") + cmd.extend(["--orfs", str(orf_file)]) + if junctions: + for junc_file in junctions: + if not junc_file.exists(): + raise FileNotFoundError(f"Junctions file not found: {junc_file}") + cmd.extend(["--junctions", str(junc_file)]) + if quantification: + for quant in quantification: + if ":" not in quant or len(quant.split(":")) != 2: + raise ValueError(f"Invalid quantification format: '{quant}'. Expected 'name:path'.") + cmd.extend(["--quantification", quant]) + if log_file: + cmd.extend(["--log-file", str(log_file)]) + if force: + cmd.append("--force") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Mikado serialise failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\nStdout: {e.stdout}" + ) from e + + output_files_list = [] + if db_type == "sqlite": + output_files_list.append(str(output_file)) + if log_file: + output_files_list.append(str(log_file)) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files_list, + } + + +# @mcp.tool() +def mikado_pick( + json_conf: Path, + output_file: Path, + scoring_file: Path, + requirements_file: Path, + reference: Path, + subloci_out: Optional[Path] = None, + loci_out: Optional[Path] = None, + stats_out: Optional[Path] = None, + write_scores: Optional[Path] = None, + log_file: Optional[Path] = None, + log_level: str = "INFO", + cpus: int = 1, + seed: Optional[int] = None, + mode: str = "permissive", + max_intron: Optional[int] = None, + min_intron_len: int = 20, + max_intron_overlap: int = 10, + num_genes: Optional[int] = None, + shuffle: bool = False, + no_chimeras: bool = False, + keep_chimeras: bool = False, +): + """ + Selects the best transcript models for each locus based on scoring and requirements. + + Args: + json_conf: Path to the configuration file in JSON format. + output_file: Path for the main output GFF3 file. + scoring_file: Path to the scoring YAML file. + requirements_file: Path to the requirements YAML file. + reference: Path to the reference genome FASTA file. + subloci_out: Path to output GFF3 with subloci information. + loci_out: Path to output GFF3 with loci information. + stats_out: Path to output statistics file in JSON format. + write_scores: Path to write detailed scores to. + log_file: Path to the log file. + log_level: Logging level. + cpus: Number of CPUs to use. + seed: Random seed for reproducibility. + mode: Selection mode, 'permissive' or 'strict'. + max_intron: Maximum allowed intron size. + min_intron_len: Minimum intron length. + max_intron_overlap: Maximum overlap between introns. + num_genes: Limit the number of genes to process (for testing). + shuffle: If True, shuffle genes before processing. + no_chimeras: If True, disable chimera detection. + keep_chimeras: If True, keep chimeric transcripts in the output. + """ + if not json_conf.exists(): + raise FileNotFoundError(f"Configuration file not found: {json_conf}") + if not scoring_file.exists(): + raise FileNotFoundError(f"Scoring file not found: {scoring_file}") + if not requirements_file.exists(): + raise FileNotFoundError(f"Requirements file not found: {requirements_file}") + if not reference.exists(): + raise FileNotFoundError(f"Reference genome not found: {reference}") + + log_level_choices = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] + if log_level.upper() not in log_level_choices: + raise ValueError(f"Invalid log level '{log_level}'. Choose from {log_level_choices}.") + + mode_choices = ["permissive", "strict"] + if mode not in mode_choices: + raise ValueError(f"Invalid mode '{mode}'. Choose from {mode_choices}.") + + cmd = [ + "mikado", "pick", + "--json-conf", str(json_conf), + "-o", str(output_file), + "--scoring-file", str(scoring_file), + "--requirements-file", str(requirements_file), + "--reference", str(reference), + "--log-level", log_level.upper(), + "--cpus", str(cpus), + "--mode", mode, + "--min-intron-len", str(min_intron_len), + "--max-intron-overlap", str(max_intron_overlap), + ] + + if subloci_out: + cmd.extend(["--subloci-out", str(subloci_out)]) + if loci_out: + cmd.extend(["--loci-out", str(loci_out)]) + if stats_out: + cmd.extend(["--stats-out", str(stats_out)]) + if write_scores: + cmd.extend(["--write-scores", str(write_scores)]) + if log_file: + cmd.extend(["--log-file", str(log_file)]) + if seed is not None: + cmd.extend(["--seed", str(seed)]) + if max_intron is not None: + cmd.extend(["--max-intron", str(max_intron)]) + if num_genes is not None: + cmd.extend(["--num-genes", str(num_genes)]) + if shuffle: + cmd.append("--shuffle") + if no_chimeras: + cmd.append("--no-chimeras") + if keep_chimeras: + cmd.append("--keep-chimeras") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Mikado pick failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\nStdout: {e.stdout}" + ) from e + + output_files_paths = [output_file] + if subloci_out: + output_files_paths.append(subloci_out) + if loci_out: + output_files_paths.append(loci_out) + if stats_out: + output_files_paths.append(stats_out) + if write_scores: + output_files_paths.append(write_scores) + if log_file: + output_files_paths.append(log_file) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(p) for p in output_files_paths if p.exists()], + } + + +# @mcp.tool() +def mikado_compare( + reference: Path, + predicted: Path, + output_prefix: str, + log_file: Optional[Path] = None, + log_level: str = "INFO", + cpus: int = 1, + labels: str = "reference,predicted", + json_output: bool = False, +): + """ + Compares two annotation files (reference vs. predicted) and generates statistics. + + Args: + reference: Path to the reference annotation file (GFF3/GTF). + predicted: Path to the predicted annotation file (GFF3/GTF). + output_prefix: Prefix for output files. + log_file: Path to the log file. + log_level: Logging level. + cpus: Number of CPUs to use. + labels: Comma-separated labels for reference and prediction. + json_output: If True, output statistics in JSON format. + """ + if not reference.exists(): + raise FileNotFoundError(f"Reference annotation not found: {reference}") + if not predicted.exists(): + raise FileNotFoundError(f"Predicted annotation not found: {predicted}") + + log_level_choices = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] + if log_level.upper() not in log_level_choices: + raise ValueError(f"Invalid log level '{log_level}'. Choose from {log_level_choices}.") + + cmd = [ + "mikado", "compare", + "-r", str(reference), + "-p", str(predicted), + "-o", output_prefix, + "--log-level", log_level.upper(), + "--cpus", str(cpus), + "--labels", labels, + ] + + if log_file: + cmd.extend(["-l", str(log_file)]) + if json_output: + cmd.append("--json") + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Mikado compare failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\nStdout: {e.stdout}" + ) from e + + # Mikado compare creates several output files with the given prefix + # We can list the most common ones. + output_files_paths = [ + Path(f"{output_prefix}.stats.tsv"), + Path(f"{output_prefix}.tmap"), + Path(f"{output_prefix}.refmap"), + ] + if json_output: + output_files_paths.append(Path(f"{output_prefix}.stats.json")) + if log_file: + output_files_paths.append(log_file) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [str(p) for p in output_files_paths if p.exists()], + } + + +# @mcp.tool() +def mikado_util_blast_to_gff3( + blast_xml: Path, + output_gff3: Path, + log_file: Optional[Path] = None, + log_level: str = "INFO", +): + """ + Utility to convert BLAST XML results to GFF3 format. + + Args: + blast_xml: Path to the input BLAST XML file. + output_gff3: Path for the output GFF3 file. + log_file: Path to the log file. + log_level: Logging level. + """ + if not blast_xml.exists(): + raise FileNotFoundError(f"BLAST XML file not found: {blast_xml}") + + log_level_choices = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] + if log_level.upper() not in log_level_choices: + raise ValueError(f"Invalid log level '{log_level}'. Choose from {log_level_choices}.") + + cmd = [ + "mikado", "util", "blast-to-gff3", + str(blast_xml), + str(output_gff3), + "--log-level", log_level.upper(), + ] + if log_file: + cmd.extend(["--log-file", str(log_file)]) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Mikado util blast-to-gff3 failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\nStdout: {e.stdout}" + ) from e + + output_files_list = [str(output_gff3)] + if log_file: + output_files_list.append(str(log_file)) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files_list, + } + + +# @mcp.tool() +def mikado_util_gff_to_fasta( + input_gff: Path, + reference_fasta: Path, + output_fasta: Path, + feature: str = "transcript", + id_attribute: str = "ID", + log_file: Optional[Path] = None, + log_level: str = "INFO", +): + """ + Utility to extract sequences from a GFF file given a reference genome. + + Args: + input_gff: Path to the input GFF/GTF file. + reference_fasta: Path to the reference genome FASTA file. + output_fasta: Path for the output FASTA file. + feature: Feature type to extract (e.g., 'transcript', 'CDS'). + id_attribute: GFF attribute to use for FASTA headers. + log_file: Path to the log file. + log_level: Logging level. + """ + if not input_gff.exists(): + raise FileNotFoundError(f"Input GFF file not found: {input_gff}") + if not reference_fasta.exists(): + raise FileNotFoundError(f"Reference FASTA file not found: {reference_fasta}") + + log_level_choices = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] + if log_level.upper() not in log_level_choices: + raise ValueError(f"Invalid log level '{log_level}'. Choose from {log_level_choices}.") + + cmd = [ + "mikado", "util", "gff-to-fasta", + str(input_gff), + str(reference_fasta), + str(output_fasta), + "--feature", feature, + "--id-attribute", id_attribute, + "--log-level", log_level.upper(), + ] + if log_file: + cmd.extend(["--log-file", str(log_file)]) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Mikado util gff-to-fasta failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\nStdout: {e.stdout}" + ) from e + + output_files_list = [str(output_fasta)] + if log_file: + output_files_list.append(str(log_file)) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files_list, + } + + +# @mcp.tool() +def mikado_util_transcripts_to_gff3( + input_fasta: Path, + output_gff3: Path, + log_file: Optional[Path] = None, + log_level: str = "INFO", +): + """ + Utility to convert a transcript FASTA file to a basic GFF3 representation. + + Args: + input_fasta: Path to the input transcript FASTA file. + output_gff3: Path for the output GFF3 file. + log_file: Path to the log file. + log_level: Logging level. + """ + if not input_fasta.exists(): + raise FileNotFoundError(f"Input FASTA file not found: {input_fasta}") + + log_level_choices = ["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] + if log_level.upper() not in log_level_choices: + raise ValueError(f"Invalid log level '{log_level}'. Choose from {log_level_choices}.") + + cmd = [ + "mikado", "util", "transcripts-to-gff3", + str(input_fasta), + str(output_gff3), + "--log-level", log_level.upper(), + ] + if log_file: + cmd.extend(["--log-file", str(log_file)]) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True, + ) + except subprocess.CalledProcessError as e: + raise RuntimeError( + f"Mikado util transcripts-to-gff3 failed with exit code {e.returncode}\n" + f"Stderr: {e.stderr}\nStdout: {e.stdout}" + ) from e + + output_files_list = [str(output_gff3)] + if log_file: + output_files_list.append(str(log_file)) + + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files_list, + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mikado/app/mikado_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mikado/app/mikado_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..bc8c07ed6a554c8eee8b2a8db0ce0a5429da3c04 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mikado/app/mikado_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mikado/app/mikado_server.py') +SERVER_NAME = 'biosci_mikado' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mikado/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mikado/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mikado/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mikado/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mikado/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..f8967c46303e6f0c253991aa1ecd52cff09dab97 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mikado/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-mikado: + build: . + image: mcp-mikado:latest + container_name: mcp-mikado + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=mikado + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mikado/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mikado/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..8ad2f4c84ba049689dfc79c2c7e5f384479c35c8 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mikado/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - mikado + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mikado/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mikado/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mikado/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minced/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minced/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..92ad70879153858165c0fd526a3d1c9f2eb8d268 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minced/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install minced via conda (e.g., from bioconda) +RUN conda install -c bioconda minced -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/minced_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/minced_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/minced_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minced/app/minced_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minced/app/minced_server.py new file mode 100644 index 0000000000000000000000000000000000000000..bf911493ebab776c8049cb81c73722408e21c310 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minced/app/minced_server.py @@ -0,0 +1,122 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Dict, Any + +@mcp.tool() +def find_crisprs( + input_fasta: Path, + min_repeats: Optional[int] = None, + output_table: Optional[Path] = None, + output_gff: Optional[Path] = None, +) -> Dict[str, Any]: + """ + Finds Clustered Regularly Interspaced Short Palindromic Repeats (CRISPRs) + in full genomes or environmental datasets using MinCED. + + MinCED is a program to find CRISPRs in full genomes or environmental datasets + such as assembled contigs from metagenomes. It runs from the command-line + and was derived from CRT. + + Args: + input_fasta: Path to the input FASTA file containing sequences to search. + This file must exist and be readable. + min_repeats: Minimum number of repeats to find. This parameter is useful + for short sequences, such as 100-200 bp reads, where the + default minimum number of repeats might be too high. + If not specified, MinCED uses its internal default value. + Must be a positive integer if provided. + output_table: Optional path for the output table file. This file will + contain the detected CRISPRs in a tabular format (e.g., .txt or .crisprs). + If provided, the parent directory must exist. If not provided, + results are typically printed to standard output. + output_gff: Optional path for the output GFF (General Feature Format) file. + This file will contain the detected CRISPRs in GFF format, + suitable for genome browsers. If provided, the parent directory + must exist. As per MinCED's typical usage, this output is + expected to be specified alongside the `output_table`. + + Returns: + A dictionary containing the command executed, standard output, standard error, + and a list of paths to any generated output files. + + Raises: + ValueError: If input files do not exist, output directories do not exist, + or parameter values are invalid. + subprocess.CalledProcessError: If the MinCED command execution fails. + """ + # 1. Input validation + if not input_fasta.is_file(): + raise ValueError(f"Input FASTA file not found or is not a file: {input_fasta}") + + if min_repeats is not None: + if not isinstance(min_repeats, int) or min_repeats <= 0: + raise ValueError(f"min_repeats must be a positive integer, got {min_repeats}") + + if output_table: + if not output_table.parent.is_dir(): + raise ValueError(f"Output table directory does not exist: {output_table.parent}") + + if output_gff: + if not output_gff.parent.is_dir(): + raise ValueError(f"Output GFF directory does not exist: {output_gff.parent}") + # Enforce the observed MinCED behavior: GFF output is typically secondary + # to the table output, and specified after it. + if not output_table: + raise ValueError( + "output_gff can only be specified if output_table is also specified, " + "as per MinCED's typical usage patterns (e.g., `minced input.fa out.txt out.gff`)." + ) + + # 2. Command construction + command: List[str] = ["minced"] + + if min_repeats is not None: + command.extend(["-minNR", str(min_repeats)]) + + command.append(str(input_fasta)) + + output_files_generated: List[Path] = [] + + if output_table: + command.append(str(output_table)) + output_files_generated.append(output_table) + + if output_gff: + command.append(str(output_gff)) + output_files_generated.append(output_gff) + + # 3. Subprocess execution + process_result: subprocess.CompletedProcess + try: + process_result = subprocess.run( + command, + capture_output=True, + text=True, + check=True + ) + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(command), + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"MinCED command failed with exit code {e.returncode}: {e}", + "returncode": e.returncode, + "output_files": [] + } + except FileNotFoundError: + return { + "command_executed": " ".join(command), + "stdout": "", + "stderr": "Error: 'minced' command not found. Please ensure MinCED is installed and accessible in your PATH.", + "error": "MinCED executable not found.", + "returncode": 127, # Common return code for command not found + "output_files": [] + } + + # 4. Return structured output + return { + "command_executed": " ".join(command), + "stdout": process_result.stdout, + "stderr": process_result.stderr, + "output_files": [str(p) for p in output_files_generated] + } \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minced/app/minced_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minced/app/minced_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..362897735d03694d9eb110db21990db6a480aaed --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minced/app/minced_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minced/app/minced_server.py') +SERVER_NAME = 'biosci_minced' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minced/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minced/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minced/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minced/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minced/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e662e27b97894b6512ad1d446f132ae3d646b7a6 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minced/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-minced: + build: . + image: mcp-minced:latest + container_name: mcp-minced + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=minced + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minced/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minced/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..24b148709212713acee0ed3d53908aec8c01fe4e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minced/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - minced + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minced/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minced/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minced/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_miniasm/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_miniasm/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d30352ce436d33f4866cc0ec9cc718e88d91e6d0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_miniasm/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install miniasm via conda (e.g., from bioconda) +RUN conda install -c bioconda miniasm -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/miniasm_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/miniasm_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/miniasm_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_miniasm/app/miniasm_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_miniasm/app/miniasm_server.py new file mode 100644 index 0000000000000000000000000000000000000000..9e7badaee199ca55d5971909ef35370c90e3620d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_miniasm/app/miniasm_server.py @@ -0,0 +1,206 @@ +import subprocess +import re +from pathlib import Path +from typing import Optional, List, Literal + +# Assuming mcp is available in the execution environment +# import mcp + +class mcp: + """A mock mcp class for standalone development and testing.""" + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +@mcp.tool() +def run_miniasm( + in_paf: Path, + reads_file: Optional[Path] = None, + output_file: Optional[Path] = None, + min_reads_unitig: int = 3, + min_match_len: int = 100, + min_identity: float = 0.05, + min_span: int = 2000, + min_coverage: int = 10, + max_drop_off: int = 2000, + small_bubble_threshold: int = 4, + max_short_overlap_fraction: float = 0.8, + hpc_kmer_len: int = 10, + drop_ratio: str = "0.5,0.8", + max_gap_diff: int = 1000, + min_approx_map_identity: float = 0.8, + skip_1pass: bool = False, + skip_2pass: bool = False, + output_format: Literal["gfa", "paf"] = "gfa", + heap_sort: Literal["yes", "no"] = "no", +) -> dict: + """ + Run the miniasm de novo assembler for noisy long reads. + + miniasm is a fast OLC-based de novo assembler. It takes an all-vs-all read + self-mapping file in PAF format and outputs an assembly in GFA format. + + Args: + in_paf: Input file with overlaps in PAF format. + reads_file: Read sequences from this file. If not provided, reads are taken from in_paf. + output_file: Output assembly to this file. If not provided, output is sent to stdout. + min_reads_unitig: Minimum number of reads in a unitig. + min_match_len: Minimum match length. + min_identity: Minimum identity for an overlap. + min_span: Minimum span of an overlap. + min_coverage: Minimum coverage of a unitig. + max_drop_off: Maximum drop-off length for a unitig. + small_bubble_threshold: Threshold for small bubble detection. + max_short_overlap_fraction: Maximum fraction of short overlaps. + hpc_kmer_len: Homopolymer-compressed k-mer length. + drop_ratio: Drop shorter overlaps with this ratio to the longest (e.g., '0.5' or '0.5,0.8'). + max_gap_diff: Maximum gap differences. + min_approx_map_identity: Minimum identity for approximate mapping. + skip_1pass: Skip the 1-pass read selection. + skip_2pass: Skip the 2-pass read selection. + output_format: Output format ('gfa' or 'paf'). + heap_sort: Use introsort if 'no', or binary heap sort if 'yes'. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # Input validation + if not in_paf.is_file(): + raise FileNotFoundError(f"Input PAF file not found: {in_paf}") + if reads_file and not reads_file.is_file(): + raise FileNotFoundError(f"Reads file not found: {reads_file}") + + # Validate numeric parameters + if min_reads_unitig < 0: + raise ValueError("min_reads_unitig must be non-negative.") + if min_match_len < 0: + raise ValueError("min_match_len must be non-negative.") + if not (0.0 <= min_identity <= 1.0): + raise ValueError("min_identity must be between 0.0 and 1.0.") + if min_span < 0: + raise ValueError("min_span must be non-negative.") + if min_coverage < 0: + raise ValueError("min_coverage must be non-negative.") + if max_drop_off < 0: + raise ValueError("max_drop_off must be non-negative.") + if small_bubble_threshold < 0: + raise ValueError("small_bubble_threshold must be non-negative.") + if not (0.0 <= max_short_overlap_fraction <= 1.0): + raise ValueError("max_short_overlap_fraction must be between 0.0 and 1.0.") + if hpc_kmer_len < 0: + raise ValueError("hpc_kmer_len must be non-negative.") + if max_gap_diff < 0: + raise ValueError("max_gap_diff must be non-negative.") + if not (0.0 <= min_approx_map_identity <= 1.0): + raise ValueError("min_approx_map_identity must be between 0.0 and 1.0.") + + # Validate drop_ratio format + if not re.match(r"^\d+(\.\d+)?(,\d+(\.\d+)?)?$", drop_ratio): + raise ValueError("drop_ratio must be one or two floats separated by a comma (e.g., '0.5' or '0.5,0.8').") + + # Command construction + cmd = ["miniasm"] + + if output_file: + cmd.extend(["-o", str(output_file)]) + if reads_file: + cmd.extend(["-f", str(reads_file)]) + + # Add parameters that differ from their defaults for a cleaner command + if min_reads_unitig != 3: cmd.extend(["-n", str(min_reads_unitig)]) + if min_match_len != 100: cmd.extend(["-m", str(min_match_len)]) + if min_identity != 0.05: cmd.extend(["-i", str(min_identity)]) + if min_span != 2000: cmd.extend(["-s", str(min_span)]) + if min_coverage != 10: cmd.extend(["-c", str(min_coverage)]) + if max_drop_off != 2000: cmd.extend(["-d", str(max_drop_off)]) + if small_bubble_threshold != 4: cmd.extend(["-e", str(small_bubble_threshold)]) + if max_short_overlap_fraction != 0.8: cmd.extend(["-F", str(max_short_overlap_fraction)]) + if hpc_kmer_len != 10: cmd.extend(["-h", str(hpc_kmer_len)]) + if drop_ratio != "0.5,0.8": cmd.extend(["-r", drop_ratio]) + if max_gap_diff != 1000: cmd.extend(["-g", str(max_gap_diff)]) + if min_approx_map_identity != 0.8: cmd.extend(["-I", str(min_approx_map_identity)]) + if skip_1pass: cmd.append("-1") + if skip_2pass: cmd.append("-2") + if output_format != "gfa": cmd.extend(["-p", output_format]) + if heap_sort != "no": cmd.append(f"--heap-sort={heap_sort}") + + cmd.append(str(in_paf)) + command_executed = " ".join(cmd) + + try: + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=True + ) + + output_files = [str(output_file)] if output_file else [] + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files + } + except FileNotFoundError: + raise RuntimeError("miniasm not found. Please ensure it is installed and in your PATH.") + except subprocess.CalledProcessError as e: + # Provide a structured error message + error_message = ( + f"miniasm execution failed with exit code {e.returncode}.\n" + f"Command: {e.cmd}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + raise RuntimeError(error_message) from e + +@mcp.tool() +def miniasm_version() -> dict: + """ + Get the version of the miniasm tool. + + Returns: + A dictionary containing the command executed and the version information. + """ + cmd = ["miniasm", "--version"] + command_executed = " ".join(cmd) + + try: + # miniasm can print version to stderr and exit with non-zero code + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=False # Do not check for non-zero exit code initially + ) + + # Version info is typically in stderr + output = result.stderr.strip() if result.stderr else result.stdout.strip() + + if result.returncode != 0 and not output: + raise subprocess.CalledProcessError( + returncode=result.returncode, + cmd=cmd, + output=result.stdout, + stderr=result.stderr + ) + + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "version": output + } + except FileNotFoundError: + raise RuntimeError("miniasm not found. Please ensure it is installed and in your PATH.") + except subprocess.CalledProcessError as e: + error_message = ( + f"miniasm version check failed with exit code {e.returncode}.\n" + f"Command: {e.cmd}\n" + f"Stderr: {e.stderr}\n" + f"Stdout: {e.stdout}" + ) + raise RuntimeError(error_message) from e \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_miniasm/app/miniasm_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_miniasm/app/miniasm_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..cb5a0b3d49fa9fe5f84e82f4c6b123377286d85c --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_miniasm/app/miniasm_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_miniasm/app/miniasm_server.py') +SERVER_NAME = 'biosci_miniasm' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_miniasm/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_miniasm/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_miniasm/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_miniasm/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_miniasm/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..ee5827bc9a64a5cbd0c8c52b73ebd35005a2b12d --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_miniasm/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-miniasm: + build: . + image: mcp-miniasm:latest + container_name: mcp-miniasm + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=miniasm + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_miniasm/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_miniasm/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..d9cbeb62e4e3f8b5c0fd385bfd6ead2ca551b2a0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_miniasm/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - miniasm + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_miniasm/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_miniasm/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_miniasm/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minimap2/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minimap2/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..793f6222d68748cc27ea2c54cd23ba34849f1636 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minimap2/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install minimap2 via conda (e.g., from bioconda) +RUN conda install -c bioconda minimap2 -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/minimap2_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/minimap2_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/minimap2_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minimap2/app/minimap2_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minimap2/app/minimap2_server.py new file mode 100644 index 0000000000000000000000000000000000000000..f9d2abc58c31307b2649730a9d37d90a0b0a584e --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minimap2/app/minimap2_server.py @@ -0,0 +1,249 @@ +import subprocess +from pathlib import Path +from typing import Optional, List, Union +import tempfile + +@mcp.tool() +def minimap2_index( + target_fa: str, + output_mmi: str, + preset: Optional[str] = None, + k: Optional[int] = None, + w: Optional[int] = None, + H: bool = False, + I: Optional[str] = None, +): + """ + Indexes target sequences for faster mapping with minimap2. + + Args: + target_fa: Path to the target FASTA file. + output_mmi: Path where the index (.mmi) will be saved. + preset: Preset (e.g., map-ont, lr:hq, map-hifi, sr, etc.). Applied before other options. + k: K-mer size (no larger than 28). + w: Minimizer window size. + H: Use homopolymer-compressed k-mer (preferable for PacBio). + I: Split index for every ~NUM input bases (e.g., 8G, 4M). + """ + target_path = Path(target_fa) + if not target_path.exists(): + return {"error": f"Target file {target_fa} not found."} + + cmd = ["minimap2"] + + if preset: + cmd.extend(["-x", preset]) + if k is not None: + if k > 28: + return {"error": "k-mer size (k) cannot be larger than 28."} + cmd.extend(["-k", str(k)]) + if w is not None: + cmd.extend(["-w", str(w)]) + if H: + cmd.append("-H") + if I: + cmd.extend(["-I", I]) + + cmd.extend(["-d", output_mmi, target_fa]) + + try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True) + return { + "command_executed": " ".join(cmd), + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": [output_mmi] + } + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def minimap2_align( + target: str, + queries: List[str], + output_file: Optional[str] = None, + preset: Optional[str] = None, + sam_format: bool = False, + threads: int = 3, + k: Optional[int] = None, + w: Optional[int] = None, + H: bool = False, + I: Optional[str] = None, + f: Optional[float] = None, + g: Optional[str] = None, + G: Optional[str] = None, + F: Optional[int] = None, + r: Optional[str] = None, + n: Optional[int] = None, + m: Optional[int] = None, + X: bool = False, + p: Optional[float] = None, + N: Optional[int] = None, + A: Optional[int] = None, + B: Optional[int] = None, + O: Optional[str] = None, + E: Optional[str] = None, + z: Optional[str] = None, + s: Optional[int] = None, + u: Optional[str] = None, + J: Optional[int] = None, + L: bool = False, + R: Optional[str] = None, + write_cigar_paf: bool = False, + cs_tag: Optional[str] = None, + ds_tag: bool = False, + MD_tag: bool = False, + eqx: bool = False, + soft_clip_supplementary: bool = False, + minibatch_size: Optional[str] = None, + junc_bed: Optional[str] = None, + junc_bonus: Optional[int] = None, + secondary: bool = True, +): + """ + Performs sequence alignment using minimap2. + + Args: + target: Path to target.fa or target.idx. + queries: List of paths to query sequence files (FASTA/FASTQ). + output_file: Path to output file. If not provided, results are returned in stdout. + preset: Preset (map-ont, lr:hq, map-hifi, map-pb, map-iclr, asm5, asm10, asm20, splice, splice:hq, splice:sr, sr, ava-pb, ava-ont). + sam_format: Output in SAM format (default is PAF). + threads: Number of threads to use. + k: K-mer size (no larger than 28). + w: Minimizer window size. + H: Use homopolymer-compressed k-mer. + I: Split index for every ~NUM input bases. + f: Filter out top FLOAT fraction of repetitive minimizers. + g: Stop chain elongation if there are no minimizers in INT-bp. + G: Max intron length (effective with splice mode). + F: Max fragment length (effective with -xsr or fragment mode). + r: Chaining/alignment bandwidth and long-join bandwidth (e.g., "500,20000"). + n: Minimal number of minimizers on a chain. + m: Minimal chaining score. + X: Skip self and dual mappings (for all-vs-all mode). + p: Min secondary-to-primary score ratio. + N: Retain at most INT secondary alignments. + A: Matching score. + B: Mismatch penalty. + O: Gap open penalty (e.g., "4,24"). + E: Gap extension penalty (e.g., "2,1"). + z: Z-drop score and inversion Z-drop score (e.g., "400,200"). + s: Minimal peak DP alignment score. + u: How to find GT-AG. f:transcript strand, b:both strands, n:don't match. + J: Splice mode. 0: original, 1: miniprot. + L: Write CIGAR with >65535 ops at the CG tag. + R: SAM read group line (e.g., '@RG\\tID:foo\\tSM:bar'). + write_cigar_paf: Output CIGAR in PAF (cg tag). + cs_tag: Output the cs tag ('short' or 'long'). + ds_tag: Output the ds tag (extension to cs). + MD_tag: Output the MD tag. + eqx: Write =/X CIGAR operators. + soft_clip_supplementary: Use soft clipping for supplementary alignments. + minibatch_size: Minibatch size for mapping (e.g., 500M). + junc_bed: Gene annotations in BED12 or intron positions in 5-column BED. + junc_bonus: Score bonus for a splice donor or acceptor found in annotation. + secondary: Whether to output secondary alignments. + """ + target_path = Path(target) + if not target_path.exists(): + return {"error": f"Target file {target} not found."} + + for q in queries: + if not Path(q).exists(): + return {"error": f"Query file {q} not found."} + + cmd = ["minimap2"] + + # Preset must be applied first + if preset: + cmd.extend(["-x", preset]) + + # Indexing/Mapping Options + if k is not None: + if k > 28: return {"error": "k-mer size (k) cannot be larger than 28."} + cmd.extend(["-k", str(k)]) + if w is not None: cmd.extend(["-w", str(w)]) + if H: cmd.append("-H") + if I: cmd.extend(["-I", I]) + if f is not None: cmd.extend(["-f", str(f)]) + if g: cmd.extend(["-g", g]) + if G: cmd.extend(["-G", G]) + if F is not None: cmd.extend(["-F", str(F)]) + if r: cmd.extend(["-r", r]) + if n is not None: cmd.extend(["-n", str(n)]) + if m is not None: cmd.extend(["-m", str(m)]) + if X: cmd.append("-X") + if p is not None: cmd.extend(["-p", str(p)]) + if N is not None: cmd.extend(["-N", str(N)]) + + # Alignment Options + if A is not None: cmd.extend(["-A", str(A)]) + if B is not None: cmd.extend(["-B", str(B)]) + if O: cmd.extend(["-O", O]) + if E: cmd.extend(["-E", E]) + if z: cmd.extend(["-z", z]) + if s is not None: cmd.extend(["-s", str(s)]) + if u: cmd.extend(["-u", u]) + if J is not None: cmd.extend(["-J", str(J)]) + if junc_bed: cmd.extend(["--junc-bed", junc_bed]) + if junc_bonus is not None: cmd.extend(["--junc-bonus", str(junc_bonus)]) + + # I/O Options + if sam_format: cmd.append("-a") + if output_file: cmd.extend(["-o", output_file]) + if L: cmd.append("-L") + if R: cmd.extend(["-R", R]) + if write_cigar_paf: cmd.append("-c") + if cs_tag: + cmd.append(f"--cs={cs_tag}" if cs_tag in ["short", "long"] else "--cs") + if ds_tag: cmd.append("--ds") + if MD_tag: cmd.append("--MD") + if eqx: cmd.append("--eqx") + if soft_clip_supplementary: cmd.append("-Y") + if minibatch_size: cmd.extend(["-K", minibatch_size]) + if not secondary: cmd.append("--secondary=no") + + cmd.extend(["-t", str(threads)]) + + # Positional arguments + cmd.append(target) + cmd.extend(queries) + + try: + result = subprocess.run(cmd, check=True, capture_output=True, text=True) + + output_info = { + "command_executed": " ".join(cmd), + "stdout": result.stdout if not output_file else f"Output written to {output_file}", + "stderr": result.stderr, + } + if output_file: + output_info["output_files"] = [output_file] + + return output_info + + except subprocess.CalledProcessError as e: + return { + "command_executed": " ".join(cmd), + "error": str(e), + "stdout": e.stdout, + "stderr": e.stderr + } + +@mcp.tool() +def minimap2_get_version(): + """Returns the version of minimap2 installed.""" + try: + result = subprocess.run(["minimap2", "--version"], check=True, capture_output=True, text=True) + return { + "version": result.stdout.strip(), + "stderr": result.stderr + } + except subprocess.CalledProcessError as e: + return {"error": str(e), "stderr": e.stderr} \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minimap2/app/minimap2_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minimap2/app/minimap2_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0ed3d19bf03af202ef35ed698c60b88b8eb816ba --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minimap2/app/minimap2_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minimap2/app/minimap2_server.py') +SERVER_NAME = 'biosci_minimap2' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minimap2/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minimap2/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minimap2/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minimap2/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minimap2/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..cb3d2d3316d8323d63147ca1248b6fea882ad58b --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minimap2/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-minimap2: + build: . + image: mcp-minimap2:latest + container_name: mcp-minimap2 + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=minimap2 + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minimap2/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minimap2/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..154d9e7c7a9e6be3f612a2d2bd8a20950f903714 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minimap2/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - minimap2 + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minimap2/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minimap2/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minimap2/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minvar/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minvar/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..91036ed5d946a5b5dc6654e450800f020784b222 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minvar/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install minvar via conda (e.g., from bioconda) +RUN conda install -c bioconda minvar -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/minvar_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/minvar_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/minvar_server.py"] + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minvar/app/minvar_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minvar/app/minvar_server.py new file mode 100644 index 0000000000000000000000000000000000000000..0c71b94eb9921b320b45cf66f36f4ce66bff3fec --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minvar/app/minvar_server.py @@ -0,0 +1,139 @@ +import subprocess +import shlex +from pathlib import Path +from typing import Optional, List + +# This is a placeholder for the MCP decorator. +# In a real MCP environment, 'mcp' would be imported. +class mcp: + @staticmethod + def tool(): + def decorator(func): + return func + return decorator + +@mcp.tool() +def minvar( + reference_fasta: Path, + reads_bam: Path, + output_vcf: Optional[Path] = None, + min_depth: int = 10, + min_qual: int = 20, + min_mapping_qual: int = 10, + min_freq: float = 0.01, + ploidy: int = 2, + perform_indel_calling: bool = False, + threads: int = 1, + max_records_in_ram: int = 100000, + lenient_validation: bool = False, + validation_stringency: str = "STRICT", +) -> dict: + """ + Runs minvar, a simple, fast variant caller for targeted sequencing data. + + Args: + reference_fasta: The reference FASTA file. + reads_bam: The input BAM file. + output_vcf: The path to the output VCF file. If not provided, output is written to standard out. + min_depth: The minimum depth to consider a position (default: 10). + min_qual: The minimum base quality to consider a read base (default: 20). + min_mapping_qual: The minimum mapping quality to consider a read (default: 10). + min_freq: The minimum frequency to call a variant (default: 0.01). + ploidy: The ploidy of the organism (default: 2). + perform_indel_calling: If True, indels will be called. + threads: The number of threads to use (default: 1). + max_records_in_ram: The maximum number of BAM records to hold in RAM. + lenient_validation: If True, SAM/BAM validation will be lenient. + validation_stringency: Set the SAM/BAM validation stringency. Can be STRICT, LENIENT, or SILENT. + + Returns: + A dictionary containing the command executed, stdout, stderr, and a list of output files. + """ + # 1. Input validation + if not reference_fasta.is_file(): + raise FileNotFoundError(f"Reference FASTA file not found: {reference_fasta}") + if not reads_bam.is_file(): + raise FileNotFoundError(f"Input BAM file not found: {reads_bam}") + + if output_vcf and not output_vcf.parent.exists(): + raise NotADirectoryError(f"Parent directory for output VCF does not exist: {output_vcf.parent}") + + if min_depth < 0: + raise ValueError("min_depth must be a non-negative integer.") + if min_qual < 0: + raise ValueError("min_qual must be a non-negative integer.") + if min_mapping_qual < 0: + raise ValueError("min_mapping_qual must be a non-negative integer.") + if not (0.0 <= min_freq <= 1.0): + raise ValueError("min_freq must be a float between 0.0 and 1.0.") + if ploidy <= 0: + raise ValueError("ploidy must be a positive integer.") + if threads <= 0: + raise ValueError("threads must be a positive integer.") + if max_records_in_ram <= 0: + raise ValueError("max_records_in_ram must be a positive integer.") + + allowed_stringencies = ["STRICT", "LENIENT", "SILENT"] + if validation_stringency not in allowed_stringencies: + raise ValueError(f"validation_stringency must be one of {allowed_stringencies}, but got '{validation_stringency}'") + + # 2. Command construction + cmd = ["minvar"] + + if output_vcf: + cmd.extend(["-o", str(output_vcf)]) + + cmd.extend(["-d", str(min_depth)]) + cmd.extend(["-q", str(min_qual)]) + cmd.extend(["-m", str(min_mapping_qual)]) + cmd.extend(["-f", str(min_freq)]) + cmd.extend(["-p", str(ploidy)]) + cmd.extend(["-t", str(threads)]) + cmd.extend(["--maxRecordsInRam", str(max_records_in_ram)]) + cmd.extend(["--validationStringency", validation_stringency]) + + if perform_indel_calling: + cmd.append("-i") + if lenient_validation: + cmd.append("--lenientValidation") + + # Positional arguments + cmd.append(str(reference_fasta)) + cmd.append(str(reads_bam)) + + command_executed = shlex.join(cmd) + + # 3. Subprocess execution and error handling + try: + result = subprocess.run( + cmd, + check=True, + capture_output=True, + text=True, + ) + + output_files = [str(output_vcf)] if output_vcf else [] + + # 4. Structured result return + return { + "command_executed": command_executed, + "stdout": result.stdout, + "stderr": result.stderr, + "output_files": output_files, + } + except FileNotFoundError: + return { + "command_executed": command_executed, + "stdout": "", + "stderr": "Error: 'minvar' command not found. Please ensure it is installed and in your PATH.", + "error": "Executable not found", + "output_files": [], + } + except subprocess.CalledProcessError as e: + return { + "command_executed": command_executed, + "stdout": e.stdout, + "stderr": e.stderr, + "error": f"minvar failed with exit code {e.returncode}", + "output_files": [], + } diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minvar/app/minvar_shim_server.py b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minvar/app/minvar_shim_server.py new file mode 100644 index 0000000000000000000000000000000000000000..dc28878aeb28a844ea44edbe36151ef534f5d720 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minvar/app/minvar_shim_server.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3 +from __future__ import annotations + +import ast +from pathlib import Path + +from mcp.server.fastmcp import FastMCP + + +SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minvar/app/minvar_server.py') +SERVER_NAME = 'biosci_minvar' + + +class _ShimMCP: + @staticmethod + def tool(): + def _decorator(fn): + return fn + return _decorator + + +def _load_functions(): + code = SOURCE_SERVER.read_text(encoding="utf-8") + tree = ast.parse(code, filename=str(SOURCE_SERVER)) + function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")] + namespace = { + "__name__": "__mcp_source__", + "mcp": _ShimMCP(), + } + exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace) + loaded = [] + for name in function_names: + fn = namespace.get(name) + if callable(fn): + loaded.append(fn) + return loaded + + +mcp = FastMCP(SERVER_NAME) +for _fn in _load_functions(): + mcp.tool()(_fn) + + +if __name__ == "__main__": + mcp.run(transport="stdio") diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minvar/app/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minvar/app/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minvar/app/requirements.txt @@ -0,0 +1 @@ + diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minvar/docker-compose.yml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minvar/docker-compose.yml new file mode 100644 index 0000000000000000000000000000000000000000..e93ae37754114a6374be3bf9c29703f268a21eb1 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minvar/docker-compose.yml @@ -0,0 +1,22 @@ +version: '3.8' + +services: + mcp-minvar: + build: . + image: mcp-minvar:latest + container_name: mcp-minvar + ports: + - "8000:8000" + environment: + - MCP_SERVER_NAME=minvar + volumes: + - ./workspace:/app/workspace + - ./output:/app/output + restart: unless-stopped + healthcheck: + test: ["CMD", "python", "-c", "import sys; sys.exit(0)"] + interval: 30s + timeout: 10s + retries: 3 + start_period: 5s + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minvar/environment.yaml b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minvar/environment.yaml new file mode 100644 index 0000000000000000000000000000000000000000..f08c778abc067dbfec8826717a83732771547246 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minvar/environment.yaml @@ -0,0 +1,10 @@ + +name: mcp-tool +channels: + - bioconda + - conda-forge + - defaults +dependencies: + - minvar + - python=3.10 + \ No newline at end of file diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minvar/requirements.txt b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minvar/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc4702c254694b94825ae9800a56d8f68b1bcda0 --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_minvar/requirements.txt @@ -0,0 +1,2 @@ +fastmcp +mcp diff --git a/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mitos/Dockerfile b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mitos/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5e66302babb1ba9a1ae1b93695f0113e30b9ecdf --- /dev/null +++ b/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_mitos/Dockerfile @@ -0,0 +1,40 @@ + +FROM python:3.10-slim + +# Install system dependencies +RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/* + +# Install Miniconda +RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh + +# Add conda to PATH +ENV PATH="/opt/conda/bin:$PATH" + +# Install mitos via conda (e.g., from bioconda) +RUN conda install -c bioconda mitos -y && conda clean -a + +# Install Python dependencies +RUN pip install uv +RUN uv pip install --system fastmcp + +# Create app directory +WORKDIR /app + +# Copy your MCP server +COPY app/mitos_server.py /app/ + +# Create workspace and output directories +RUN mkdir -p /app/workspace /app/output + +# Make sure the server script is executable +RUN chmod +x /app/mitos_server.py + +# Expose port for MCP over HTTP (optional) +EXPOSE 8000 + +# Health check +HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)" + +# Default command runs the MCP server via stdio +CMD ["python", "/app/mitos_server.py"] + \ No newline at end of file