czty commited on
Commit
be345b4
·
verified ·
1 Parent(s): 7ee22cb

BioOcto code and data release (snapshot 2026-11-27) (part 9)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gdk-pixbuf/docker-compose.yml +22 -0
  2. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gdk-pixbuf/environment.yaml +10 -0
  3. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gdk-pixbuf/requirements.txt +2 -0
  4. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/Dockerfile +40 -0
  5. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/app/gecode_server.py +136 -0
  6. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/app/gecode_shim_server.py +45 -0
  7. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/app/requirements.txt +1 -0
  8. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/docker-compose.yml +22 -0
  9. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/environment.yaml +10 -0
  10. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/requirements.txt +2 -0
  11. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gemini/requirements.txt +2 -0
  12. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/Dockerfile +40 -0
  13. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/app/gene-trajectory-python_server.py +207 -0
  14. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/app/gene-trajectory-python_shim_server.py +45 -0
  15. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/app/requirements.txt +1 -0
  16. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/docker-compose.yml +22 -0
  17. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/environment.yaml +10 -0
  18. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/requirements.txt +2 -0
  19. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/Dockerfile +40 -0
  20. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/app/genecircuitry_server.py +149 -0
  21. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/app/genecircuitry_shim_server.py +45 -0
  22. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/app/requirements.txt +1 -0
  23. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/docker-compose.yml +22 -0
  24. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/environment.yaml +10 -0
  25. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/requirements.txt +2 -0
  26. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/Dockerfile +40 -0
  27. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/app/geneimpacts_server.py +216 -0
  28. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/app/geneimpacts_shim_server.py +45 -0
  29. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/app/requirements.txt +1 -0
  30. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/docker-compose.yml +22 -0
  31. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/environment.yaml +10 -0
  32. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/requirements.txt +2 -0
  33. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genenotebook/requirements.txt +2 -0
  34. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/Dockerfile +40 -0
  35. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/app/genoboo_server.py +200 -0
  36. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/app/genoboo_shim_server.py +45 -0
  37. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/app/requirements.txt +1 -0
  38. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/docker-compose.yml +22 -0
  39. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/environment.yaml +10 -0
  40. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/requirements.txt +2 -0
  41. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomad/requirements.txt +2 -0
  42. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/Dockerfile +40 -0
  43. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/app/genomepy_server.py +346 -0
  44. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/app/genomepy_shim_server.py +45 -0
  45. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/app/requirements.txt +1 -0
  46. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/docker-compose.yml +22 -0
  47. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/environment.yaml +10 -0
  48. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/requirements.txt +2 -0
  49. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genometools-genometools/Dockerfile +40 -0
  50. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genometools-genometools/app/genometools-genometools_server.py +626 -0
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gdk-pixbuf/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-gdk-pixbuf:
5
+ build: .
6
+ image: mcp-gdk-pixbuf:latest
7
+ container_name: mcp-gdk-pixbuf
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=gdk-pixbuf
12
+ volumes:
13
+ - ./workspace:/app/workspace
14
+ - ./output:/app/output
15
+ restart: unless-stopped
16
+ healthcheck:
17
+ test: ["CMD", "python", "-c", "import sys; sys.exit(0)"]
18
+ interval: 30s
19
+ timeout: 10s
20
+ retries: 3
21
+ start_period: 5s
22
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gdk-pixbuf/environment.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ name: mcp-tool
3
+ channels:
4
+ - bioconda
5
+ - conda-forge
6
+ - defaults
7
+ dependencies:
8
+ - gdk-pixbuf
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gdk-pixbuf/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/Dockerfile ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ FROM python:3.10-slim
3
+
4
+ # Install system dependencies
5
+ RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/*
6
+
7
+ # Install Miniconda
8
+ RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh
9
+
10
+ # Add conda to PATH
11
+ ENV PATH="/opt/conda/bin:$PATH"
12
+
13
+ # Install gecode via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda gecode -y && conda clean -a
15
+
16
+ # Install Python dependencies
17
+ RUN pip install uv
18
+ RUN uv pip install --system fastmcp
19
+
20
+ # Create app directory
21
+ WORKDIR /app
22
+
23
+ # Copy your MCP server
24
+ COPY app/gecode_server.py /app/
25
+
26
+ # Create workspace and output directories
27
+ RUN mkdir -p /app/workspace /app/output
28
+
29
+ # Make sure the server script is executable
30
+ RUN chmod +x /app/gecode_server.py
31
+
32
+ # Expose port for MCP over HTTP (optional)
33
+ EXPOSE 8000
34
+
35
+ # Health check
36
+ HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)"
37
+
38
+ # Default command runs the MCP server via stdio
39
+ CMD ["python", "/app/gecode_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/app/gecode_server.py ADDED
@@ -0,0 +1,136 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ from pathlib import Path
3
+ from typing import Optional, List, Dict, Any
4
+
5
+ @mcp.tool()
6
+ def fzn_gecode(
7
+ fzn_file: str,
8
+ all_solutions: bool = False,
9
+ num_solutions: int = 1,
10
+ parallel: int = 1,
11
+ time_limit: int = 0,
12
+ statistics: bool = False,
13
+ free_search: bool = False,
14
+ seed: int = 0,
15
+ output_file: Optional[str] = None,
16
+ ) -> Dict[str, Any]:
17
+ """
18
+ Execute the Gecode FlatZinc interpreter to solve constraint problems.
19
+
20
+ Args:
21
+ fzn_file: Path to the FlatZinc (.fzn) input file.
22
+ all_solutions: Search for all solutions (overrides num_solutions).
23
+ num_solutions: Number of solutions to search for (default 1, use 0 for all).
24
+ parallel: Number of threads to use for parallel search (default 1).
25
+ time_limit: Time limit in milliseconds (0 for no limit).
26
+ statistics: Print solver statistics after execution.
27
+ free_search: Use free search (ignore search annotations in the FZN file).
28
+ seed: Random seed for the solver.
29
+ output_file: Redirect solver output to a specific file.
30
+ """
31
+ # Input validation
32
+ fzn_path = Path(fzn_file)
33
+ if not fzn_path.exists():
34
+ return {
35
+ "error": f"Input FlatZinc file not found: {fzn_file}",
36
+ "command_executed": ""
37
+ }
38
+
39
+ if not fzn_path.suffix == ".fzn":
40
+ # Warning: Gecode expects .fzn files, but we proceed as the user might have renamed it
41
+ pass
42
+
43
+ # Construct command
44
+ cmd = ["fzn-gecode"]
45
+
46
+ # Handle solution count
47
+ if all_solutions:
48
+ cmd.append("-a")
49
+ elif num_solutions != 1:
50
+ if num_solutions < 0:
51
+ return {"error": "num_solutions must be non-negative", "command_executed": ""}
52
+ cmd.extend(["-n", str(num_solutions)])
53
+
54
+ # Parallelism
55
+ if parallel < 1:
56
+ return {"error": "parallel threads must be at least 1", "command_executed": ""}
57
+ cmd.extend(["-p", str(parallel)])
58
+
59
+ # Time limit
60
+ if time_limit > 0:
61
+ cmd.extend(["-t", str(time_limit)])
62
+ elif time_limit < 0:
63
+ return {"error": "time_limit must be non-negative", "command_executed": ""}
64
+
65
+ # Boolean flags
66
+ if statistics:
67
+ cmd.append("-s")
68
+ if free_search:
69
+ cmd.append("-f")
70
+
71
+ # Seed
72
+ if seed != 0:
73
+ cmd.extend(["-r", str(seed)])
74
+
75
+ # Output file
76
+ if output_file:
77
+ cmd.extend(["-o", output_file])
78
+
79
+ # Positional argument
80
+ cmd.append(str(fzn_path))
81
+
82
+ try:
83
+ # Execute the solver
84
+ process = subprocess.run(
85
+ cmd,
86
+ capture_output=True,
87
+ text=True,
88
+ check=True
89
+ )
90
+
91
+ return {
92
+ "command_executed": " ".join(cmd),
93
+ "stdout": process.stdout,
94
+ "stderr": process.stderr,
95
+ "output_files": [output_file] if output_file else []
96
+ }
97
+
98
+ except subprocess.CalledProcessError as e:
99
+ return {
100
+ "error": f"Gecode execution failed with exit code {e.returncode}",
101
+ "command_executed": " ".join(cmd),
102
+ "stdout": e.stdout,
103
+ "stderr": e.stderr
104
+ }
105
+ except FileNotFoundError:
106
+ return {
107
+ "error": "fzn-gecode binary not found. Ensure Gecode is installed and in your PATH.",
108
+ "command_executed": " ".join(cmd)
109
+ }
110
+
111
+ @mcp.tool()
112
+ def gecode_version() -> Dict[str, Any]:
113
+ """
114
+ Check the installed version of Gecode via fzn-gecode.
115
+ """
116
+ cmd = ["fzn-gecode", "--help"] # fzn-gecode usually prints version in help or doesn't have a --version flag
117
+
118
+ try:
119
+ process = subprocess.run(
120
+ cmd,
121
+ capture_output=True,
122
+ text=True,
123
+ check=False # Help might return non-zero in some versions
124
+ )
125
+
126
+ # Extract version if possible, otherwise return full help text
127
+ return {
128
+ "command_executed": " ".join(cmd),
129
+ "stdout": process.stdout,
130
+ "stderr": process.stderr
131
+ }
132
+ except Exception as e:
133
+ return {
134
+ "error": str(e),
135
+ "command_executed": " ".join(cmd)
136
+ }
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/app/gecode_shim_server.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/app/gecode_server.py')
11
+ SERVER_NAME = 'biosci_gecode'
12
+
13
+
14
+ class _ShimMCP:
15
+ @staticmethod
16
+ def tool():
17
+ def _decorator(fn):
18
+ return fn
19
+ return _decorator
20
+
21
+
22
+ def _load_functions():
23
+ code = SOURCE_SERVER.read_text(encoding="utf-8")
24
+ tree = ast.parse(code, filename=str(SOURCE_SERVER))
25
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
26
+ namespace = {
27
+ "__name__": "__mcp_source__",
28
+ "mcp": _ShimMCP(),
29
+ }
30
+ exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace)
31
+ loaded = []
32
+ for name in function_names:
33
+ fn = namespace.get(name)
34
+ if callable(fn):
35
+ loaded.append(fn)
36
+ return loaded
37
+
38
+
39
+ mcp = FastMCP(SERVER_NAME)
40
+ for _fn in _load_functions():
41
+ mcp.tool()(_fn)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ mcp.run(transport="stdio")
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-gecode:
5
+ build: .
6
+ image: mcp-gecode:latest
7
+ container_name: mcp-gecode
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=gecode
12
+ volumes:
13
+ - ./workspace:/app/workspace
14
+ - ./output:/app/output
15
+ restart: unless-stopped
16
+ healthcheck:
17
+ test: ["CMD", "python", "-c", "import sys; sys.exit(0)"]
18
+ interval: 30s
19
+ timeout: 10s
20
+ retries: 3
21
+ start_period: 5s
22
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/environment.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ name: mcp-tool
3
+ channels:
4
+ - bioconda
5
+ - conda-forge
6
+ - defaults
7
+ dependencies:
8
+ - gecode
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gecode/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gemini/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/Dockerfile ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ FROM python:3.10-slim
3
+
4
+ # Install system dependencies
5
+ RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/*
6
+
7
+ # Install Miniconda
8
+ RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh
9
+
10
+ # Add conda to PATH
11
+ ENV PATH="/opt/conda/bin:$PATH"
12
+
13
+ # Install gene-trajectory-python via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda gene-trajectory-python -y && conda clean -a
15
+
16
+ # Install Python dependencies
17
+ RUN pip install uv
18
+ RUN uv pip install --system fastmcp
19
+
20
+ # Create app directory
21
+ WORKDIR /app
22
+
23
+ # Copy your MCP server
24
+ COPY app/gene-trajectory-python_server.py /app/
25
+
26
+ # Create workspace and output directories
27
+ RUN mkdir -p /app/workspace /app/output
28
+
29
+ # Make sure the server script is executable
30
+ RUN chmod +x /app/gene-trajectory-python_server.py
31
+
32
+ # Expose port for MCP over HTTP (optional)
33
+ EXPOSE 8000
34
+
35
+ # Health check
36
+ HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)"
37
+
38
+ # Default command runs the MCP server via stdio
39
+ CMD ["python", "/app/gene-trajectory-python_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/app/gene-trajectory-python_server.py ADDED
@@ -0,0 +1,207 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import tempfile
3
+ import sys
4
+ from pathlib import Path
5
+ from typing import Optional, Dict, List
6
+
7
+ # MCP-related imports are intentionally omitted as per the instructions.
8
+ # from mcp import tool
9
+
10
+ # @mcp.tool()
11
+ def run_gene_trajectory(
12
+ adata_path: Path,
13
+ output_adata_path: Path,
14
+ obsm_key: str = 'X_pca',
15
+ n_variable_genes: int = 2000,
16
+ layer: Optional[str] = None,
17
+ n_components: int = 50,
18
+ n_neighbors: int = 15,
19
+ use_highly_variable: bool = True,
20
+ resolution: float = 1.0,
21
+ n_clusters: Optional[int] = None,
22
+ n_groups: int = 100,
23
+ n_pcs: int = 50,
24
+ n_diff_maps: int = 15,
25
+ t: int = 1,
26
+ random_state: int = 0,
27
+ output_trajectory_plot: Optional[Path] = None,
28
+ trajectory_plot_basis: str = 'X_diffmap_eval',
29
+ output_heatmap_plot: Optional[Path] = None,
30
+ heatmap_plot_n_genes: int = 10,
31
+ output_feature_plot: Optional[Path] = None,
32
+ feature_plot_basis: str = 'X_umap',
33
+ ) -> Dict:
34
+ """
35
+ Runs the full GeneTrajectory pipeline on a single-cell dataset.
36
+
37
+ This tool identifies trajectories of genes rather than cells by calculating
38
+ optimal transport distances between gene distributions across the cell-cell graph.
39
+ It takes an AnnData object as input, performs the analysis, and saves the
40
+ updated AnnData object with trajectory information. Optional plots can also be generated.
41
+
42
+ Args:
43
+ adata_path: Path to the input AnnData file (`.h5ad`).
44
+ output_adata_path: Path to save the output AnnData file (`.h5ad`) with results.
45
+ obsm_key: Key in `adata.obsm` for the PCA representation.
46
+ n_variable_genes: Number of highly variable genes to use.
47
+ layer: The layer in `adata` to use for computation. If None, `adata.X` is used.
48
+ n_components: Number of principal components to compute if `obsm_key` is not present.
49
+ n_neighbors: Number of neighbors for the cell-cell graph.
50
+ use_highly_variable: Whether to use highly variable genes.
51
+ resolution: Resolution for Leiden clustering.
52
+ n_clusters: Number of clusters for K-means in coarse-graining. If None, it's determined automatically.
53
+ n_groups: Number of groups for coarse-graining.
54
+ n_pcs: Number of principal components for the diffusion map.
55
+ n_diff_maps: Number of diffusion maps to compute.
56
+ t: Time step for the diffusion map.
57
+ random_state: Random state for reproducibility.
58
+ output_trajectory_plot: Optional path to save the gene trajectory plot as a PNG file.
59
+ trajectory_plot_basis: Basis to use for the trajectory plot (e.g., 'X_diffmap_eval').
60
+ output_heatmap_plot: Optional path to save the gene program heatmap as a PNG file.
61
+ heatmap_plot_n_genes: Number of genes to display in the heatmap for each program.
62
+ output_feature_plot: Optional path to save the gene program feature plot as a PNG file.
63
+ feature_plot_basis: Basis to use for the feature plot (e.g., 'X_umap').
64
+
65
+ Returns:
66
+ A dictionary containing the executed command, stdout, stderr, and a
67
+ dictionary of output file paths.
68
+ """
69
+ # 1. Input validation
70
+ if not adata_path.is_file():
71
+ raise FileNotFoundError(f"Input AnnData file not found: {adata_path}")
72
+ if n_variable_genes <= 0:
73
+ raise ValueError("n_variable_genes must be a positive integer.")
74
+ if n_components <= 0:
75
+ raise ValueError("n_components must be a positive integer.")
76
+ if n_neighbors <= 0:
77
+ raise ValueError("n_neighbors must be a positive integer.")
78
+ if resolution <= 0:
79
+ raise ValueError("resolution must be a positive float.")
80
+ if n_groups <= 0:
81
+ raise ValueError("n_groups must be a positive integer.")
82
+ if n_pcs <= 0:
83
+ raise ValueError("n_pcs must be a positive integer.")
84
+ if n_diff_maps <= 0:
85
+ raise ValueError("n_diff_maps must be a positive integer.")
86
+ if t <= 0:
87
+ raise ValueError("t must be a positive integer.")
88
+
89
+ with tempfile.TemporaryDirectory() as temp_dir_str:
90
+ temp_dir = Path(temp_dir_str)
91
+ script_path = temp_dir / "run_gene_trajectory_script.py"
92
+
93
+ # 2. Generate the Python script to execute the library's functions
94
+ # This approach isolates the execution and dependencies from the MCP server.
95
+ script_content = f"""
96
+ import sys
97
+ import warnings
98
+ import anndata as ad
99
+ import gene_trajectory as gt
100
+ import matplotlib.pyplot as plt
101
+
102
+ # Suppress common warnings from underlying libraries for cleaner output
103
+ warnings.filterwarnings("ignore", category=UserWarning, module='scanpy')
104
+ warnings.filterwarnings("ignore", category=FutureWarning)
105
+
106
+ try:
107
+ # Load input data
108
+ adata = ad.read_h5ad(r'{adata_path.resolve()}')
109
+
110
+ # Instantiate the GeneTrajectory model
111
+ model = gt.GeneTrajectory()
112
+
113
+ # Run the full pipeline
114
+ adata_result = model.run(
115
+ adata,
116
+ obsm_key='{obsm_key}',
117
+ n_variable_genes={n_variable_genes},
118
+ layer={repr(layer)},
119
+ n_components={n_components},
120
+ n_neighbors={n_neighbors},
121
+ use_highly_variable={use_highly_variable},
122
+ resolution={resolution},
123
+ n_clusters={repr(n_clusters)},
124
+ n_groups={n_groups},
125
+ n_pcs={n_pcs},
126
+ n_diff_maps={n_diff_maps},
127
+ t={t},
128
+ random_state={random_state},
129
+ copy=True
130
+ )
131
+
132
+ # Save the resulting AnnData object
133
+ adata_result.write_h5ad(r'{output_adata_path.resolve()}')
134
+
135
+ # Generate and save optional plots
136
+ if {output_trajectory_plot is not None}:
137
+ output_traj_plot_path = r'{str(output_trajectory_plot.resolve()) if output_trajectory_plot else ""}'
138
+ fig, ax = plt.subplots(figsize=(6, 6))
139
+ model.plot_trajectory(basis='{trajectory_plot_basis}', ax=ax)
140
+ fig.savefig(output_traj_plot_path, bbox_inches='tight', dpi=300)
141
+ plt.close(fig)
142
+
143
+ if {output_heatmap_plot is not None}:
144
+ output_heatmap_plot_path = r'{str(output_heatmap_plot.resolve()) if output_heatmap_plot else ""}'
145
+ # plot_program_heatmap returns a seaborn ClusterGrid object
146
+ grid = model.plot_program_heatmap(n_genes={heatmap_plot_n_genes})
147
+ grid.savefig(output_heatmap_plot_path, bbox_inches='tight', dpi=300)
148
+ plt.close()
149
+
150
+ if {output_feature_plot is not None}:
151
+ output_feature_plot_path = r'{str(output_feature_plot.resolve()) if output_feature_plot else ""}'
152
+ # Check if the required basis exists in the AnnData object
153
+ if '{feature_plot_basis}' not in adata_result.obsm:
154
+ print(
155
+ f"Warning: Basis '{feature_plot_basis}' not found in adata.obsm. Skipping feature plot.",
156
+ file=sys.stderr
157
+ )
158
+ else:
159
+ fig, ax = plt.subplots(figsize=(6, 6))
160
+ model.plot_program_feature(basis='{feature_plot_basis}', ax=ax)
161
+ fig.savefig(output_feature_plot_path, bbox_inches='tight', dpi=300)
162
+ plt.close(fig)
163
+
164
+ except Exception as e:
165
+ print(f"An error occurred during GeneTrajectory execution: {{e}}", file=sys.stderr)
166
+ sys.exit(1)
167
+
168
+ print("GeneTrajectory analysis completed successfully.")
169
+ """
170
+ script_path.write_text(script_content)
171
+
172
+ # 3. Execute the script in a subprocess
173
+ command = [sys.executable, str(script_path)]
174
+ command_str = " ".join(command)
175
+
176
+ try:
177
+ result = subprocess.run(
178
+ command,
179
+ capture_output=True,
180
+ text=True,
181
+ check=True,
182
+ cwd=temp_dir,
183
+ )
184
+ except subprocess.CalledProcessError as e:
185
+ print(f"Error executing GeneTrajectory script.")
186
+ print(f"Return Code: {e.returncode}")
187
+ print(f"Stdout: {e.stdout}")
188
+ print(f"Stderr: {e.stderr}")
189
+ raise
190
+
191
+ # 4. Collect output file paths for the structured result
192
+ output_files = {"processed_adata": str(output_adata_path)}
193
+ if output_trajectory_plot:
194
+ output_files["trajectory_plot"] = str(output_trajectory_plot)
195
+ if output_heatmap_plot:
196
+ output_files["heatmap_plot"] = str(output_heatmap_plot)
197
+ if output_feature_plot:
198
+ # Only report the file if it was actually created
199
+ if output_feature_plot.exists():
200
+ output_files["feature_plot"] = str(output_feature_plot)
201
+
202
+ return {
203
+ "command_executed": command_str,
204
+ "stdout": result.stdout,
205
+ "stderr": result.stderr,
206
+ "output_files": output_files,
207
+ }
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/app/gene-trajectory-python_shim_server.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/app/gene-trajectory-python_server.py')
11
+ SERVER_NAME = 'biosci_gene_trajectory_python'
12
+
13
+
14
+ class _ShimMCP:
15
+ @staticmethod
16
+ def tool():
17
+ def _decorator(fn):
18
+ return fn
19
+ return _decorator
20
+
21
+
22
+ def _load_functions():
23
+ code = SOURCE_SERVER.read_text(encoding="utf-8")
24
+ tree = ast.parse(code, filename=str(SOURCE_SERVER))
25
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
26
+ namespace = {
27
+ "__name__": "__mcp_source__",
28
+ "mcp": _ShimMCP(),
29
+ }
30
+ exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace)
31
+ loaded = []
32
+ for name in function_names:
33
+ fn = namespace.get(name)
34
+ if callable(fn):
35
+ loaded.append(fn)
36
+ return loaded
37
+
38
+
39
+ mcp = FastMCP(SERVER_NAME)
40
+ for _fn in _load_functions():
41
+ mcp.tool()(_fn)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ mcp.run(transport="stdio")
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-gene-trajectory-python:
5
+ build: .
6
+ image: mcp-gene-trajectory-python:latest
7
+ container_name: mcp-gene-trajectory-python
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=gene-trajectory-python
12
+ volumes:
13
+ - ./workspace:/app/workspace
14
+ - ./output:/app/output
15
+ restart: unless-stopped
16
+ healthcheck:
17
+ test: ["CMD", "python", "-c", "import sys; sys.exit(0)"]
18
+ interval: 30s
19
+ timeout: 10s
20
+ retries: 3
21
+ start_period: 5s
22
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/environment.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ name: mcp-tool
3
+ channels:
4
+ - bioconda
5
+ - conda-forge
6
+ - defaults
7
+ dependencies:
8
+ - gene-trajectory-python
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_gene-trajectory-python/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/Dockerfile ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ FROM python:3.10-slim
3
+
4
+ # Install system dependencies
5
+ RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/*
6
+
7
+ # Install Miniconda
8
+ RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh
9
+
10
+ # Add conda to PATH
11
+ ENV PATH="/opt/conda/bin:$PATH"
12
+
13
+ # Install genecircuitry via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda genecircuitry -y && conda clean -a
15
+
16
+ # Install Python dependencies
17
+ RUN pip install uv
18
+ RUN uv pip install --system fastmcp
19
+
20
+ # Create app directory
21
+ WORKDIR /app
22
+
23
+ # Copy your MCP server
24
+ COPY app/genecircuitry_server.py /app/
25
+
26
+ # Create workspace and output directories
27
+ RUN mkdir -p /app/workspace /app/output
28
+
29
+ # Make sure the server script is executable
30
+ RUN chmod +x /app/genecircuitry_server.py
31
+
32
+ # Expose port for MCP over HTTP (optional)
33
+ EXPOSE 8000
34
+
35
+ # Health check
36
+ HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)"
37
+
38
+ # Default command runs the MCP server via stdio
39
+ CMD ["python", "/app/genecircuitry_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/app/genecircuitry_server.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import tempfile
3
+ from pathlib import Path
4
+ from typing import List, Optional
5
+
6
+ # This is a placeholder for the MCP decorator.
7
+ # In a real MCP environment, this would be provided by the MCP framework.
8
+ def tool(func):
9
+ def wrapper(*args, **kwargs):
10
+ return func(*args, **kwargs)
11
+ return wrapper
12
+
13
+ mcp = type("mcp", (), {"tool": tool})
14
+
15
+ @mcp.tool
16
+ def run_pipeline(
17
+ input_file: Path,
18
+ output_dir: Path,
19
+ steps: Optional[List[str]] = None,
20
+ skip_celloracle: bool = False,
21
+ skip_hotspot: bool = False,
22
+ seed: Optional[int] = None,
23
+ n_jobs: int = 1,
24
+ min_genes: Optional[int] = None,
25
+ cluster_key_stratification: Optional[str] = None,
26
+ parallel: bool = False,
27
+ ):
28
+ """
29
+ Runs the complete genecircuitry analysis pipeline for TRN analysis from single-cell data.
30
+
31
+ This tool integrates Scanpy for preprocessing, CellOracle for GRN inference,
32
+ and Hotspot for identifying embedding-aware gene modules.
33
+ """
34
+ # --- Input Validation ---
35
+ if not input_file.is_file():
36
+ raise FileNotFoundError(f"Input file not found: {input_file}")
37
+
38
+ if n_jobs <= 0:
39
+ raise ValueError("n_jobs must be a positive integer.")
40
+
41
+ allowed_steps = [
42
+ "load", "preprocessing", "stratification", "clustering",
43
+ "celloracle", "hotspot", "grn_analysis", "summary"
44
+ ]
45
+ if steps:
46
+ for step in steps:
47
+ if step not in allowed_steps:
48
+ raise ValueError(
49
+ f"Invalid step '{step}'. Allowed steps are: {', '.join(allowed_steps)}"
50
+ )
51
+
52
+ if parallel and not cluster_key_stratification:
53
+ raise ValueError(
54
+ "When --parallel is enabled, --cluster-key-stratification must be provided."
55
+ )
56
+
57
+ # --- File Path Handling ---
58
+ try:
59
+ output_dir.mkdir(parents=True, exist_ok=True)
60
+ except OSError as e:
61
+ raise OSError(f"Failed to create output directory {output_dir}: {e}")
62
+
63
+ # --- Command Construction ---
64
+ # The documentation suggests the main entry point is a script, but a `genecircuitry`
65
+ # CLI is also mentioned. We will assume the installed package provides this entry point.
66
+ cmd = [
67
+ "genecircuitry",
68
+ "--input", str(input_file),
69
+ "--output", str(output_dir),
70
+ ]
71
+
72
+ if steps:
73
+ cmd.append("--steps")
74
+ cmd.extend(steps)
75
+
76
+ if skip_celloracle:
77
+ cmd.append("--skip-celloracle")
78
+
79
+ if skip_hotspot:
80
+ cmd.append("--skip-hotspot")
81
+
82
+ if seed is not None:
83
+ cmd.extend(["--seed", str(seed)])
84
+
85
+ cmd.extend(["--n-jobs", str(n_jobs)])
86
+
87
+ if min_genes is not None:
88
+ cmd.extend(["--min-genes", str(min_genes)])
89
+
90
+ if cluster_key_stratification:
91
+ cmd.extend(["--cluster-key-stratification", cluster_key_stratification])
92
+
93
+ if parallel:
94
+ cmd.append("--parallel")
95
+
96
+ command_executed = " ".join(cmd)
97
+
98
+ # --- Subprocess Execution ---
99
+ try:
100
+ result = subprocess.run(
101
+ cmd,
102
+ capture_output=True,
103
+ text=True,
104
+ check=True,
105
+ cwd=output_dir, # Run from the output directory to keep logs/temp files contained
106
+ )
107
+ except FileNotFoundError:
108
+ return {
109
+ "error": "genecircuitry command not found. Please ensure the tool is installed and in the system's PATH.",
110
+ "command_executed": command_executed,
111
+ "stdout": "",
112
+ "stderr": "Executable not found.",
113
+ }
114
+ except subprocess.CalledProcessError as e:
115
+ return {
116
+ "error": "GeneCircuitry pipeline failed.",
117
+ "command_executed": command_executed,
118
+ "stdout": e.stdout,
119
+ "stderr": e.stderr,
120
+ "return_code": e.returncode,
121
+ }
122
+
123
+ # --- Structured Result Return ---
124
+ # Based on the documentation, these are the expected primary output files.
125
+ # The exact files generated may depend on the steps run.
126
+ output_files = {
127
+ "preprocessed_data": str(output_dir / "preprocessed_adata.h5ad"),
128
+ "analysis_summary": str(output_dir / "analysis_summary.txt"),
129
+ "celloracle_object": str(output_dir / "celloracle" / "oracle_object.celloracle.oracle"),
130
+ "celloracle_links": str(output_dir / "celloracle" / "grn_links.celloracle.links"),
131
+ "hotspot_autocorrelation": str(output_dir / "hotspot" / "autocorrelation_results.csv"),
132
+ "hotspot_significant_genes": str(output_dir / "hotspot" / "significant_genes.csv"),
133
+ "hotspot_gene_modules": str(output_dir / "hotspot" / "gene_modules.csv"),
134
+ "qc_figures_dir": str(output_dir / "figures" / "qc"),
135
+ "grn_analysis_figures_dir": str(output_dir / "figures" / "grn_analysis"),
136
+ }
137
+
138
+ # Filter out files that might not have been created
139
+ final_output_files = {
140
+ key: path for key, path in output_files.items() if Path(path).exists() or Path(path).is_dir()
141
+ }
142
+
143
+
144
+ return {
145
+ "command_executed": command_executed,
146
+ "stdout": result.stdout,
147
+ "stderr": result.stderr,
148
+ "output_files": final_output_files,
149
+ }
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/app/genecircuitry_shim_server.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/app/genecircuitry_server.py')
11
+ SERVER_NAME = 'biosci_genecircuitry'
12
+
13
+
14
+ class _ShimMCP:
15
+ @staticmethod
16
+ def tool():
17
+ def _decorator(fn):
18
+ return fn
19
+ return _decorator
20
+
21
+
22
+ def _load_functions():
23
+ code = SOURCE_SERVER.read_text(encoding="utf-8")
24
+ tree = ast.parse(code, filename=str(SOURCE_SERVER))
25
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
26
+ namespace = {
27
+ "__name__": "__mcp_source__",
28
+ "mcp": _ShimMCP(),
29
+ }
30
+ exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace)
31
+ loaded = []
32
+ for name in function_names:
33
+ fn = namespace.get(name)
34
+ if callable(fn):
35
+ loaded.append(fn)
36
+ return loaded
37
+
38
+
39
+ mcp = FastMCP(SERVER_NAME)
40
+ for _fn in _load_functions():
41
+ mcp.tool()(_fn)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ mcp.run(transport="stdio")
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-genecircuitry:
5
+ build: .
6
+ image: mcp-genecircuitry:latest
7
+ container_name: mcp-genecircuitry
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=genecircuitry
12
+ volumes:
13
+ - ./workspace:/app/workspace
14
+ - ./output:/app/output
15
+ restart: unless-stopped
16
+ healthcheck:
17
+ test: ["CMD", "python", "-c", "import sys; sys.exit(0)"]
18
+ interval: 30s
19
+ timeout: 10s
20
+ retries: 3
21
+ start_period: 5s
22
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/environment.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ name: mcp-tool
3
+ channels:
4
+ - bioconda
5
+ - conda-forge
6
+ - defaults
7
+ dependencies:
8
+ - genecircuitry
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genecircuitry/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/Dockerfile ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ FROM python:3.10-slim
3
+
4
+ # Install system dependencies
5
+ RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/*
6
+
7
+ # Install Miniconda
8
+ RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh
9
+
10
+ # Add conda to PATH
11
+ ENV PATH="/opt/conda/bin:$PATH"
12
+
13
+ # Install geneimpacts via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda geneimpacts -y && conda clean -a
15
+
16
+ # Install Python dependencies
17
+ RUN pip install uv
18
+ RUN uv pip install --system fastmcp
19
+
20
+ # Create app directory
21
+ WORKDIR /app
22
+
23
+ # Copy your MCP server
24
+ COPY app/geneimpacts_server.py /app/
25
+
26
+ # Create workspace and output directories
27
+ RUN mkdir -p /app/workspace /app/output
28
+
29
+ # Make sure the server script is executable
30
+ RUN chmod +x /app/geneimpacts_server.py
31
+
32
+ # Expose port for MCP over HTTP (optional)
33
+ EXPOSE 8000
34
+
35
+ # Health check
36
+ HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)"
37
+
38
+ # Default command runs the MCP server via stdio
39
+ CMD ["python", "/app/geneimpacts_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/app/geneimpacts_server.py ADDED
@@ -0,0 +1,216 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import tempfile
3
+ from pathlib import Path
4
+ from typing import Optional, Dict, List, Any
5
+
6
+ # This is a placeholder for the actual mcp decorator.
7
+ # Per the instructions, there is "NO NEED to import mcp".
8
+ def tool(*args, **kwargs):
9
+ def decorator(f):
10
+ return f
11
+ return decorator
12
+
13
+ mcp = type("mcp", (), {"tool": tool})
14
+
15
+ # The Python script that will be executed by the MCP tool.
16
+ # This script uses the geneimpacts library to perform the core logic.
17
+ VCF_PROCESSING_SCRIPT = """
18
+ import sys
19
+ import argparse
20
+ import re
21
+ from geneimpacts import Vep, SnpEff, BCFtools
22
+
23
+ def get_parser_and_header(ann_type, ann_field, vcf_header_lines):
24
+ \"\"\"Find the INFO header and return the parser class and format string.\"\"\"
25
+ parser_class = None
26
+ if ann_type == 'vep':
27
+ parser_class = Vep
28
+ elif ann_type == 'snpeff':
29
+ parser_class = SnpEff
30
+ elif ann_type == 'bcftools':
31
+ parser_class = BCFtools
32
+ else:
33
+ # This case should be caught by argparse choices, but is here for safety.
34
+ raise ValueError(f"Unknown annotation type: {ann_type}")
35
+
36
+ # Regex to find the format string within the VCF INFO header description
37
+ header_pattern = re.compile(f'##INFO=<ID={ann_field},.*Description=".*Format: (.*?)">')
38
+ format_string = None
39
+ for line in vcf_header_lines:
40
+ match = header_pattern.search(line)
41
+ if match:
42
+ format_string = match.group(1).strip()
43
+ break
44
+
45
+ if format_string is None:
46
+ raise ValueError(f"Could not find format string for INFO field '{ann_field}' in VCF header. "
47
+ f"Expected a ##INFO line with 'Format: ...' in the description.")
48
+
49
+ return parser_class, format_string
50
+
51
+ def get_top_impact_string(effects):
52
+ \"\"\"Get a string representation of the top impact(s).\"\"\"
53
+ if not effects:
54
+ return "."
55
+
56
+ # Effect.top_severity can return a single object or a list if there's a tie
57
+ top_effects = effects[0].top_severity(effects)
58
+ if not isinstance(top_effects, list):
59
+ top_effects = [top_effects]
60
+
61
+ # Create a unique, sorted list of strings for deterministic output
62
+ impact_strings = {f"{e.gene}|{e.impact_severity}|{e.impact}" for e in top_effects}
63
+ return ",".join(sorted(list(impact_strings)))
64
+
65
+ def main():
66
+ parser = argparse.ArgumentParser(description="Prioritize variant impacts in a VCF file using geneimpacts.")
67
+ parser.add_argument('input_vcf', help="Input VCF file.")
68
+ parser.add_argument('output_vcf', help="Output VCF file.")
69
+ parser.add_argument('--ann_type', required=True, choices=['vep', 'snpeff', 'bcftools'], help="Annotation type.")
70
+ parser.add_argument('--ann_field', required=True, help="INFO field containing the annotations (e.g., CSQ, ANN).")
71
+ parser.add_argument('--new_field', required=True, help="Name for the new INFO field with the top impact.")
72
+ args = parser.parse_args()
73
+
74
+ header_lines = []
75
+ variant_lines = []
76
+ with open(args.input_vcf, 'r') as infile:
77
+ for line in infile:
78
+ if line.startswith('#'):
79
+ header_lines.append(line)
80
+ else:
81
+ variant_lines.append(line)
82
+
83
+ try:
84
+ EffectParser, format_header = get_parser_and_header(args.ann_type, args.ann_field, header_lines)
85
+ except ValueError as e:
86
+ sys.stderr.write(str(e) + '\\n')
87
+ sys.exit(1)
88
+
89
+ with open(args.output_vcf, 'w') as outfile:
90
+ # Write original header, inserting our new INFO field definition
91
+ for line in header_lines:
92
+ if line.startswith('#CHROM'):
93
+ new_header_line = f'##INFO=<ID={args.new_field},Number=.,Type=String,Description="Most severe functional impact from {args.ann_field} field, predicted by geneimpacts. Format: Gene|Severity|Impact">'
94
+ outfile.write(new_header_line + '\\n')
95
+ outfile.write(line)
96
+
97
+ # Process and write variant lines
98
+ for line in variant_lines:
99
+ fields = line.strip().split('\\t')
100
+ info_col = fields[7]
101
+
102
+ info_dict = {item.split('=', 1)[0]: item.split('=', 1)[1] if '=' in item else True for item in info_col.split(';')}
103
+
104
+ top_impact_str = "."
105
+ if args.ann_field in info_dict and info_dict[args.ann_field] is not True:
106
+ ann_string = info_dict[args.ann_field]
107
+ try:
108
+ parser_instance = EffectParser(ann_string, header=format_header)
109
+ effects = list(parser_instance)
110
+ top_impact_str = get_top_impact_string(effects)
111
+ except Exception as e:
112
+ sys.stderr.write(f"Warning: Could not process variant {fields[0]}:{fields[1]}. Error: {e}\\n")
113
+ top_impact_str = "ERROR_PARSING"
114
+
115
+ new_info_entry = f"{args.new_field}={top_impact_str}"
116
+
117
+ if info_col == ".":
118
+ fields[7] = new_info_entry
119
+ else:
120
+ fields[7] = f"{info_col};{new_info_entry}"
121
+
122
+ outfile.write('\\t'.join(fields) + '\\n')
123
+
124
+ if __name__ == "__main__":
125
+ main()
126
+ """
127
+
128
+ @mcp.tool()
129
+ def prioritize(
130
+ vcf_file: Path,
131
+ annotation_type: str,
132
+ annotation_field: str,
133
+ output_vcf: Optional[Path] = None,
134
+ new_info_field: str = "GI_TOP"
135
+ ) -> Dict[str, Any]:
136
+ """
137
+ Prioritizes variant effects from VEP, SnpEff, or BCFtools annotations in a VCF file.
138
+
139
+ This tool reads a VCF file, parses the specified annotation field, uses the
140
+ geneimpacts library to determine the most severe impact for each variant, and
141
+ writes a new VCF file with this information added to a new INFO field.
142
+
143
+ Args:
144
+ vcf_file: Path to the input VCF file.
145
+ annotation_type: The type of annotation to parse. Must be one of 'vep', 'snpeff', or 'bcftools'.
146
+ annotation_field: The INFO field tag containing the annotations (e.g., 'CSQ' for VEP, 'ANN' for SnpEff).
147
+ output_vcf: Optional path for the output annotated VCF file. If not provided, a temporary file will be created.
148
+ new_info_field: The name for the new INFO field that will store the top impact. Defaults to 'GI_TOP'.
149
+
150
+ Returns:
151
+ A dictionary containing the command executed, stdout, stderr, and a dictionary of output files.
152
+ """
153
+ # 1. Input validation
154
+ if not vcf_file.is_file():
155
+ raise FileNotFoundError(f"Input VCF file not found: {vcf_file}")
156
+
157
+ valid_ann_types = ['vep', 'snpeff', 'bcftools']
158
+ if annotation_type not in valid_ann_types:
159
+ raise ValueError(f"Invalid annotation_type '{annotation_type}'. Must be one of {valid_ann_types}")
160
+
161
+ if not new_info_field.isalnum() or new_info_field[0].isdigit():
162
+ raise ValueError(f"new_info_field '{new_info_field}' must be alphanumeric and not start with a digit.")
163
+
164
+ with tempfile.TemporaryDirectory() as temp_dir:
165
+ temp_dir_path = Path(temp_dir)
166
+
167
+ # 2. File path handling
168
+ if output_vcf:
169
+ output_path = output_vcf
170
+ if not output_path.parent.exists():
171
+ raise FileNotFoundError(f"Parent directory for output file does not exist: {output_path.parent}")
172
+ else:
173
+ output_path = temp_dir_path / f"{vcf_file.stem}.geneimpacts.vcf"
174
+
175
+ script_path = temp_dir_path / "vcf_processor.py"
176
+ script_path.write_text(VCF_PROCESSING_SCRIPT)
177
+
178
+ # 3. Subprocess execution
179
+ cmd = [
180
+ "python", str(script_path),
181
+ str(vcf_file),
182
+ str(output_path),
183
+ "--ann_type", annotation_type,
184
+ "--ann_field", annotation_field,
185
+ "--new_field", new_info_field
186
+ ]
187
+
188
+ command_executed = " ".join(cmd)
189
+
190
+ try:
191
+ result = subprocess.run(
192
+ cmd,
193
+ capture_output=True,
194
+ text=True,
195
+ check=True,
196
+ cwd=temp_dir
197
+ )
198
+
199
+ # 4. Structured result return
200
+ return {
201
+ "command_executed": command_executed,
202
+ "stdout": result.stdout,
203
+ "stderr": result.stderr,
204
+ "output_files": {
205
+ "annotated_vcf": str(output_path)
206
+ }
207
+ }
208
+ except subprocess.CalledProcessError as e:
209
+ # 5. Error handling
210
+ return {
211
+ "command_executed": command_executed,
212
+ "stdout": e.stdout,
213
+ "stderr": e.stderr,
214
+ "error": f"geneimpacts wrapper script failed with exit code {e.returncode}",
215
+ "output_files": {}
216
+ }
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/app/geneimpacts_shim_server.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/app/geneimpacts_server.py')
11
+ SERVER_NAME = 'biosci_geneimpacts'
12
+
13
+
14
+ class _ShimMCP:
15
+ @staticmethod
16
+ def tool():
17
+ def _decorator(fn):
18
+ return fn
19
+ return _decorator
20
+
21
+
22
+ def _load_functions():
23
+ code = SOURCE_SERVER.read_text(encoding="utf-8")
24
+ tree = ast.parse(code, filename=str(SOURCE_SERVER))
25
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
26
+ namespace = {
27
+ "__name__": "__mcp_source__",
28
+ "mcp": _ShimMCP(),
29
+ }
30
+ exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace)
31
+ loaded = []
32
+ for name in function_names:
33
+ fn = namespace.get(name)
34
+ if callable(fn):
35
+ loaded.append(fn)
36
+ return loaded
37
+
38
+
39
+ mcp = FastMCP(SERVER_NAME)
40
+ for _fn in _load_functions():
41
+ mcp.tool()(_fn)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ mcp.run(transport="stdio")
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-geneimpacts:
5
+ build: .
6
+ image: mcp-geneimpacts:latest
7
+ container_name: mcp-geneimpacts
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=geneimpacts
12
+ volumes:
13
+ - ./workspace:/app/workspace
14
+ - ./output:/app/output
15
+ restart: unless-stopped
16
+ healthcheck:
17
+ test: ["CMD", "python", "-c", "import sys; sys.exit(0)"]
18
+ interval: 30s
19
+ timeout: 10s
20
+ retries: 3
21
+ start_period: 5s
22
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/environment.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ name: mcp-tool
3
+ channels:
4
+ - bioconda
5
+ - conda-forge
6
+ - defaults
7
+ dependencies:
8
+ - geneimpacts
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_geneimpacts/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genenotebook/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/Dockerfile ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ FROM python:3.10-slim
3
+
4
+ # Install system dependencies
5
+ RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/*
6
+
7
+ # Install Miniconda
8
+ RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh
9
+
10
+ # Add conda to PATH
11
+ ENV PATH="/opt/conda/bin:$PATH"
12
+
13
+ # Install genoboo via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda genoboo -y && conda clean -a
15
+
16
+ # Install Python dependencies
17
+ RUN pip install uv
18
+ RUN uv pip install --system fastmcp
19
+
20
+ # Create app directory
21
+ WORKDIR /app
22
+
23
+ # Copy your MCP server
24
+ COPY app/genoboo_server.py /app/
25
+
26
+ # Create workspace and output directories
27
+ RUN mkdir -p /app/workspace /app/output
28
+
29
+ # Make sure the server script is executable
30
+ RUN chmod +x /app/genoboo_server.py
31
+
32
+ # Expose port for MCP over HTTP (optional)
33
+ EXPOSE 8000
34
+
35
+ # Health check
36
+ HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)"
37
+
38
+ # Default command runs the MCP server via stdio
39
+ CMD ["python", "/app/genoboo_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/app/genoboo_server.py ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ from pathlib import Path
3
+ from typing import Optional
4
+
5
+ # Note: The @mcp.tool decorator is used for MCP integration and is assumed to be available in the execution environment.
6
+ # No import is included here as per the instructions.
7
+
8
+
9
+ @mcp.tool()
10
+ def run_genenotebook(port: int = 3000, timeout: int = 60):
11
+ """
12
+ Starts the GeneNoteBook server.
13
+
14
+ This command initiates the server process, which does not terminate on its own.
15
+ A timeout is used to capture the initial startup logs and then terminate the process.
16
+ Managing the long-running server process is outside the scope of this tool.
17
+ The default admin account is username: 'admin', password: 'admin'.
18
+ """
19
+ # Input validation
20
+ if not (1 <= port <= 65535):
21
+ raise ValueError("Port must be an integer between 1 and 65535.")
22
+ if timeout <= 0:
23
+ raise ValueError("Timeout must be a positive integer.")
24
+
25
+ cmd = ["genenotebook", "run", "--port", str(port)]
26
+ command_executed = " ".join(cmd)
27
+ stdout_str = ""
28
+ stderr_str = ""
29
+
30
+ try:
31
+ # Run the command with a timeout, as it's a server process.
32
+ # We don't use check=True because a timeout is the expected outcome.
33
+ process = subprocess.run(
34
+ cmd, capture_output=True, text=True, timeout=timeout
35
+ )
36
+ stdout_str = process.stdout
37
+ stderr_str = process.stderr
38
+ # If it exits before timeout, it might be an error
39
+ if process.returncode != 0:
40
+ stderr_str += (
41
+ f"\nProcess exited unexpectedly with code {process.returncode}."
42
+ )
43
+ except subprocess.TimeoutExpired as e:
44
+ # This is the expected outcome for a server process.
45
+ stdout_str = e.stdout if e.stdout else ""
46
+ stderr_str = e.stderr if e.stderr else ""
47
+ stderr_str += f"\nProcess timed out after {timeout} seconds, as expected for a server startup."
48
+ except FileNotFoundError:
49
+ return {
50
+ "command_executed": command_executed,
51
+ "stdout": "",
52
+ "stderr": "Error: 'genenotebook' command not found. Please ensure it is installed and in your PATH.",
53
+ "output_files": [],
54
+ }
55
+
56
+ return {
57
+ "command_executed": command_executed,
58
+ "stdout": stdout_str,
59
+ "stderr": stderr_str,
60
+ "output_files": [],
61
+ }
62
+
63
+
64
+ @mcp.tool()
65
+ def add_genome(
66
+ genome_fasta: Path,
67
+ name: str,
68
+ username: str,
69
+ password: str,
70
+ port: int = 3000,
71
+ ):
72
+ """
73
+ Adds a genome from a FASTA file to a running GeneNoteBook instance.
74
+
75
+ This tool requires a GeneNoteBook server to be running and accessible at the specified port.
76
+ """
77
+ # Input validation
78
+ if not genome_fasta.is_file():
79
+ raise FileNotFoundError(f"Input genome FASTA file not found: {genome_fasta}")
80
+ if not name:
81
+ raise ValueError("A name for the genome (-n) must be provided.")
82
+ if not username:
83
+ raise ValueError("A username (-u) must be provided.")
84
+ if not password:
85
+ raise ValueError("A password (-p) must be provided.")
86
+ if not (1 <= port <= 65535):
87
+ raise ValueError("Port must be an integer between 1 and 65535.")
88
+
89
+ cmd = [
90
+ "genenotebook",
91
+ "add",
92
+ "genome",
93
+ "-u",
94
+ username,
95
+ "-p",
96
+ password,
97
+ "--port",
98
+ str(port),
99
+ "-n",
100
+ name,
101
+ str(genome_fasta),
102
+ ]
103
+ command_executed = " ".join(cmd)
104
+
105
+ try:
106
+ process = subprocess.run(cmd, check=True, capture_output=True, text=True)
107
+ stdout = process.stdout
108
+ stderr = process.stderr
109
+ except subprocess.CalledProcessError as e:
110
+ return {
111
+ "command_executed": command_executed,
112
+ "stdout": e.stdout,
113
+ "stderr": e.stderr,
114
+ "output_files": [],
115
+ }
116
+ except FileNotFoundError:
117
+ return {
118
+ "command_executed": command_executed,
119
+ "stdout": "",
120
+ "stderr": "Error: 'genenotebook' command not found. Please ensure it is installed and in your PATH.",
121
+ "output_files": [],
122
+ }
123
+
124
+ return {
125
+ "command_executed": command_executed,
126
+ "stdout": stdout,
127
+ "stderr": stderr,
128
+ "output_files": [],
129
+ }
130
+
131
+
132
+ @mcp.tool()
133
+ def add_annotation(
134
+ annotation_gff3: Path,
135
+ name: str,
136
+ username: str,
137
+ password: str,
138
+ port: int = 3000,
139
+ ):
140
+ """
141
+ Adds an annotation file (GFF3) to a genome in a running GeneNoteBook instance.
142
+
143
+ This tool requires a GeneNoteBook server to be running and accessible at the specified port.
144
+ The 'name' parameter should match the name of an existing genome in the database.
145
+ """
146
+ # Input validation
147
+ if not annotation_gff3.is_file():
148
+ raise FileNotFoundError(
149
+ f"Input annotation GFF3 file not found: {annotation_gff3}"
150
+ )
151
+ if not name:
152
+ raise ValueError("A name for the target genome (-n) must be provided.")
153
+ if not username:
154
+ raise ValueError("A username (-u) must be provided.")
155
+ if not password:
156
+ raise ValueError("A password (-p) must be provided.")
157
+ if not (1 <= port <= 65535):
158
+ raise ValueError("Port must be an integer between 1 and 65535.")
159
+
160
+ cmd = [
161
+ "genenotebook",
162
+ "add",
163
+ "annotation",
164
+ "-u",
165
+ username,
166
+ "-p",
167
+ password,
168
+ "--port",
169
+ str(port),
170
+ "-n",
171
+ name,
172
+ str(annotation_gff3),
173
+ ]
174
+ command_executed = " ".join(cmd)
175
+
176
+ try:
177
+ process = subprocess.run(cmd, check=True, capture_output=True, text=True)
178
+ stdout = process.stdout
179
+ stderr = process.stderr
180
+ except subprocess.CalledProcessError as e:
181
+ return {
182
+ "command_executed": command_executed,
183
+ "stdout": e.stdout,
184
+ "stderr": e.stderr,
185
+ "output_files": [],
186
+ }
187
+ except FileNotFoundError:
188
+ return {
189
+ "command_executed": command_executed,
190
+ "stdout": "",
191
+ "stderr": "Error: 'genenotebook' command not found. Please ensure it is installed and in your PATH.",
192
+ "output_files": [],
193
+ }
194
+
195
+ return {
196
+ "command_executed": command_executed,
197
+ "stdout": stdout,
198
+ "stderr": stderr,
199
+ "output_files": [],
200
+ }
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/app/genoboo_shim_server.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/app/genoboo_server.py')
11
+ SERVER_NAME = 'biosci_genoboo'
12
+
13
+
14
+ class _ShimMCP:
15
+ @staticmethod
16
+ def tool():
17
+ def _decorator(fn):
18
+ return fn
19
+ return _decorator
20
+
21
+
22
+ def _load_functions():
23
+ code = SOURCE_SERVER.read_text(encoding="utf-8")
24
+ tree = ast.parse(code, filename=str(SOURCE_SERVER))
25
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
26
+ namespace = {
27
+ "__name__": "__mcp_source__",
28
+ "mcp": _ShimMCP(),
29
+ }
30
+ exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace)
31
+ loaded = []
32
+ for name in function_names:
33
+ fn = namespace.get(name)
34
+ if callable(fn):
35
+ loaded.append(fn)
36
+ return loaded
37
+
38
+
39
+ mcp = FastMCP(SERVER_NAME)
40
+ for _fn in _load_functions():
41
+ mcp.tool()(_fn)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ mcp.run(transport="stdio")
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-genoboo:
5
+ build: .
6
+ image: mcp-genoboo:latest
7
+ container_name: mcp-genoboo
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=genoboo
12
+ volumes:
13
+ - ./workspace:/app/workspace
14
+ - ./output:/app/output
15
+ restart: unless-stopped
16
+ healthcheck:
17
+ test: ["CMD", "python", "-c", "import sys; sys.exit(0)"]
18
+ interval: 30s
19
+ timeout: 10s
20
+ retries: 3
21
+ start_period: 5s
22
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/environment.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ name: mcp-tool
3
+ channels:
4
+ - bioconda
5
+ - conda-forge
6
+ - defaults
7
+ dependencies:
8
+ - genoboo
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genoboo/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomad/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/Dockerfile ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ FROM python:3.10-slim
3
+
4
+ # Install system dependencies
5
+ RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/*
6
+
7
+ # Install Miniconda
8
+ RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh
9
+
10
+ # Add conda to PATH
11
+ ENV PATH="/opt/conda/bin:$PATH"
12
+
13
+ # Install genomepy via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda genomepy -y && conda clean -a
15
+
16
+ # Install Python dependencies
17
+ RUN pip install uv
18
+ RUN uv pip install --system fastmcp
19
+
20
+ # Create app directory
21
+ WORKDIR /app
22
+
23
+ # Copy your MCP server
24
+ COPY app/genomepy_server.py /app/
25
+
26
+ # Create workspace and output directories
27
+ RUN mkdir -p /app/workspace /app/output
28
+
29
+ # Make sure the server script is executable
30
+ RUN chmod +x /app/genomepy_server.py
31
+
32
+ # Expose port for MCP over HTTP (optional)
33
+ EXPOSE 8000
34
+
35
+ # Health check
36
+ HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)"
37
+
38
+ # Default command runs the MCP server via stdio
39
+ CMD ["python", "/app/genomepy_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/app/genomepy_server.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ from pathlib import Path
3
+ from typing import Optional, List, Literal, Dict, Any
4
+
5
+ # Define common types for reusability and clarity
6
+ GenomeMaskType = Literal["hard", "soft", "none"]
7
+ ProviderType = Literal["GENCODE", "Ensembl", "UCSC", "NCBI", "Local", "URL"]
8
+ UCSCAnnotationType = Literal["ncbiRefSeq", "refGene", "ensGene", "knownGene"]
9
+ PluginName = Literal["blacklist", "bowtie2", "bwa", "gmap", "hisat2", "minimap2", "star"]
10
+
11
+ def _run_genomepy_command(
12
+ command_args: List[str],
13
+ expected_output_paths: Optional[List[Path]] = None
14
+ ) -> Dict[str, Any]:
15
+ """
16
+ Helper function to run genomepy commands and handle output/errors.
17
+ """
18
+ cmd = ["genomepy"] + command_args
19
+ command_executed = " ".join(map(str, cmd))
20
+ stdout = ""
21
+ stderr = ""
22
+ output_files_found: List[str] = []
23
+
24
+ try:
25
+ result = subprocess.run(
26
+ cmd,
27
+ capture_output=True,
28
+ text=True,
29
+ check=True
30
+ )
31
+ stdout = result.stdout
32
+ stderr = result.stderr
33
+
34
+ if expected_output_paths:
35
+ for p in expected_output_paths:
36
+ if p.exists():
37
+ output_files_found.append(str(p.resolve()))
38
+
39
+ except subprocess.CalledProcessError as e:
40
+ return {
41
+ "command_executed": command_executed,
42
+ "stdout": e.stdout,
43
+ "stderr": e.stderr,
44
+ "error": f"Command failed with exit code {e.returncode}",
45
+ "output_files": output_files_found,
46
+ }
47
+ except FileNotFoundError:
48
+ return {
49
+ "command_executed": command_executed,
50
+ "stdout": "",
51
+ "stderr": "genomepy command not found. Please ensure it is installed and in your PATH.",
52
+ "error": "genomepy executable not found",
53
+ "output_files": output_files_found,
54
+ }
55
+
56
+ return {
57
+ "command_executed": command_executed,
58
+ "stdout": stdout,
59
+ "stderr": stderr,
60
+ "output_files": output_files_found,
61
+ }
62
+
63
+ @mcp.tool()
64
+ def get_version() -> Dict[str, Any]:
65
+ """
66
+ Show the genomepy version.
67
+ """
68
+ return _run_genomepy_command(["--version"])
69
+
70
+ @mcp.tool()
71
+ def search(
72
+ term: str,
73
+ provider: Optional[ProviderType] = None,
74
+ size: bool = False,
75
+ ) -> Dict[str, Any]:
76
+ """
77
+ Search for genomes and gene annotations by name, taxonomy ID, or assembly accession ID.
78
+
79
+ Args:
80
+ term: The search term (e.g., genome name, taxonomy ID, assembly accession ID).
81
+ provider: Limit the search result to a specific provider (e.g., "UCSC", "Ensembl").
82
+ size: If True, get the absolute size of each genome (this option slows down the search).
83
+
84
+ Returns:
85
+ A dictionary containing the command executed, stdout, stderr, and any output files.
86
+ """
87
+ if not term:
88
+ raise ValueError("Search term cannot be empty.")
89
+
90
+ cmd_args = ["search", term]
91
+ if provider:
92
+ cmd_args.extend(["--provider", provider])
93
+ if size:
94
+ cmd_args.append("--size")
95
+
96
+ return _run_genomepy_command(cmd_args)
97
+
98
+ @mcp.tool()
99
+ def install(
100
+ name_or_path_or_url: str,
101
+ annotation: bool = False,
102
+ provider: Optional[ProviderType] = None,
103
+ genomes_dir: Optional[Path] = None,
104
+ regex: Optional[str] = None,
105
+ no_match: bool = False,
106
+ mask: GenomeMaskType = "soft",
107
+ bgzip: bool = False,
108
+ localname: Optional[str] = None,
109
+ url_to_annotation: Optional[str] = None,
110
+ local_path_to_annotation: Optional[Path] = None,
111
+ force: bool = False,
112
+ threads: int = 8,
113
+ ucsc_annotation: Optional[UCSCAnnotationType] = None,
114
+ ) -> Dict[str, Any]:
115
+ """
116
+ Install a genome and optionally run active plugins.
117
+ Supports downloading from providers (Ensembl, UCSC, NCBI, GENCODE), URLs, or local files.
118
+
119
+ Args:
120
+ name_or_path_or_url: The genome name, URL, or local file path to install.
121
+ annotation: If True, download gene annotation files along with the genome.
122
+ provider: Specify the provider by name (e.g., "UCSC", "Ensembl"). Required for URL/Local.
123
+ genomes_dir: Directory where genomes will be saved. Defaults to ~/.local/share/genomes/.
124
+ regex: A regular expression to filter for matching sequences (e.g., 'chr[0-9XY]+$').
125
+ no_match: Use with --regex to filter for non-matching sequences.
126
+ mask: Masking type for genome sequences. Choices: "hard" (ACNNN), "soft" (ACgtN), "none" (ACGTN).
127
+ bgzip: If True, compress the downloaded data using bgzip.
128
+ localname: Local name for the genome (used when provider is URL or Local).
129
+ url_to_annotation: URL to an annotation file (used with --provider URL).
130
+ local_path_to_annotation: Filepath to a local annotation file (used with --provider Local).
131
+ force: If True, overwrite local files if they exist.
132
+ threads: Number of threads to use for aligner index creation (if plugins are active).
133
+ ucsc_annotation: Specific UCSC annotation type to download (e.g., "refGene", "ncbiRefSeq").
134
+ Only applicable when --provider UCSC.
135
+
136
+ Returns:
137
+ A dictionary containing the command executed, stdout, stderr, and any output files.
138
+ """
139
+ if not name_or_path_or_url:
140
+ raise ValueError("Genome name, path, or URL cannot be empty.")
141
+ if threads < 1:
142
+ raise ValueError("Number of threads must be a positive integer.")
143
+ if no_match and not regex:
144
+ raise ValueError("--no-match requires --regex to be set.")
145
+ if url_to_annotation and provider != "URL":
146
+ raise ValueError("--URL-to-annotation can only be used with --provider URL.")
147
+ if local_path_to_annotation and provider != "Local":
148
+ raise ValueError("--Local-path-to-annotation can only be used with --provider Local.")
149
+ if ucsc_annotation and provider != "UCSC":
150
+ raise ValueError("--UCSC-annotation can only be used with --provider UCSC.")
151
+ if local_path_to_annotation and not Path(local_path_to_annotation).is_file():
152
+ raise FileNotFoundError(f"Local annotation file not found: {local_path_to_annotation}")
153
+
154
+ cmd_args = ["install", name_or_path_or_url]
155
+
156
+ if annotation:
157
+ cmd_args.append("--annotation")
158
+ if provider:
159
+ cmd_args.extend(["--provider", provider])
160
+
161
+ final_genomes_dir = genomes_dir if genomes_dir else Path.home() / ".local" / "share" / "genomes"
162
+ final_genomes_dir.mkdir(parents=True, exist_ok=True)
163
+ cmd_args.extend(["--genomes_dir", str(final_genomes_dir)])
164
+
165
+ if regex:
166
+ cmd_args.extend(["--regex", regex])
167
+ if no_match:
168
+ cmd_args.append("--no-match")
169
+ if mask != "soft":
170
+ cmd_args.extend(["--mask", mask])
171
+ if bgzip:
172
+ cmd_args.append("--bgzip")
173
+ if localname:
174
+ cmd_args.extend(["--localname", localname])
175
+ if url_to_annotation:
176
+ cmd_args.extend(["--URL-to-annotation", url_to_annotation])
177
+ if local_path_to_annotation:
178
+ cmd_args.extend(["--Local-path-to-annotation", str(local_path_to_annotation)])
179
+ if force:
180
+ cmd_args.append("--force")
181
+ if threads != 8:
182
+ cmd_args.extend(["--threads", str(threads)])
183
+ if ucsc_annotation:
184
+ cmd_args.extend(["--UCSC-annotation", ucsc_annotation])
185
+
186
+ # Determine the local name for the genome, which forms the subfolder name
187
+ genome_local_name: str
188
+ if localname:
189
+ genome_local_name = localname
190
+ elif provider in ["Local", "URL"]:
191
+ base_name = Path(name_or_path_or_url).name
192
+ # Remove common genome file extensions to get the base name genomepy uses for folders
193
+ suffixes_to_remove = [".fa.gz", ".fasta.gz", ".fa", ".fasta", ".tar.gz", ".tar"]
194
+ for suffix in suffixes_to_remove:
195
+ if base_name.endswith(suffix):
196
+ base_name = base_name[:-len(suffix)]
197
+ break
198
+ genome_local_name = base_name
199
+ else:
200
+ genome_local_name = name_or_path_or_url
201
+
202
+ # Predict potential output files
203
+ expected_output_paths: List[Path] = []
204
+ genome_output_folder = final_genomes_dir / genome_local_name
205
+
206
+ fasta_filename = f"{genome_local_name}.fa.gz" if bgzip else f"{genome_local_name}.fa"
207
+ expected_output_paths.append(genome_output_folder / fasta_filename)
208
+ expected_output_paths.append(genome_output_folder / f"{fasta_filename}.fai") # pyfaidx index
209
+ expected_output_paths.append(genome_output_folder / "README.txt") # Reproducibility file
210
+
211
+ if annotation:
212
+ expected_output_paths.append(genome_output_folder / f"{genome_local_name}.annotation.gtf")
213
+ expected_output_paths.append(genome_output_folder / f"{genome_local_name}.annotation.bed")
214
+
215
+ return _run_genomepy_command(cmd_args, expected_output_paths=expected_output_paths)
216
+
217
+ @mcp.tool()
218
+ def annotation(
219
+ genome_name: str,
220
+ provider: Optional[ProviderType] = None,
221
+ genomes_dir: Optional[Path] = None,
222
+ ) -> Dict[str, Any]:
223
+ """
224
+ Show the first lines of each available gene annotation for a specified genome.
225
+
226
+ Args:
227
+ genome_name: The name of the genome for which to inspect annotations.
228
+ provider: Limit to a specific provider.
229
+ genomes_dir: Directory where genomes are stored. Defaults to ~/.local/share/genomes/.
230
+
231
+ Returns:
232
+ A dictionary containing the command executed, stdout, stderr, and any output files.
233
+ """
234
+ if not genome_name:
235
+ raise ValueError("Genome name cannot be empty.")
236
+
237
+ cmd_args = ["annotation", genome_name]
238
+ if provider:
239
+ cmd_args.extend(["--provider", provider])
240
+ if genomes_dir:
241
+ if not genomes_dir.is_dir():
242
+ raise FileNotFoundError(f"Genomes directory not found: {genomes_dir}")
243
+ cmd_args.extend(["--genomes_dir", str(genomes_dir)])
244
+
245
+ return _run_genomepy_command(cmd_args)
246
+
247
+ @mcp.tool()
248
+ def clean() -> Dict[str, Any]:
249
+ """
250
+ Remove local provider data and cached genome lists.
251
+
252
+ Returns:
253
+ A dictionary containing the command executed, stdout, stderr, and any output files.
254
+ """
255
+ return _run_genomepy_command(["clean"])
256
+
257
+ @mcp.tool()
258
+ def config_generate() -> Dict[str, Any]:
259
+ """
260
+ Generate a default genomepy configuration file (~/.config/genomepy/genomepy.yaml).
261
+
262
+ Returns:
263
+ A dictionary containing the command executed, stdout, stderr, and any output files.
264
+ """
265
+ config_file = Path.home() / ".config" / "genomepy" / "genomepy.yaml"
266
+ return _run_genomepy_command(["config", "generate"], expected_output_paths=[config_file])
267
+
268
+ @mcp.tool()
269
+ def genomes(
270
+ provider: Optional[ProviderType] = None,
271
+ size: bool = False,
272
+ ) -> Dict[str, Any]:
273
+ """
274
+ List available genomes, optionally filtered by provider and including genome sizes.
275
+
276
+ Args:
277
+ provider: Limit the genome list to a specific provider.
278
+ size: If True, get the absolute size of each genome (this option slows down the search).
279
+
280
+ Returns:
281
+ A dictionary containing the command executed, stdout, stderr, and any output files.
282
+ """
283
+ cmd_args = ["genomes"]
284
+ if provider:
285
+ cmd_args.extend(["--provider", provider])
286
+ if size:
287
+ cmd_args.append("--size")
288
+
289
+ return _run_genomepy_command(cmd_args)
290
+
291
+ @mcp.tool()
292
+ def plugin_list() -> Dict[str, Any]:
293
+ """
294
+ List currently enabled genomepy plugins.
295
+
296
+ Returns:
297
+ A dictionary containing the command executed, stdout, stderr, and any output files.
298
+ """
299
+ return _run_genomepy_command(["plugin", "list"])
300
+
301
+ @mcp.tool()
302
+ def plugin_enable(
303
+ plugin_name: PluginName,
304
+ ) -> Dict[str, Any]:
305
+ """
306
+ Enable a genomepy plugin.
307
+ Plugins are optional steps executed after installing an assembly (e.g., blacklist, aligner indexes).
308
+
309
+ Args:
310
+ plugin_name: The name of the plugin to enable (e.g., "blacklist", "bwa", "star").
311
+
312
+ Returns:
313
+ A dictionary containing the command executed, stdout, stderr, and any output files.
314
+ """
315
+ if not plugin_name:
316
+ raise ValueError("Plugin name cannot be empty.")
317
+
318
+ return _run_genomepy_command(["plugin", "enable", plugin_name])
319
+
320
+ @mcp.tool()
321
+ def plugin_disable(
322
+ plugin_name: PluginName,
323
+ ) -> Dict[str, Any]:
324
+ """
325
+ Disable a genomepy plugin.
326
+
327
+ Args:
328
+ plugin_name: The name of the plugin to disable.
329
+
330
+ Returns:
331
+ A dictionary containing the command executed, stdout, stderr, and any output files.
332
+ """
333
+ if not plugin_name:
334
+ raise ValueError("Plugin name cannot be empty.")
335
+
336
+ return _run_genomepy_command(["plugin", "disable", plugin_name])
337
+
338
+ @mcp.tool()
339
+ def providers() -> Dict[str, Any]:
340
+ """
341
+ List all available genome providers.
342
+
343
+ Returns:
344
+ A dictionary containing the command executed, stdout, stderr, and any output files.
345
+ """
346
+ return _run_genomepy_command(["providers"])
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/app/genomepy_shim_server.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/app/genomepy_server.py')
11
+ SERVER_NAME = 'biosci_genomepy'
12
+
13
+
14
+ class _ShimMCP:
15
+ @staticmethod
16
+ def tool():
17
+ def _decorator(fn):
18
+ return fn
19
+ return _decorator
20
+
21
+
22
+ def _load_functions():
23
+ code = SOURCE_SERVER.read_text(encoding="utf-8")
24
+ tree = ast.parse(code, filename=str(SOURCE_SERVER))
25
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
26
+ namespace = {
27
+ "__name__": "__mcp_source__",
28
+ "mcp": _ShimMCP(),
29
+ }
30
+ exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace)
31
+ loaded = []
32
+ for name in function_names:
33
+ fn = namespace.get(name)
34
+ if callable(fn):
35
+ loaded.append(fn)
36
+ return loaded
37
+
38
+
39
+ mcp = FastMCP(SERVER_NAME)
40
+ for _fn in _load_functions():
41
+ mcp.tool()(_fn)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ mcp.run(transport="stdio")
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-genomepy:
5
+ build: .
6
+ image: mcp-genomepy:latest
7
+ container_name: mcp-genomepy
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=genomepy
12
+ volumes:
13
+ - ./workspace:/app/workspace
14
+ - ./output:/app/output
15
+ restart: unless-stopped
16
+ healthcheck:
17
+ test: ["CMD", "python", "-c", "import sys; sys.exit(0)"]
18
+ interval: 30s
19
+ timeout: 10s
20
+ retries: 3
21
+ start_period: 5s
22
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/environment.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ name: mcp-tool
3
+ channels:
4
+ - bioconda
5
+ - conda-forge
6
+ - defaults
7
+ dependencies:
8
+ - genomepy
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genomepy/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genometools-genometools/Dockerfile ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ FROM python:3.10-slim
3
+
4
+ # Install system dependencies
5
+ RUN apt-get update && apt-get install -y default-jre wget curl && apt-get clean && rm -rf /var/lib/apt/lists/*
6
+
7
+ # Install Miniconda
8
+ RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O /tmp/miniconda.sh && bash /tmp/miniconda.sh -b -p /opt/conda && rm /tmp/miniconda.sh
9
+
10
+ # Add conda to PATH
11
+ ENV PATH="/opt/conda/bin:$PATH"
12
+
13
+ # Install genometools-genometools via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda genometools-genometools -y && conda clean -a
15
+
16
+ # Install Python dependencies
17
+ RUN pip install uv
18
+ RUN uv pip install --system fastmcp
19
+
20
+ # Create app directory
21
+ WORKDIR /app
22
+
23
+ # Copy your MCP server
24
+ COPY app/genometools-genometools_server.py /app/
25
+
26
+ # Create workspace and output directories
27
+ RUN mkdir -p /app/workspace /app/output
28
+
29
+ # Make sure the server script is executable
30
+ RUN chmod +x /app/genometools-genometools_server.py
31
+
32
+ # Expose port for MCP over HTTP (optional)
33
+ EXPOSE 8000
34
+
35
+ # Health check
36
+ HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 CMD python -c "import sys; sys.exit(0)"
37
+
38
+ # Default command runs the MCP server via stdio
39
+ CMD ["python", "/app/genometools-genometools_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_genometools-genometools/app/genometools-genometools_server.py ADDED
@@ -0,0 +1,626 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import tempfile
3
+ from pathlib import Path
4
+ from typing import List, Optional
5
+
6
+ # Helper function to build command list from parameters
7
+ def _build_command(base_cmd: List[str], params: dict) -> List[str]:
8
+ """Builds a command list from a dictionary of parameters."""
9
+ cmd = list(base_cmd)
10
+ for key, value in params.items():
11
+ if value is None:
12
+ continue
13
+ if isinstance(value, bool):
14
+ if value:
15
+ cmd.append(f"-{key}")
16
+ elif isinstance(value, list):
17
+ for item in value:
18
+ cmd.extend([f"-{key}", str(item)])
19
+ else:
20
+ cmd.extend([f"-{key}", str(value)])
21
+ return cmd
22
+
23
+ @mcp.tool()
24
+ def gff3(
25
+ gff3_files: List[Path],
26
+ sort: bool = False,
27
+ sortlines: bool = False,
28
+ tidy: bool = False,
29
+ add_ids: bool = False,
30
+ check_ids: bool = False,
31
+ fail_on_warning: bool = False,
32
+ typecheck: Optional[Path] = None,
33
+ xrfcheck: Optional[str] = None,
34
+ show_retain_body: bool = False,
35
+ add_contigs: bool = False,
36
+ contigs_file: Optional[Path] = None,
37
+ offset: Optional[int] = None,
38
+ offset_file: Optional[Path] = None,
39
+ set_source: Optional[str] = None,
40
+ out_file: Optional[Path] = None,
41
+ ) -> dict:
42
+ """
43
+ Parse, check, and format GFF3 files. Output is written to stdout by default.
44
+
45
+ Args:
46
+ gff3_files: One or more GFF3 files to process.
47
+ sort: Sort the GFF3 features.
48
+ sortlines: Sort the GFF3 file line by line.
49
+ tidy: Tidy up the GFF3 files.
50
+ add_ids: Add missing IDs to features.
51
+ check_ids: Check uniqueness of feature IDs.
52
+ fail_on_warning: Fail if a warning occurs during parsing.
53
+ typecheck: Check feature types against the given ontology file.
54
+ xrfcheck: Check attribute values against the given ontology.
55
+ show_retain_body: Show '##sequence-region' lines from input and add '##contig' lines for contigs not seen in input.
56
+ add_contigs: Add '##contig' lines for all contigs.
57
+ contigs_file: File containing contigs to add.
58
+ offset: Add this offset to all coordinates.
59
+ offset_file: File containing offsets for each sequence ID.
60
+ set_source: Set the source field of all top-level features to the given string.
61
+ out_file: Optional path to write the output GFF3. If not provided, output is in stdout.
62
+ """
63
+ for f in gff3_files:
64
+ if not f.exists():
65
+ raise FileNotFoundError(f"Input GFF3 file not found: {f}")
66
+ if typecheck and not typecheck.exists():
67
+ raise FileNotFoundError(f"Typecheck ontology file not found: {typecheck}")
68
+ if contigs_file and not contigs_file.exists():
69
+ raise FileNotFoundError(f"Contigs file not found: {contigs_file}")
70
+ if offset_file and not offset_file.exists():
71
+ raise FileNotFoundError(f"Offset file not found: {offset_file}")
72
+
73
+ cmd = ["gt", "gff3"]
74
+ if sort: cmd.append("-sort")
75
+ if sortlines: cmd.append("-sortlines")
76
+ if tidy: cmd.append("-tidy")
77
+ if add_ids: cmd.append("-addids")
78
+ if check_ids: cmd.append("-checkids")
79
+ if fail_on_warning: cmd.append("-fail")
80
+ if typecheck: cmd.extend(["-typecheck", str(typecheck)])
81
+ if xrfcheck: cmd.extend(["-xrfcheck", xrfcheck])
82
+ if show_retain_body: cmd.append("-show_retain_body")
83
+ if add_contigs: cmd.append("-addcontigs")
84
+ if contigs_file: cmd.extend(["-contigsfile", str(contigs_file)])
85
+ if offset is not None: cmd.extend(["-offset", str(offset)])
86
+ if offset_file: cmd.extend(["-offsetfile", str(offset_file)])
87
+ if set_source: cmd.extend(["-setsource", set_source])
88
+ if out_file: cmd.extend(["-o", str(out_file)])
89
+
90
+ cmd.extend([str(f) for f in gff3_files])
91
+
92
+ try:
93
+ result = subprocess.run(cmd, capture_output=True, text=True, check=True)
94
+ output_files = [str(out_file)] if out_file and out_file.exists() else []
95
+ return {
96
+ "command_executed": " ".join(cmd),
97
+ "stdout": result.stdout,
98
+ "stderr": result.stderr,
99
+ "output_files": output_files,
100
+ }
101
+ except subprocess.CalledProcessError as e:
102
+ raise RuntimeError(
103
+ f"genometools gff3 failed with exit code {e.returncode}\n"
104
+ f"Stderr: {e.stderr}\n"
105
+ f"Stdout: {e.stdout}"
106
+ ) from e
107
+
108
+ @mcp.tool()
109
+ def gff3validator(
110
+ gff3_files: List[Path],
111
+ typecheck: Optional[Path] = None,
112
+ xrfcheck: Optional[str] = None,
113
+ ) -> dict:
114
+ """
115
+ Validate GFF3 files according to the specification.
116
+
117
+ Args:
118
+ gff3_files: One or more GFF3 files to validate.
119
+ typecheck: Check feature types against the given ontology file.
120
+ xrfcheck: Check attribute values against the given ontology.
121
+ """
122
+ for f in gff3_files:
123
+ if not f.exists():
124
+ raise FileNotFoundError(f"Input GFF3 file not found: {f}")
125
+ if typecheck and not typecheck.exists():
126
+ raise FileNotFoundError(f"Typecheck ontology file not found: {typecheck}")
127
+
128
+ cmd = ["gt", "gff3validator"]
129
+ if typecheck: cmd.extend(["-typecheck", str(typecheck)])
130
+ if xrfcheck: cmd.extend(["-xrfcheck", xrfcheck])
131
+ cmd.extend([str(f) for f in gff3_files])
132
+
133
+ try:
134
+ result = subprocess.run(cmd, capture_output=True, text=True, check=True)
135
+ return {
136
+ "command_executed": " ".join(cmd),
137
+ "stdout": result.stdout,
138
+ "stderr": result.stderr,
139
+ "output_files": [],
140
+ }
141
+ except subprocess.CalledProcessError as e:
142
+ raise RuntimeError(
143
+ f"genometools gff3validator failed with exit code {e.returncode}\n"
144
+ f"Stderr: {e.stderr}\n"
145
+ f"Stdout: {e.stdout}"
146
+ ) from e
147
+
148
+ @mcp.tool()
149
+ def sketch(
150
+ gff3_file: Path,
151
+ style_file: Path,
152
+ output_file: Path,
153
+ seqid: Optional[str] = None,
154
+ range_start: Optional[int] = None,
155
+ range_end: Optional[int] = None,
156
+ format: str = "png",
157
+ width: int = 800,
158
+ force: bool = False,
159
+ ) -> dict:
160
+ """
161
+ Create a graphical representation of genome annotations (AnnotationSketch).
162
+
163
+ Args:
164
+ gff3_file: The GFF3 file to sketch.
165
+ style_file: A style file describing how to draw the annotations.
166
+ output_file: The path to the output image file.
167
+ seqid: The sequence ID to draw. If not given, all sequences are drawn.
168
+ range_start: The start of the range to draw.
169
+ range_end: The end of the range to draw.
170
+ format: The output format (png, pdf, ps, svg).
171
+ width: The width of the output image in pixels.
172
+ force: Force overwriting of the output file if it exists.
173
+ """
174
+ if not gff3_file.exists():
175
+ raise FileNotFoundError(f"Input GFF3 file not found: {gff3_file}")
176
+ if not style_file.exists():
177
+ raise FileNotFoundError(f"Style file not found: {style_file}")
178
+ if (range_start is not None and range_end is None) or (range_start is None and range_end is not None):
179
+ raise ValueError("Both range_start and range_end must be specified if one is.")
180
+ if format not in ["png", "pdf", "ps", "svg"]:
181
+ raise ValueError("Invalid format. Must be one of 'png', 'pdf', 'ps', 'svg'.")
182
+
183
+ cmd = ["gt", "sketch"]
184
+ cmd.extend(["-style", str(style_file)])
185
+ cmd.extend(["-o", str(output_file)])
186
+ if seqid: cmd.extend(["-seqid", seqid])
187
+ if range_start is not None and range_end is not None:
188
+ cmd.extend(["-range", f"{range_start} {range_end}"])
189
+ cmd.extend(["-format", format])
190
+ cmd.extend(["-width", str(width)])
191
+ if force: cmd.append("-force")
192
+ cmd.append(str(gff3_file))
193
+
194
+ try:
195
+ result = subprocess.run(cmd, capture_output=True, text=True, check=True)
196
+ output_files = [str(output_file)] if output_file.exists() else []
197
+ return {
198
+ "command_executed": " ".join(cmd),
199
+ "stdout": result.stdout,
200
+ "stderr": result.stderr,
201
+ "output_files": output_files,
202
+ }
203
+ except subprocess.CalledProcessError as e:
204
+ raise RuntimeError(
205
+ f"genometools sketch failed with exit code {e.returncode}\n"
206
+ f"Stderr: {e.stderr}\n"
207
+ f"Stdout: {e.stdout}"
208
+ ) from e
209
+
210
+ @mcp.tool()
211
+ def encseq_encode(
212
+ db_files: List[Path],
213
+ index_name: str,
214
+ sds: str = "yes",
215
+ md5: str = "yes",
216
+ sat: Optional[str] = None,
217
+ dna: bool = False,
218
+ protein: bool = False,
219
+ lossless: bool = False,
220
+ des: str = "yes",
221
+ ssp: str = "yes",
222
+ ) -> dict:
223
+ """
224
+ Encode sequence files into a compressed format (encseq).
225
+
226
+ Args:
227
+ db_files: List of sequence files (e.g., FASTA) to encode.
228
+ index_name: Basename for the output index files.
229
+ sds: Skip description support (yes, no).
230
+ md5: Compute MD5 sums for sequences (yes, no).
231
+ sat: Suffix array type (e.g., direct, lcp, bwt).
232
+ dna: Assume DNA sequences.
233
+ protein: Assume protein sequences.
234
+ lossless: Use lossless encoding.
235
+ des: Create description table (yes, no).
236
+ ssp: Create sequence separator position table (yes, no).
237
+ """
238
+ for f in db_files:
239
+ if not f.exists():
240
+ raise FileNotFoundError(f"Input sequence file not found: {f}")
241
+
242
+ cmd = ["gt", "encseq", "encode"]
243
+ cmd.extend(["-indexname", index_name])
244
+ cmd.extend(["-sds", sds])
245
+ cmd.extend(["-md5", md5])
246
+ if sat: cmd.extend(["-sat", sat])
247
+ if dna: cmd.append("-dna")
248
+ if protein: cmd.append("-protein")
249
+ if lossless: cmd.append("-lossless")
250
+ cmd.extend(["-des", des])
251
+ cmd.extend(["-ssp", ssp])
252
+ cmd.extend([str(f) for f in db_files])
253
+
254
+ try:
255
+ result = subprocess.run(cmd, capture_output=True, text=True, check=True)
256
+
257
+ # Identify created index files
258
+ output_files = []
259
+ extensions = [".esq", ".ssp", ".des", ".sds", ".md5", ".prj"]
260
+ if sat:
261
+ extensions.extend([".suf", ".lcp", ".bwt"])
262
+ for ext in extensions:
263
+ f = Path(f"{index_name}{ext}")
264
+ if f.exists():
265
+ output_files.append(str(f))
266
+
267
+ return {
268
+ "command_executed": " ".join(cmd),
269
+ "stdout": result.stdout,
270
+ "stderr": result.stderr,
271
+ "output_files": output_files,
272
+ }
273
+ except subprocess.CalledProcessError as e:
274
+ raise RuntimeError(
275
+ f"genometools encseq encode failed with exit code {e.returncode}\n"
276
+ f"Stderr: {e.stderr}\n"
277
+ f"Stdout: {e.stdout}"
278
+ ) from e
279
+
280
+ @mcp.tool()
281
+ def ltrharvest(
282
+ index: str,
283
+ gff3_files: Optional[List[Path]] = None,
284
+ verbose: bool = False,
285
+ overlaps: str = "best",
286
+ seed: int = 0,
287
+ minlenltr: int = 100,
288
+ maxlenltr: int = 1000,
289
+ mindistltr: int = 1000,
290
+ maxdistltr: int = 25000,
291
+ similar: float = 85.0,
292
+ motif: Optional[str] = "tgca",
293
+ motifmis: int = 1,
294
+ xdrop: int = 5,
295
+ mat: Optional[Path] = None,
296
+ mis: int = -2,
297
+ ins: int = -3,
298
+ delete: int = -3,
299
+ vic: int = 60,
300
+ mintsd: int = 4,
301
+ maxtsd: int = 20,
302
+ fasta: Optional[Path] = None,
303
+ fastawidth: int = 0,
304
+ gff3_out: Optional[Path] = None,
305
+ out: Optional[str] = None,
306
+ ) -> dict:
307
+ """
308
+ De novo detection of LTR retrotransposons.
309
+
310
+ Args:
311
+ index: Basename of the encoded sequence index.
312
+ gff3_files: Optional GFF3 files with sequence regions to process.
313
+ verbose: Be verbose.
314
+ overlaps: Handling of overlapping predictions (best, no, all, inner).
315
+ seed: Seed for random number generator.
316
+ minlenltr: Minimum length of LTRs in bp.
317
+ maxlenltr: Maximum length of LTRs in bp.
318
+ mindistltr: Minimum distance of LTRs in bp.
319
+ maxdistltr: Maximum distance of LTRs in bp.
320
+ similar: Similarity threshold in percent.
321
+ motif: 2 bp motif at LTR boundaries.
322
+ motifmis: Max number of mismatches in motif.
323
+ xdrop: X-drop extension threshold for alignment.
324
+ mat: Score matrix file.
325
+ mis: Mismatch score for alignment.
326
+ ins: Insertion score for alignment.
327
+ delete: Deletion score for alignment.
328
+ vic: Length of vicinity for TSD search.
329
+ mintsd: Minimum length of TSDs in bp.
330
+ maxtsd: Maximum length of TSDs in bp.
331
+ fasta: Output sequences for predicted LTRs to this file.
332
+ fastawidth: Width for FASTA output.
333
+ gff3_out: Output predictions to this GFF3 file.
334
+ out: Output FASTA and GFF3 to files with this prefix (mutually exclusive with -fasta and -gff3).
335
+ """
336
+ if not Path(f"{index}.esq").exists():
337
+ raise FileNotFoundError(f"Encoded sequence index not found for basename: {index}")
338
+ if out and (fasta or gff3_out):
339
+ raise ValueError("-out is mutually exclusive with -fasta and -gff3_out")
340
+ if overlaps not in ["best", "no", "all", "inner"]:
341
+ raise ValueError("Invalid value for 'overlaps'. Must be one of 'best', 'no', 'all', 'inner'.")
342
+
343
+ cmd = ["gt", "ltrharvest", "-index", index]
344
+ if verbose: cmd.append("-v")
345
+ cmd.extend(["-overlaps", overlaps])
346
+ cmd.extend(["-seed", str(seed)])
347
+ cmd.extend(["-minlenltr", str(minlenltr)])
348
+ cmd.extend(["-maxlenltr", str(maxlenltr)])
349
+ cmd.extend(["-mindistltr", str(mindistltr)])
350
+ cmd.extend(["-maxdistltr", str(maxdistltr)])
351
+ cmd.extend(["-similar", str(similar)])
352
+ if motif: cmd.extend(["-motif", motif])
353
+ cmd.extend(["-motifmis", str(motifmis)])
354
+ cmd.extend(["-xdrop", str(xdrop)])
355
+ if mat: cmd.extend(["-mat", str(mat)])
356
+ cmd.extend(["-mis", str(mis)])
357
+ cmd.extend(["-ins", str(ins)])
358
+ cmd.extend(["-del", str(delete)])
359
+ cmd.extend(["-vic", str(vic)])
360
+ cmd.extend(["-mintsd", str(mintsd)])
361
+ cmd.extend(["-maxtsd", str(maxtsd)])
362
+ if fasta: cmd.extend(["-fasta", str(fasta)])
363
+ if fastawidth > 0: cmd.extend(["-fastawidth", str(fastawidth)])
364
+ if gff3_out: cmd.extend(["-gff3", str(gff3_out)])
365
+ if out: cmd.extend(["-out", out])
366
+ if gff3_files:
367
+ for f in gff3_files:
368
+ if not f.exists(): raise FileNotFoundError(f"Input GFF3 file not found: {f}")
369
+ cmd.append(str(f))
370
+
371
+ try:
372
+ result = subprocess.run(cmd, capture_output=True, text=True, check=True)
373
+ output_files = []
374
+ if out:
375
+ gff_out_path = Path(f"{out}.gff3")
376
+ fasta_out_path = Path(f"{out}.fasta")
377
+ if gff_out_path.exists(): output_files.append(str(gff_out_path))
378
+ if fasta_out_path.exists(): output_files.append(str(fasta_out_path))
379
+ if fasta and fasta.exists(): output_files.append(str(fasta))
380
+ if gff3_out and gff3_out.exists(): output_files.append(str(gff3_out))
381
+
382
+ return {
383
+ "command_executed": " ".join(cmd),
384
+ "stdout": result.stdout,
385
+ "stderr": result.stderr,
386
+ "output_files": output_files,
387
+ }
388
+ except subprocess.CalledProcessError as e:
389
+ raise RuntimeError(
390
+ f"genometools ltrharvest failed with exit code {e.returncode}\n"
391
+ f"Stderr: {e.stderr}\n"
392
+ f"Stdout: {e.stdout}"
393
+ ) from e
394
+
395
+ @mcp.tool()
396
+ def ltrdigest(
397
+ gff3_file: Path,
398
+ sequence_index: str,
399
+ output_gff3: Path,
400
+ trna_library: Optional[Path] = None,
401
+ ppt_len: List[int] = [8, 30],
402
+ pbs_len: List[int] = [10, 30],
403
+ pbs_trna_ali_score_range: List[int] = [10, 30],
404
+ hmms: Optional[List[Path]] = None,
405
+ verbose: bool = False,
406
+ ) -> dict:
407
+ """
408
+ Annotate internal features of LTR retrotransposons.
409
+
410
+ Args:
411
+ gff3_file: GFF3 file with LTR retrotransposon predictions (e.g., from ltrharvest).
412
+ sequence_index: Basename of the encoded sequence index.
413
+ output_gff3: Path for the output GFF3 file with annotations.
414
+ trna_library: FASTA file of tRNA sequences for PBS detection.
415
+ ppt_len: Range [min, max] for Polypurine Tract (PPT) length.
416
+ pbs_len: Range [min, max] for Primer Binding Site (PBS) length.
417
+ pbs_trna_ali_score_range: Range [min, max] for PBS-tRNA alignment score.
418
+ hmms: List of HMM profile files for protein domain searches.
419
+ verbose: Be verbose.
420
+ """
421
+ if not gff3_file.exists():
422
+ raise FileNotFoundError(f"Input GFF3 file not found: {gff3_file}")
423
+ if not Path(f"{sequence_index}.esq").exists():
424
+ raise FileNotFoundError(f"Encoded sequence index not found for basename: {sequence_index}")
425
+ if trna_library and not trna_library.exists():
426
+ raise FileNotFoundError(f"tRNA library file not found: {trna_library}")
427
+ if len(ppt_len) != 2 or len(pbs_len) != 2 or len(pbs_trna_ali_score_range) != 2:
428
+ raise ValueError("Length/score range parameters must be lists of two integers.")
429
+
430
+ cmd = ["gt", "ltrdigest", "-seqfile", sequence_index]
431
+ if trna_library: cmd.extend(["-trnalib", str(trna_library)])
432
+ cmd.extend(["-pptlen", f"{ppt_len[0]} {ppt_len[1]}"])
433
+ cmd.extend(["-pbslen", f"{pbs_len[0]} {pbs_len[1]}"])
434
+ cmd.extend(["-pbstrnaaliscorranges", f"{pbs_trna_ali_score_range[0]} {pbs_trna_ali_score_range[1]}"])
435
+ if hmms:
436
+ for hmm in hmms:
437
+ if not hmm.exists(): raise FileNotFoundError(f"HMM file not found: {hmm}")
438
+ cmd.extend(["-hmms", str(hmm)])
439
+ if verbose: cmd.append("-v")
440
+ cmd.extend(["-o", str(output_gff3)])
441
+ cmd.append(str(gff3_file))
442
+
443
+ try:
444
+ result = subprocess.run(cmd, capture_output=True, text=True, check=True)
445
+ output_files = [str(output_gff3)] if output_gff3.exists() else []
446
+ return {
447
+ "command_executed": " ".join(cmd),
448
+ "stdout": result.stdout,
449
+ "stderr": result.stderr,
450
+ "output_files": output_files,
451
+ }
452
+ except subprocess.CalledProcessError as e:
453
+ raise RuntimeError(
454
+ f"genometools ltrdigest failed with exit code {e.returncode}\n"
455
+ f"Stderr: {e.stderr}\n"
456
+ f"Stdout: {e.stdout}"
457
+ ) from e
458
+
459
+ @mcp.tool()
460
+ def tallymer_create(
461
+ encoded_sequence: str,
462
+ index_name: str,
463
+ mer_size: int,
464
+ min_occ: int = 1,
465
+ prefix_length: int = 0,
466
+ counts: bool = False,
467
+ direction: str = "f",
468
+ ) -> dict:
469
+ """
470
+ Create a Tallymer index from an encoded sequence.
471
+
472
+ Args:
473
+ encoded_sequence: Basename of the encoded sequence index.
474
+ index_name: Basename for the output Tallymer index.
475
+ mer_size: The k-mer size.
476
+ min_occ: Minimum occurrences of a k-mer to be included.
477
+ prefix_length: Set prefix length for bucket sort.
478
+ counts: Store k-mer counts in the index.
479
+ direction: Direction to consider (f: forward, r: reverse, p: both).
480
+ """
481
+ if not Path(f"{encoded_sequence}.esq").exists():
482
+ raise FileNotFoundError(f"Encoded sequence index not found: {encoded_sequence}")
483
+ if direction not in ["f", "r", "p"]:
484
+ raise ValueError("Direction must be 'f', 'r', or 'p'.")
485
+
486
+ cmd = ["gt", "tallymer", "create"]
487
+ cmd.extend(["-esa", encoded_sequence])
488
+ cmd.extend(["-indexname", index_name])
489
+ cmd.extend(["-mersize", str(mer_size)])
490
+ cmd.extend(["-minocc", str(min_occ)])
491
+ cmd.extend(["-pl", str(prefix_length)])
492
+ if counts: cmd.append("-counts")
493
+ cmd.extend(["-dir", direction])
494
+
495
+ try:
496
+ result = subprocess.run(cmd, capture_output=True, text=True, check=True)
497
+
498
+ # Tallymer creates several files, e.g., .tis, .counts, .mer, etc.
499
+ # We list the most common ones.
500
+ output_files = []
501
+ extensions = [".tis", ".mer", ".prj"]
502
+ if counts: extensions.append(".counts")
503
+ for ext in extensions:
504
+ f = Path(f"{index_name}{ext}")
505
+ if f.exists():
506
+ output_files.append(str(f))
507
+
508
+ return {
509
+ "command_executed": " ".join(cmd),
510
+ "stdout": result.stdout,
511
+ "stderr": result.stderr,
512
+ "output_files": output_files,
513
+ }
514
+ except subprocess.CalledProcessError as e:
515
+ raise RuntimeError(
516
+ f"genometools tallymer create failed with exit code {e.returncode}\n"
517
+ f"Stderr: {e.stderr}\n"
518
+ f"Stdout: {e.stdout}"
519
+ ) from e
520
+
521
+ @mcp.tool()
522
+ def tallymer_search(
523
+ query_file: Path,
524
+ index: str,
525
+ strand: str = "fp",
526
+ threshold: Optional[int] = None,
527
+ min_len: Optional[int] = None,
528
+ output_options: Optional[List[str]] = None,
529
+ ) -> dict:
530
+ """
531
+ Search for k-mers from a query file in a Tallymer index. Output is to stdout.
532
+
533
+ Args:
534
+ query_file: FASTA file with query sequences.
535
+ index: Basename of the Tallymer index.
536
+ strand: Strand to search (f: forward, p: reverse, fp: both).
537
+ threshold: Report matches with count >= threshold.
538
+ min_len: Minimum length of a seed extension.
539
+ output_options: List of fields to output (e.g., qseqnum, qpos, counts).
540
+ """
541
+ if not query_file.exists():
542
+ raise FileNotFoundError(f"Query file not found: {query_file}")
543
+ if not Path(f"{index}.tis").exists():
544
+ raise FileNotFoundError(f"Tallymer index not found: {index}")
545
+ if strand not in ["f", "p", "fp"]:
546
+ raise ValueError("Strand must be 'f', 'p', or 'fp'.")
547
+
548
+ cmd = ["gt", "tallymer", "search"]
549
+ cmd.extend(["-q", str(query_file)])
550
+ cmd.extend(["-index", index])
551
+ cmd.extend(["-strand", strand])
552
+ if threshold is not None: cmd.extend(["-t", str(threshold)])
553
+ if min_len is not None: cmd.extend(["-l", str(min_len)])
554
+ if output_options:
555
+ cmd.extend(["-output", " ".join(output_options)])
556
+
557
+ try:
558
+ result = subprocess.run(cmd, capture_output=True, text=True, check=True)
559
+ return {
560
+ "command_executed": " ".join(cmd),
561
+ "stdout": result.stdout,
562
+ "stderr": result.stderr,
563
+ "output_files": [],
564
+ }
565
+ except subprocess.CalledProcessError as e:
566
+ raise RuntimeError(
567
+ f"genometools tallymer search failed with exit code {e.returncode}\n"
568
+ f"Stderr: {e.stderr}\n"
569
+ f"Stdout: {e.stdout}"
570
+ ) from e
571
+
572
+ @mcp.tool()
573
+ def extractfeat(
574
+ gff3_file: Path,
575
+ seq_file: Path,
576
+ type: str,
577
+ join: bool = False,
578
+ translate: bool = False,
579
+ target_strand: Optional[str] = None,
580
+ seqid: Optional[str] = None,
581
+ out_file: Optional[Path] = None,
582
+ ) -> dict:
583
+ """
584
+ Extract features from a sequence file based on a GFF3 annotation.
585
+
586
+ Args:
587
+ gff3_file: GFF3 annotation file.
588
+ seq_file: Sequence file (FASTA).
589
+ type: The feature type to extract (e.g., 'gene', 'exon').
590
+ join: Join all features of the given type into a single sequence.
591
+ translate: Translate the extracted sequences into protein.
592
+ target_strand: Extract features only from this strand (+, -, .).
593
+ seqid: Extract features only from this sequence ID.
594
+ out_file: Optional path to write the output FASTA. If not provided, output is in stdout.
595
+ """
596
+ if not gff3_file.exists():
597
+ raise FileNotFoundError(f"GFF3 file not found: {gff3_file}")
598
+ if not seq_file.exists():
599
+ raise FileNotFoundError(f"Sequence file not found: {seq_file}")
600
+ if target_strand and target_strand not in ["+", "-", "."]:
601
+ raise ValueError("target_strand must be '+', '-', or '.'")
602
+
603
+ cmd = ["gt", "extractfeat", "-type", type]
604
+ cmd.extend(["-seqfile", str(seq_file)])
605
+ if join: cmd.append("-join")
606
+ if translate: cmd.append("-translate")
607
+ if target_strand: cmd.extend(["-targetstrand", target_strand])
608
+ if seqid: cmd.extend(["-seqid", seqid])
609
+ if out_file: cmd.extend(["-o", str(out_file)])
610
+ cmd.append(str(gff3_file))
611
+
612
+ try:
613
+ result = subprocess.run(cmd, capture_output=True, text=True, check=True)
614
+ output_files = [str(out_file)] if out_file and out_file.exists() else []
615
+ return {
616
+ "command_executed": " ".join(cmd),
617
+ "stdout": result.stdout,
618
+ "stderr": result.stderr,
619
+ "output_files": output_files,
620
+ }
621
+ except subprocess.CalledProcessError as e:
622
+ raise RuntimeError(
623
+ f"genometools extractfeat failed with exit code {e.returncode}\n"
624
+ f"Stderr: {e.stderr}\n"
625
+ f"Stdout: {e.stdout}"
626
+ ) from e