czty commited on
Commit
51d08ca
·
verified ·
1 Parent(s): 5ffee6a

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

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_help_txt/mcp_celltypist/app/celltypist_server.py +197 -0
  2. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_celltypist/app/celltypist_shim_server.py +45 -0
  3. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_celltypist/docker-compose.yml +22 -0
  4. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_celltypist/environment.yaml +10 -0
  5. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_celltypist/requirements.txt +2 -0
  6. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_circos/Dockerfile +40 -0
  7. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_circos/app/circos_server.py +252 -0
  8. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_circos/app/circos_shim_server.py +45 -0
  9. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_circos/app/requirements.txt +1 -0
  10. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_circos/docker-compose.yml +22 -0
  11. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_circos/environment.yaml +10 -0
  12. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_circos/requirements.txt +2 -0
  13. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_clustalo/Dockerfile +40 -0
  14. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_clustalo/app/clustalo_server.py +248 -0
  15. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_clustalo/app/clustalo_shim_server.py +45 -0
  16. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_clustalo/app/requirements.txt +1 -0
  17. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_clustalo/docker-compose.yml +22 -0
  18. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_clustalo/environment.yaml +10 -0
  19. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_clustalo/requirements.txt +2 -0
  20. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_clustalw/Dockerfile +40 -0
  21. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_clustalw/app/clustalw_server.py +181 -0
  22. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_clustalw/app/clustalw_shim_server.py +45 -0
  23. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_clustalw/app/requirements.txt +1 -0
  24. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_clustalw/docker-compose.yml +22 -0
  25. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_clustalw/environment.yaml +10 -0
  26. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_clustalw/requirements.txt +2 -0
  27. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cnmf/Dockerfile +40 -0
  28. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cnmf/app/cnmf_server.py +348 -0
  29. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cnmf/app/cnmf_shim_server.py +45 -0
  30. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cnmf/docker-compose.yml +22 -0
  31. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cnmf/environment.yaml +10 -0
  32. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cnmf/requirements.txt +2 -0
  33. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_csvtk/Dockerfile +40 -0
  34. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_csvtk/app/csvtk_server.py +548 -0
  35. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_csvtk/app/csvtk_shim_server.py +45 -0
  36. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_csvtk/app/requirements.txt +1 -0
  37. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_csvtk/docker-compose.yml +22 -0
  38. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_csvtk/environment.yaml +10 -0
  39. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_csvtk/requirements.txt +2 -0
  40. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cytotrace2-python/Dockerfile +40 -0
  41. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cytotrace2-python/app/cytotrace2-python_server.py +150 -0
  42. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cytotrace2-python/app/cytotrace2-python_shim_server.py +45 -0
  43. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cytotrace2-python/docker-compose.yml +22 -0
  44. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cytotrace2-python/environment.yaml +10 -0
  45. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cytotrace2-python/requirements.txt +2 -0
  46. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_decoupler/Dockerfile +40 -0
  47. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_decoupler/app/decoupler_server.py +692 -0
  48. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_decoupler/app/decoupler_shim_server.py +45 -0
  49. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_decoupler/docker-compose.yml +22 -0
  50. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_decoupler/environment.yaml +10 -0
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_celltypist/app/celltypist_server.py ADDED
@@ -0,0 +1,197 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import subprocess
4
+ import tempfile
5
+ from pathlib import Path
6
+ from typing import List, Literal, Optional
7
+
8
+ # MCP decorator is not imported as per instructions.
9
+ # It is assumed to be available in the execution environment.
10
+
11
+ # @mcp.tool()
12
+ def celltypist_predict(
13
+ indata: Path,
14
+ model: Optional[str] = None,
15
+ transpose_input: bool = False,
16
+ gene_file: Optional[Path] = None,
17
+ cell_file: Optional[Path] = None,
18
+ mode: Literal["best_match", "prob_match"] = "best_match",
19
+ p_thres: float = 0.5,
20
+ majority_voting: bool = False,
21
+ over_clustering: str = "auto",
22
+ use_gpu: bool = False,
23
+ min_prop: float = 0.0,
24
+ outdir: Optional[Path] = None,
25
+ prefix: Optional[str] = None,
26
+ xlsx: bool = False,
27
+ plot_results: bool = False,
28
+ quiet: bool = False,
29
+ ) -> dict:
30
+ """
31
+ Run Celltypist for semi-automatic cell type annotation on a given count matrix.
32
+
33
+ Args:
34
+ indata: Path to the input count matrix (.csv/txt/tsv/tab/mtx) or AnnData (.h5ad).
35
+ model: Model used for predictions. Defaults to 'Immune_All_Low.pkl'.
36
+ transpose_input: Transpose the input matrix if it is in gene-by-cell format.
37
+ gene_file: Path to a file with one gene per line for mtx input.
38
+ cell_file: Path to a file with one cell per line for mtx input.
39
+ mode: Prediction mode, 'best_match' or 'prob_match'.
40
+ p_thres: Probability threshold for 'prob_match' mode.
41
+ majority_voting: Refine predicted labels by majority voting after over-clustering.
42
+ over_clustering: Input for over-clustering. Can be a file path or a string key.
43
+ use_gpu: Use GPU for over-clustering. Requires rapids-singlecell.
44
+ min_prop: Minimum proportion of cells for naming a subcluster in majority voting.
45
+ outdir: Directory to store output files. A temporary directory is used if not provided.
46
+ prefix: Prefix for output files.
47
+ xlsx: Merge output tables into a single Excel (.xlsx) file.
48
+ plot_results: Generate plots for the prediction results.
49
+ quiet: Hide banner and configuration information during the run.
50
+
51
+ Returns:
52
+ A dictionary containing the executed command, stdout, stderr, and a list of output files.
53
+ """
54
+ # 1. Input validation
55
+ if not indata.is_file():
56
+ raise FileNotFoundError(f"Input data file not found: {indata}")
57
+ if gene_file and not gene_file.is_file():
58
+ raise FileNotFoundError(f"Gene file not found: {gene_file}")
59
+ if cell_file and not cell_file.is_file():
60
+ raise FileNotFoundError(f"Cell file not found: {cell_file}")
61
+ if not (0.0 <= p_thres <= 1.0):
62
+ raise ValueError(f"p_thres must be between 0.0 and 1.0, but got {p_thres}")
63
+ if not (0.0 <= min_prop <= 1.0):
64
+ raise ValueError(f"min_prop must be between 0.0 and 1.0, but got {min_prop}")
65
+
66
+ # 2. Command construction and output directory handling
67
+ with tempfile.TemporaryDirectory() as temp_dir:
68
+ if outdir is None:
69
+ run_outdir = Path(temp_dir)
70
+ else:
71
+ run_outdir = outdir
72
+ run_outdir.mkdir(parents=True, exist_ok=True)
73
+
74
+ cmd = [
75
+ "celltypist",
76
+ "--indata", str(indata),
77
+ "--outdir", str(run_outdir),
78
+ ]
79
+
80
+ if model:
81
+ cmd.extend(["--model", model])
82
+ if transpose_input:
83
+ cmd.append("--transpose-input")
84
+ if gene_file:
85
+ cmd.extend(["--gene-file", str(gene_file)])
86
+ if cell_file:
87
+ cmd.extend(["--cell-file", str(cell_file)])
88
+
89
+ cmd.extend(["--mode", mode])
90
+ if mode == "prob_match":
91
+ cmd.extend(["--p-thres", str(p_thres)])
92
+
93
+ if majority_voting:
94
+ cmd.append("--majority-voting")
95
+ cmd.extend(["--over-clustering", over_clustering])
96
+ if use_gpu:
97
+ cmd.append("--use-GPU")
98
+ cmd.extend(["--min-prop", str(min_prop)])
99
+
100
+ if prefix:
101
+ cmd.extend(["--prefix", prefix])
102
+ if xlsx:
103
+ cmd.append("--xlsx")
104
+ if plot_results:
105
+ cmd.append("--plot-results")
106
+ if quiet:
107
+ cmd.append("--quiet")
108
+
109
+ # 3. Subprocess execution and error handling
110
+ try:
111
+ process = subprocess.run(
112
+ cmd,
113
+ check=True,
114
+ capture_output=True,
115
+ text=True,
116
+ encoding='utf-8'
117
+ )
118
+ stdout = process.stdout
119
+ stderr = process.stderr
120
+ except subprocess.CalledProcessError as e:
121
+ return {
122
+ "command_executed": " ".join(map(str, cmd)),
123
+ "stdout": e.stdout,
124
+ "stderr": e.stderr,
125
+ "return_code": e.returncode,
126
+ "output_files": []
127
+ }
128
+
129
+ # 4. Collect and return structured output
130
+ output_files = [str(f) for f in run_outdir.glob("**/*") if f.is_file()]
131
+
132
+ return {
133
+ "command_executed": " ".join(map(str, cmd)),
134
+ "stdout": stdout,
135
+ "stderr": stderr,
136
+ "output_files": output_files
137
+ }
138
+
139
+ # @mcp.tool()
140
+ def celltypist_show_models() -> dict:
141
+ """
142
+ Show all available Celltypist models and their descriptions.
143
+
144
+ Returns:
145
+ A dictionary containing the executed command, stdout, and stderr.
146
+ """
147
+ cmd = ["celltypist", "--show-models"]
148
+ try:
149
+ process = subprocess.run(
150
+ cmd,
151
+ check=True,
152
+ capture_output=True,
153
+ text=True,
154
+ encoding='utf-8'
155
+ )
156
+ return {
157
+ "command_executed": " ".join(cmd),
158
+ "stdout": process.stdout,
159
+ "stderr": process.stderr,
160
+ }
161
+ except subprocess.CalledProcessError as e:
162
+ return {
163
+ "command_executed": " ".join(cmd),
164
+ "stdout": e.stdout,
165
+ "stderr": e.stderr,
166
+ "return_code": e.returncode,
167
+ }
168
+
169
+ # @mcp.tool()
170
+ def celltypist_update_models() -> dict:
171
+ """
172
+ Download the latest Celltypist models from the remote server.
173
+
174
+ Returns:
175
+ A dictionary containing the executed command, stdout, and stderr.
176
+ """
177
+ cmd = ["celltypist", "--update-models"]
178
+ try:
179
+ process = subprocess.run(
180
+ cmd,
181
+ check=True,
182
+ capture_output=True,
183
+ text=True,
184
+ encoding='utf-8'
185
+ )
186
+ return {
187
+ "command_executed": " ".join(cmd),
188
+ "stdout": process.stdout,
189
+ "stderr": process.stderr,
190
+ }
191
+ except subprocess.CalledProcessError as e:
192
+ return {
193
+ "command_executed": " ".join(cmd),
194
+ "stdout": e.stdout,
195
+ "stderr": e.stderr,
196
+ "return_code": e.returncode,
197
+ }
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_celltypist/app/celltypist_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_help_txt/mcp_celltypist/app/celltypist_server.py')
11
+ SERVER_NAME = 'biosci_celltypist'
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_help_txt/mcp_celltypist/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-celltypist:
5
+ build: .
6
+ image: mcp-celltypist:latest
7
+ container_name: mcp-celltypist
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=celltypist
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_help_txt/mcp_celltypist/environment.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ name: mcp-tool
3
+ channels:
4
+ - bioconda
5
+ - conda-forge
6
+ - defaults
7
+ dependencies:
8
+ - celltypist
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_celltypist/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_circos/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 circos via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda circos -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/circos_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/circos_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/circos_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_circos/app/circos_server.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import tempfile
3
+ import re
4
+ from pathlib import Path
5
+ from typing import Optional, List, Dict, Any
6
+
7
+ # This is a mock decorator. In a real MCP environment, this would be provided by the mcp package.
8
+ class mcp:
9
+ @staticmethod
10
+ def tool(func):
11
+ return func
12
+
13
+ @mcp.tool
14
+ def circos_run(
15
+ conf: Path,
16
+ outputfile: Optional[str] = None,
17
+ outputdir: Optional[Path] = None,
18
+ debug: bool = False,
19
+ debug_group: Optional[str] = None,
20
+ cdump: bool = False,
21
+ mdump: bool = False,
22
+ userconf: Optional[Path] = None,
23
+ params: Optional[List[str]] = None,
24
+ nosvg: bool = False,
25
+ nopng: bool = False,
26
+ ) -> Dict[str, Any]:
27
+ """
28
+ Generates a Circos plot from a configuration file.
29
+
30
+ This is the main tool for creating visualizations. It takes a configuration
31
+ file and various command-line overrides to produce PNG and/or SVG images.
32
+ It can also be used to dump configuration for debugging purposes.
33
+
34
+ Args:
35
+ conf: The main Circos configuration file.
36
+ outputfile: The name of the output image file.
37
+ outputdir: The directory where the output files will be saved.
38
+ debug: Enable debugging output for all groups.
39
+ debug_group: Debug a specific group (e.g., 'summary', 'ideogram').
40
+ cdump: Dump the parsed configuration and exit.
41
+ mdump: Dump the module configuration and exit.
42
+ userconf: Provide an additional user configuration file.
43
+ params: A list of 'key=value' strings to override configuration parameters.
44
+ nosvg: Disable SVG output.
45
+ nopng: Disable PNG output.
46
+
47
+ Returns:
48
+ A dictionary containing the command executed, stdout, stderr, and a list of output files.
49
+ """
50
+ # Input validation
51
+ if not conf.is_file():
52
+ raise FileNotFoundError(f"Configuration file not found: {conf}")
53
+ if userconf and not userconf.is_file():
54
+ raise FileNotFoundError(f"User configuration file not found: {userconf}")
55
+ if params:
56
+ for p in params:
57
+ if not re.match(r"^\S+=\S+$", p):
58
+ raise ValueError(f"Invalid parameter format: '{p}'. Expected 'key=value'.")
59
+
60
+ cmd = ["circos"]
61
+ cmd.extend(["-conf", str(conf)])
62
+
63
+ if outputfile:
64
+ cmd.extend(["-outputfile", outputfile])
65
+ if outputdir:
66
+ outputdir.mkdir(parents=True, exist_ok=True)
67
+ cmd.extend(["-outputdir", str(outputdir)])
68
+ if debug:
69
+ cmd.append("-debug")
70
+ if debug_group:
71
+ cmd.extend(["-debug_group", debug_group])
72
+ if cdump:
73
+ cmd.append("-cdump")
74
+ if mdump:
75
+ cmd.append("-mdump")
76
+ if userconf:
77
+ cmd.extend(["-userconf", str(userconf)])
78
+ if params:
79
+ for p in params:
80
+ cmd.extend(["-param", p])
81
+ if nosvg:
82
+ cmd.append("-nosvg")
83
+ if nopng:
84
+ cmd.append("-nopng")
85
+
86
+ command_executed = " ".join(cmd)
87
+
88
+ try:
89
+ if outputdir:
90
+ work_dir = outputdir
91
+ result = subprocess.run(
92
+ cmd, capture_output=True, text=True, check=True, cwd=work_dir
93
+ )
94
+ # Scan the specified output directory for generated files
95
+ output_files = [str(p) for p in work_dir.glob("*.*")]
96
+ else:
97
+ with tempfile.TemporaryDirectory() as temp_dir:
98
+ work_dir = Path(temp_dir)
99
+ result = subprocess.run(
100
+ cmd, capture_output=True, text=True, check=True, cwd=work_dir
101
+ )
102
+ # Scan the temporary directory for generated files
103
+ output_files = [str(p) for p in work_dir.glob("*.*")]
104
+
105
+ return {
106
+ "command_executed": command_executed,
107
+ "stdout": result.stdout,
108
+ "stderr": result.stderr,
109
+ "output_files": sorted(list(set(output_files)))
110
+ }
111
+ except FileNotFoundError:
112
+ raise RuntimeError("circos command not found. Please ensure it is in your system's PATH.")
113
+ except subprocess.CalledProcessError as e:
114
+ return {
115
+ "command_executed": command_executed,
116
+ "stdout": e.stdout,
117
+ "stderr": e.stderr,
118
+ "error": f"Circos failed with exit code {e.returncode}",
119
+ "output_files": []
120
+ }
121
+
122
+ @mcp.tool
123
+ def circos_list_colors() -> Dict[str, Any]:
124
+ """Lists all available colors in Circos."""
125
+ cmd = ["circos", "-colorlist"]
126
+ command_executed = " ".join(cmd)
127
+ try:
128
+ result = subprocess.run(cmd, capture_output=True, text=True, check=True)
129
+ return {
130
+ "command_executed": command_executed,
131
+ "stdout": result.stdout,
132
+ "stderr": result.stderr,
133
+ }
134
+ except FileNotFoundError:
135
+ raise RuntimeError("circos command not found. Please ensure it is in your system's PATH.")
136
+ except subprocess.CalledProcessError as e:
137
+ return {
138
+ "command_executed": command_executed,
139
+ "stdout": e.stdout,
140
+ "stderr": e.stderr,
141
+ "error": f"Circos failed with exit code {e.returncode}",
142
+ }
143
+
144
+ @mcp.tool
145
+ def circos_list_fonts() -> Dict[str, Any]:
146
+ """Lists all available fonts in Circos."""
147
+ cmd = ["circos", "-fontlist"]
148
+ command_executed = " ".join(cmd)
149
+ try:
150
+ result = subprocess.run(cmd, capture_output=True, text=True, check=True)
151
+ return {
152
+ "command_executed": command_executed,
153
+ "stdout": result.stdout,
154
+ "stderr": result.stderr,
155
+ }
156
+ except FileNotFoundError:
157
+ raise RuntimeError("circos command not found. Please ensure it is in your system's PATH.")
158
+ except subprocess.CalledProcessError as e:
159
+ return {
160
+ "command_executed": command_executed,
161
+ "stdout": e.stdout,
162
+ "stderr": e.stderr,
163
+ "error": f"Circos failed with exit code {e.returncode}",
164
+ }
165
+
166
+ @mcp.tool
167
+ def circos_list_items(item_type: str) -> Dict[str, Any]:
168
+ """
169
+ Lists available items of a given type (e.g., 'ideogram', 'highlight').
170
+
171
+ Args:
172
+ item_type: The type of item to list (e.g., ideogram, highlight, plot, link, rule).
173
+
174
+ Returns:
175
+ A dictionary containing the command executed, stdout, and stderr.
176
+ """
177
+ if not item_type:
178
+ raise ValueError("item_type cannot be empty.")
179
+
180
+ cmd = ["circos", "-list", item_type]
181
+ command_executed = " ".join(cmd)
182
+ try:
183
+ result = subprocess.run(cmd, capture_output=True, text=True, check=True)
184
+ return {
185
+ "command_executed": command_executed,
186
+ "stdout": result.stdout,
187
+ "stderr": result.stderr,
188
+ }
189
+ except FileNotFoundError:
190
+ raise RuntimeError("circos command not found. Please ensure it is in your system's PATH.")
191
+ except subprocess.CalledProcessError as e:
192
+ return {
193
+ "command_executed": command_executed,
194
+ "stdout": e.stdout,
195
+ "stderr": e.stderr,
196
+ "error": f"Circos failed with exit code {e.returncode}",
197
+ }
198
+
199
+ @mcp.tool
200
+ def circos_show_rules(conf: Path) -> Dict[str, Any]:
201
+ """
202
+ Shows the evaluation of rules for a given configuration.
203
+
204
+ Args:
205
+ conf: The Circos configuration file to evaluate rules against.
206
+
207
+ Returns:
208
+ A dictionary containing the command executed, stdout, and stderr.
209
+ """
210
+ if not conf.is_file():
211
+ raise FileNotFoundError(f"Configuration file not found: {conf}")
212
+
213
+ cmd = ["circos", "-rules", "-conf", str(conf)]
214
+ command_executed = " ".join(cmd)
215
+ try:
216
+ result = subprocess.run(cmd, capture_output=True, text=True, check=True)
217
+ return {
218
+ "command_executed": command_executed,
219
+ "stdout": result.stdout,
220
+ "stderr": result.stderr,
221
+ }
222
+ except FileNotFoundError:
223
+ raise RuntimeError("circos command not found. Please ensure it is in your system's PATH.")
224
+ except subprocess.CalledProcessError as e:
225
+ return {
226
+ "command_executed": command_executed,
227
+ "stdout": e.stdout,
228
+ "stderr": e.stderr,
229
+ "error": f"Circos failed with exit code {e.returncode}",
230
+ }
231
+
232
+ @mcp.tool
233
+ def circos_version() -> Dict[str, Any]:
234
+ """Shows the Circos version number."""
235
+ cmd = ["circos", "-version"]
236
+ command_executed = " ".join(cmd)
237
+ try:
238
+ result = subprocess.run(cmd, capture_output=True, text=True, check=True)
239
+ return {
240
+ "command_executed": command_executed,
241
+ "stdout": result.stdout,
242
+ "stderr": result.stderr,
243
+ }
244
+ except FileNotFoundError:
245
+ raise RuntimeError("circos command not found. Please ensure it is in your system's PATH.")
246
+ except subprocess.CalledProcessError as e:
247
+ return {
248
+ "command_executed": command_executed,
249
+ "stdout": e.stdout,
250
+ "stderr": e.stderr,
251
+ "error": f"Circos failed with exit code {e.returncode}",
252
+ }
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_circos/app/circos_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_help_txt/mcp_circos/app/circos_server.py')
11
+ SERVER_NAME = 'biosci_circos'
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_help_txt/mcp_circos/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_circos/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-circos:
5
+ build: .
6
+ image: mcp-circos:latest
7
+ container_name: mcp-circos
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=circos
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_help_txt/mcp_circos/environment.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ name: mcp-tool
3
+ channels:
4
+ - bioconda
5
+ - conda-forge
6
+ - defaults
7
+ dependencies:
8
+ - circos
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_circos/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_clustalo/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 clustalo via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda clustalo -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/clustalo_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/clustalo_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/clustalo_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_clustalo/app/clustalo_server.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ from pathlib import Path
3
+ from typing import List, Optional, Literal
4
+
5
+ # @mcp.tool() decorator would be here in a real MCP environment
6
+ def clustalo(
7
+ infile: Path,
8
+ outfile: Optional[Path] = None,
9
+ hmm_in: Optional[List[Path]] = None,
10
+ hmm_batch: Optional[Path] = None,
11
+ dealign: bool = False,
12
+ profile1: Optional[Path] = None,
13
+ profile2: Optional[Path] = None,
14
+ is_profile: bool = False,
15
+ seqtype: Optional[Literal["Protein", "RNA", "DNA"]] = None,
16
+ infmt: Optional[Literal["a2m", "fasta", "fa", "sta", "clustal", "clu", "msf", "phylip", "phy", "selex", "stockholm", "st", "vienna", "vie"]] = None,
17
+ distmat_in: Optional[Path] = None,
18
+ distmat_out: Optional[Path] = None,
19
+ guidetree_in: Optional[Path] = None,
20
+ guidetree_out: Optional[Path] = None,
21
+ pileup: bool = False,
22
+ full: bool = False,
23
+ full_iter: bool = False,
24
+ cluster_size: Optional[int] = None,
25
+ clustering_out: Optional[Path] = None,
26
+ trans: int = 0,
27
+ posterior_out: Optional[Path] = None,
28
+ use_kimura: bool = False,
29
+ percent_id: bool = False,
30
+ outfmt: Literal["a2m", "fasta", "fa", "sta", "clustal", "clu", "msf", "phylip", "phy", "selex", "stockholm", "st", "vienna", "vie"] = "fasta",
31
+ residuenumber: bool = False,
32
+ wrap: Optional[int] = None,
33
+ output_order: Optional[Literal["input-order", "tree-order"]] = None,
34
+ iterations: Optional[int] = None,
35
+ max_guidetree_iterations: Optional[int] = None,
36
+ max_hmm_iterations: Optional[int] = None,
37
+ maxnumseq: Optional[int] = None,
38
+ maxseqlen: Optional[int] = None,
39
+ auto: bool = False,
40
+ threads: Optional[int] = None,
41
+ pseudo: Optional[Path] = None,
42
+ log: Optional[Path] = None,
43
+ verbose: int = 0,
44
+ force: bool = False,
45
+ mac_ram: Optional[int] = None,
46
+ ):
47
+ """
48
+ Run Clustal Omega for multiple sequence alignment.
49
+
50
+ Clustal Omega is a fast, scalable tool for generating high-quality protein
51
+ and nucleic acid multiple sequence alignments.
52
+
53
+ Args:
54
+ infile: Multiple sequence input file.
55
+ outfile: Multiple sequence alignment output file (default: stdout).
56
+ hmm_in: HMM input files.
57
+ hmm_batch: Specify HMMs for individual sequences.
58
+ dealign: Dealign input sequences.
59
+ profile1: Pre-aligned multiple sequence file (aligned columns will be kept fixed).
60
+ profile2: Pre-aligned multiple sequence file (aligned columns will be kept fixed).
61
+ is_profile: Disable check if profile, force profile (default: False).
62
+ seqtype: Force a sequence type (default: auto).
63
+ infmt: Forced sequence input file format (default: auto).
64
+ distmat_in: Pairwise distance matrix input file (skips distance computation).
65
+ distmat_out: Pairwise distance matrix output file.
66
+ guidetree_in: Guide tree input file (skips guide-tree clustering step).
67
+ guidetree_out: Guide tree output file.
68
+ pileup: Sequentially align sequences.
69
+ full: Use full distance matrix for guide-tree calculation (default: mBed).
70
+ full_iter: Use full distance matrix for guide-tree calculation during iteration (default: mBed).
71
+ cluster_size: Soft maximum of sequences in sub-clusters.
72
+ clustering_out: Clustering output file.
73
+ trans: Use transitivity (default: 0).
74
+ posterior_out: Posterior probability output file.
75
+ use_kimura: Use Kimura distance correction for aligned sequences (default: False).
76
+ percent_id: Convert distances into percent identities (default: False).
77
+ outfmt: MSA output file format (default: fasta).
78
+ residuenumber: In Clustal format, print residue numbers (default: False).
79
+ wrap: Number of residues before line-wrap in output.
80
+ output_order: MSA output order like in input/guide-tree.
81
+ iterations: Number of (combined guide-tree/HMM) iterations.
82
+ max_guidetree_iterations: Maximum number of guidetree iterations.
83
+ max_hmm_iterations: Maximum number of HMM iterations.
84
+ maxnumseq: Maximum allowed number of sequences.
85
+ maxseqlen: Maximum allowed sequence length.
86
+ auto: Set options automatically (might overwrite some of your options).
87
+ threads: Number of processors to use.
88
+ pseudo: Input file for pseudo-count parameters.
89
+ log: Log all non-essential output to this file.
90
+ verbose: Verbose output level (e.g., 1 for -v, 2 for -vv).
91
+ force: Force file overwriting.
92
+ mac_ram: Set a memory limit (undocumented, platform-specific).
93
+
94
+ Returns:
95
+ A dictionary containing the command executed, stdout, stderr, and a list of output files.
96
+ """
97
+ # --- Input Validation ---
98
+ if not infile.is_file():
99
+ raise FileNotFoundError(f"Input file not found: {infile}")
100
+
101
+ input_files_to_check = {
102
+ "hmm_batch": hmm_batch,
103
+ "profile1": profile1,
104
+ "profile2": profile2,
105
+ "distmat_in": distmat_in,
106
+ "guidetree_in": guidetree_in,
107
+ "pseudo": pseudo,
108
+ }
109
+ for name, path in input_files_to_check.items():
110
+ if path and not path.is_file():
111
+ raise FileNotFoundError(f"Input file for --{name.replace('_', '-')} not found: {path}")
112
+
113
+ if hmm_in:
114
+ for hmm_file in hmm_in:
115
+ if not hmm_file.is_file():
116
+ raise FileNotFoundError(f"HMM input file not found: {hmm_file}")
117
+
118
+ if threads is not None and threads <= 0:
119
+ raise ValueError("threads must be a positive integer.")
120
+
121
+ if verbose < 0:
122
+ raise ValueError("verbose level cannot be negative.")
123
+
124
+ # --- Command Construction ---
125
+ cmd = ["clustalo"]
126
+ output_files = []
127
+
128
+ # Sequence Input
129
+ cmd.extend(["--infile", str(infile)])
130
+ if hmm_in:
131
+ for hmm_file in hmm_in:
132
+ cmd.extend(["--hmm-in", str(hmm_file)])
133
+ if hmm_batch:
134
+ cmd.extend(["--hmm-batch", str(hmm_batch)])
135
+ if dealign:
136
+ cmd.append("--dealign")
137
+ if profile1:
138
+ cmd.extend(["--profile1", str(profile1)])
139
+ if profile2:
140
+ cmd.extend(["--profile2", str(profile2)])
141
+ if is_profile:
142
+ cmd.append("--is-profile")
143
+ if seqtype:
144
+ cmd.extend(["--seqtype", seqtype])
145
+ if infmt:
146
+ cmd.extend(["--infmt", infmt])
147
+
148
+ # Clustering
149
+ if distmat_in:
150
+ cmd.extend(["--distmat-in", str(distmat_in)])
151
+ if distmat_out:
152
+ cmd.extend(["--distmat-out", str(distmat_out)])
153
+ output_files.append(str(distmat_out))
154
+ if guidetree_in:
155
+ cmd.extend(["--guidetree-in", str(guidetree_in)])
156
+ if guidetree_out:
157
+ cmd.extend(["--guidetree-out", str(guidetree_out)])
158
+ output_files.append(str(guidetree_out))
159
+ if pileup:
160
+ cmd.append("--pileup")
161
+ if full:
162
+ cmd.append("--full")
163
+ if full_iter:
164
+ cmd.append("--full-iter")
165
+ if cluster_size is not None:
166
+ cmd.extend(["--cluster-size", str(cluster_size)])
167
+ if clustering_out:
168
+ cmd.extend(["--clustering-out", str(clustering_out)])
169
+ output_files.append(str(clustering_out))
170
+ if trans != 0:
171
+ cmd.extend(["--trans", str(trans)])
172
+ if posterior_out:
173
+ cmd.extend(["--posterior-out", str(posterior_out)])
174
+ output_files.append(str(posterior_out))
175
+ if use_kimura:
176
+ cmd.append("--use-kimura")
177
+ if percent_id:
178
+ cmd.append("--percent-id")
179
+
180
+ # Alignment Output
181
+ if outfile:
182
+ cmd.extend(["--outfile", str(outfile)])
183
+ output_files.append(str(outfile))
184
+ cmd.extend(["--outfmt", outfmt])
185
+ if residuenumber:
186
+ cmd.append("--residuenumber")
187
+ if wrap is not None:
188
+ cmd.extend(["--wrap", str(wrap)])
189
+ if output_order:
190
+ cmd.extend(["--output-order", output_order])
191
+
192
+ # Iteration
193
+ if iterations is not None:
194
+ cmd.extend(["--iterations", str(iterations)])
195
+ if max_guidetree_iterations is not None:
196
+ cmd.extend(["--max-guidetree-iterations", str(max_guidetree_iterations)])
197
+ if max_hmm_iterations is not None:
198
+ cmd.extend(["--max-hmm-iterations", str(max_hmm_iterations)])
199
+
200
+ # Limits
201
+ if maxnumseq is not None:
202
+ cmd.extend(["--maxnumseq", str(maxnumseq)])
203
+ if maxseqlen is not None:
204
+ cmd.extend(["--maxseqlen", str(maxseqlen)])
205
+
206
+ # Miscellaneous
207
+ if auto:
208
+ cmd.append("--auto")
209
+ if threads is not None:
210
+ cmd.extend(["--threads", str(threads)])
211
+ if pseudo:
212
+ cmd.extend(["--pseudo", str(pseudo)])
213
+ if log:
214
+ cmd.extend(["--log", str(log)])
215
+ output_files.append(str(log))
216
+ if verbose > 0:
217
+ cmd.append("-" + "v" * verbose)
218
+ if force:
219
+ cmd.append("--force")
220
+ if mac_ram is not None:
221
+ cmd.extend(["--MAC-RAM", str(mac_ram)])
222
+
223
+ # --- Subprocess Execution ---
224
+ try:
225
+ command_str = " ".join(cmd)
226
+ result = subprocess.run(
227
+ cmd,
228
+ capture_output=True,
229
+ text=True,
230
+ check=True
231
+ )
232
+ return {
233
+ "command_executed": command_str,
234
+ "stdout": result.stdout,
235
+ "stderr": result.stderr,
236
+ "output_files": output_files
237
+ }
238
+ except FileNotFoundError:
239
+ raise RuntimeError("clustalo command not found. Please ensure it is installed and in your system's PATH.")
240
+ except subprocess.CalledProcessError as e:
241
+ # Return structured error information
242
+ return {
243
+ "command_executed": " ".join(e.cmd),
244
+ "stdout": e.stdout,
245
+ "stderr": e.stderr,
246
+ "error": f"ClustalO failed with exit code {e.returncode}",
247
+ "output_files": []
248
+ }
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_clustalo/app/clustalo_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_help_txt/mcp_clustalo/app/clustalo_server.py')
11
+ SERVER_NAME = 'biosci_clustalo'
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_help_txt/mcp_clustalo/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_clustalo/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-clustalo:
5
+ build: .
6
+ image: mcp-clustalo:latest
7
+ container_name: mcp-clustalo
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=clustalo
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_help_txt/mcp_clustalo/environment.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ name: mcp-tool
3
+ channels:
4
+ - bioconda
5
+ - conda-forge
6
+ - defaults
7
+ dependencies:
8
+ - clustalo
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_clustalo/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_clustalw/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 clustalw via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda clustalw -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/clustalw_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/clustalw_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/clustalw_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_clustalw/app/clustalw_server.py ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import logging
3
+ from pathlib import Path
4
+ from typing import Optional, List, Dict, Any, Literal
5
+
6
+ # Set up logging
7
+ logging.basicConfig(level=logging.INFO)
8
+ log = logging.getLogger(__name__)
9
+
10
+ # This is a placeholder for the MCP decorator.
11
+ # In a real MCP environment, this would be imported.
12
+ def tool(func):
13
+ """A dummy decorator to stand in for @mcp.tool()."""
14
+ def wrapper(*args, **kwargs):
15
+ return func(*args, **kwargs)
16
+ return wrapper
17
+
18
+ mcp = type('mcp', (), {'tool': tool})
19
+
20
+
21
+ @mcp.tool
22
+ def clustalw(
23
+ infile: Optional[Path] = None,
24
+ profile1: Optional[Path] = None,
25
+ profile2: Optional[Path] = None,
26
+ outfile: Optional[Path] = None,
27
+ output_format: Optional[Literal["GDE", "GCG", "PHYLIP", "PIR", "NEXUS", "FASTA"]] = None,
28
+ sequence_type: Optional[Literal["PROTEIN", "DNA"]] = None,
29
+ convert: bool = False,
30
+ quicktree: bool = False,
31
+ newtree: Optional[Path] = None,
32
+ usetree: Optional[Path] = None,
33
+ output_order: Optional[Literal["INPUT", "ALIGNED"]] = "ALIGNED",
34
+ clustering: Optional[Literal["NJ", "UPGMA"]] = "NJ",
35
+ iteration: Optional[Literal["NONE", "TREE", "ALIGNMENT"]] = None,
36
+ numiter: Optional[int] = None,
37
+ gapdist: Optional[int] = None,
38
+ stats: Optional[Path] = None,
39
+ quiet: bool = False,
40
+ matrix: Optional[str] = None,
41
+ dnamatrix: Optional[str] = None,
42
+ gapopen: Optional[float] = None,
43
+ gapext: Optional[float] = None,
44
+ endgaps: bool = False,
45
+ nopgap: bool = False,
46
+ nohgap: bool = False,
47
+ hgapresidues: Optional[str] = None,
48
+ maxdiv: Optional[int] = None,
49
+ pwmatrix: Optional[str] = None,
50
+ pwdnamatrix: Optional[str] = None,
51
+ pwgapopen: Optional[float] = None,
52
+ pwgapext: Optional[float] = None,
53
+ negative: bool = False,
54
+ ) -> Dict[str, Any]:
55
+ """
56
+ Performs multiple sequence alignment using ClustalW 2.1.
57
+
58
+ This tool can perform de novo multiple sequence alignments, profile alignments,
59
+ or convert existing alignment formats.
60
+ """
61
+ # --- Input Validation ---
62
+ if infile and (profile1 or profile2):
63
+ raise ValueError("Cannot use `infile` with `profile1` or `profile2`. Use one mode at a time.")
64
+ if (profile1 and not profile2) or (not profile1 and profile2):
65
+ raise ValueError("`profile1` and `profile2` must be used together for profile alignment.")
66
+ if not infile and not (profile1 and profile2):
67
+ raise ValueError("Either `infile` or both `profile1` and `profile2` must be provided.")
68
+
69
+ if infile:
70
+ if not infile.is_file():
71
+ raise FileNotFoundError(f"Input file not found: {infile}")
72
+ if profile1:
73
+ if not profile1.is_file():
74
+ raise FileNotFoundError(f"Profile 1 file not found: {profile1}")
75
+ if profile2:
76
+ if not profile2.is_file():
77
+ raise FileNotFoundError(f"Profile 2 file not found: {profile2}")
78
+ if usetree:
79
+ if not usetree.is_file():
80
+ raise FileNotFoundError(f"User-provided guide tree not found: {usetree}")
81
+
82
+ if maxdiv is not None and not (0 < maxdiv <= 100):
83
+ raise ValueError("`maxdiv` must be an integer between 1 and 100.")
84
+
85
+ # --- Command and Output File Construction ---
86
+ cmd = ["clustalw"]
87
+ output_files: List[str] = []
88
+
89
+ base_input_path = infile or profile1
90
+
91
+ # Determine output file paths if not specified
92
+ if not outfile and base_input_path:
93
+ # ClustalW's default output is based on the input file stem
94
+ outfile = base_input_path.with_name(f"{base_input_path.stem}.aln")
95
+ if outfile:
96
+ cmd.append(f"-OUTFILE={outfile}")
97
+ output_files.append(str(outfile))
98
+
99
+ # ClustalW creates a .dnd guide tree file by default if not using a provided tree
100
+ predicted_treefile = None
101
+ if not newtree and not usetree and base_input_path:
102
+ predicted_treefile = base_input_path.with_name(f"{base_input_path.stem}.dnd")
103
+ output_files.append(str(predicted_treefile))
104
+
105
+ # --- Append arguments to command ---
106
+ # Input/Output
107
+ if infile: cmd.append(f"-INFILE={infile}")
108
+ if profile1: cmd.append(f"-PROFILE1={profile1}")
109
+ if profile2: cmd.append(f"-PROFILE2={profile2}")
110
+ if output_format: cmd.append(f"-OUTPUT={output_format.upper()}")
111
+ if sequence_type: cmd.append(f"-TYPE={sequence_type.upper()}")
112
+ if convert: cmd.append("-CONVERT")
113
+ if quiet: cmd.append("-QUIET")
114
+ if stats:
115
+ cmd.append(f"-STATS={stats}")
116
+ output_files.append(str(stats))
117
+
118
+ # Alignment Structure
119
+ if quicktree: cmd.append("-QUICKTREE")
120
+ if newtree:
121
+ cmd.append(f"-NEWTREE={newtree}")
122
+ output_files.append(str(newtree))
123
+ if str(predicted_treefile) in output_files:
124
+ output_files.remove(str(predicted_treefile)) # Remove predicted if explicit is given
125
+ if usetree: cmd.append(f"-USETREE={usetree}")
126
+ if output_order: cmd.append(f"-OUTORDER={output_order.upper()}")
127
+ if clustering: cmd.append(f"-CLUSTERING={clustering.upper()}")
128
+
129
+ # Iteration
130
+ if iteration: cmd.append(f"-ITERATION={iteration.upper()}")
131
+ if numiter is not None: cmd.append(f"-NUMITER={numiter}")
132
+ if gapdist is not None: cmd.append(f"-GAPDIST={gapdist}")
133
+
134
+ # Pairwise Alignment Parameters
135
+ if matrix: cmd.append(f"-MATRIX={matrix.upper()}")
136
+ if dnamatrix: cmd.append(f"-DNAMATRIX={dnamatrix.upper()}")
137
+ if gapopen is not None: cmd.append(f"-GAPOPEN={gapopen}")
138
+ if gapext is not None: cmd.append(f"-GAPEXT={gapext}")
139
+ if endgaps: cmd.append("-ENDGAPS")
140
+ if nopgap: cmd.append("-NOPGAP")
141
+ if nohgap: cmd.append("-NOHGAP")
142
+ if hgapresidues: cmd.append(f"-HGAPRESIDUES={hgapresidues}")
143
+ if maxdiv is not None: cmd.append(f"-MAXDIV={maxdiv}")
144
+
145
+ # Multiple Alignment Parameters
146
+ if pwmatrix: cmd.append(f"-PWMATRIX={pwmatrix.upper()}")
147
+ if pwdnamatrix: cmd.append(f"-PWDNAMATRIX={pwdnamatrix.upper()}")
148
+ if pwgapopen is not None: cmd.append(f"-PWGAPOPEN={pwgapopen}")
149
+ if pwgapext is not None: cmd.append(f"-PWGAPEXT={pwgapext}")
150
+ if negative: cmd.append("-NEGATIVE")
151
+
152
+ # --- Subprocess Execution ---
153
+ command_str = " ".join(map(str, cmd))
154
+ log.info(f"Executing command: {command_str}")
155
+
156
+ try:
157
+ result = subprocess.run(
158
+ cmd,
159
+ capture_output=True,
160
+ text=True,
161
+ check=True,
162
+ )
163
+ # Verify that expected output files were created
164
+ verified_files = [f for f in output_files if Path(f).exists()]
165
+
166
+ return {
167
+ "command_executed": command_str,
168
+ "stdout": result.stdout,
169
+ "stderr": result.stderr,
170
+ "output_files": verified_files,
171
+ }
172
+ except FileNotFoundError:
173
+ raise RuntimeError("clustalw executable not found. Please ensure it is in your system's PATH.")
174
+ except subprocess.CalledProcessError as e:
175
+ log.error(f"ClustalW failed with exit code {e.returncode}")
176
+ log.error(f"STDOUT: {e.stdout}")
177
+ log.error(f"STDERR: {e.stderr}")
178
+ raise RuntimeError(
179
+ f"ClustalW execution failed. Command: '{command_str}'. "
180
+ f"Error: {e.stderr}"
181
+ ) from e
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_clustalw/app/clustalw_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_help_txt/mcp_clustalw/app/clustalw_server.py')
11
+ SERVER_NAME = 'biosci_clustalw'
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_help_txt/mcp_clustalw/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_clustalw/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-clustalw:
5
+ build: .
6
+ image: mcp-clustalw:latest
7
+ container_name: mcp-clustalw
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=clustalw
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_help_txt/mcp_clustalw/environment.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ name: mcp-tool
3
+ channels:
4
+ - bioconda
5
+ - conda-forge
6
+ - defaults
7
+ dependencies:
8
+ - clustalw
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_clustalw/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cnmf/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 cnmf via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda cnmf -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 cnmf_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/cnmf_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/cnmf_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cnmf/app/cnmf_server.py ADDED
@@ -0,0 +1,348 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import shlex
3
+ from pathlib import Path
4
+ from typing import List, Optional
5
+
6
+ # MCP decorator is commented out as per instructions
7
+ # @mcp.tool()
8
+ def cnmf_prepare(
9
+ counts: Path,
10
+ components: List[int],
11
+ n_iter: int,
12
+ name: str,
13
+ output_dir: Path,
14
+ total_workers: Optional[int] = None,
15
+ seed: Optional[int] = None,
16
+ genes_file: Optional[Path] = None,
17
+ numgenes: Optional[int] = None,
18
+ tpm: Optional[Path] = None,
19
+ max_nmf_iter: int = 1000,
20
+ beta_loss: str = "frobenius",
21
+ init: str = "random",
22
+ densify: bool = False,
23
+ ) -> dict:
24
+ """
25
+ Prepares the data and directory structure for a cNMF analysis.
26
+
27
+ This step filters the count matrix, selects high-variance genes,
28
+ and sets up the output directory for subsequent factorization runs.
29
+ """
30
+ # --- Input Validation ---
31
+ if not counts.is_file():
32
+ raise FileNotFoundError(f"Input counts file not found: {counts}")
33
+ if genes_file and not genes_file.is_file():
34
+ raise FileNotFoundError(f"Genes file not found: {genes_file}")
35
+ if tpm and not tpm.is_file():
36
+ raise FileNotFoundError(f"TPM file not found: {tpm}")
37
+
38
+ if not components:
39
+ raise ValueError("At least one component value (-k/--components) must be provided.")
40
+ if n_iter <= 0:
41
+ raise ValueError("--n-iter must be a positive integer.")
42
+ if max_nmf_iter <= 0:
43
+ raise ValueError("--max-nmf-iter must be a positive integer.")
44
+ if numgenes is not None and numgenes <= 0:
45
+ raise ValueError("--numgenes must be a positive integer.")
46
+
47
+ beta_loss_choices = ["frobenius", "kullback-leibler", "itakura-saito"]
48
+ if beta_loss not in beta_loss_choices:
49
+ raise ValueError(f"--beta-loss must be one of {beta_loss_choices}, not '{beta_loss}'")
50
+
51
+ init_choices = ["random", "nndsvd"]
52
+ if init not in init_choices:
53
+ raise ValueError(f"--init must be one of {init_choices}, not '{init}'")
54
+
55
+ # --- Command Construction ---
56
+ cmd = ["cnmf", "prepare"]
57
+ cmd.extend(["--output-dir", str(output_dir)])
58
+ cmd.extend(["--name", name])
59
+ cmd.extend(["--counts", str(counts)])
60
+ cmd.extend(["--components", *[str(k) for k in components]])
61
+ cmd.extend(["--n-iter", str(n_iter)])
62
+
63
+ if total_workers is not None:
64
+ cmd.extend(["--total-workers", str(total_workers)])
65
+ if seed is not None:
66
+ cmd.extend(["--seed", str(seed)])
67
+ if genes_file:
68
+ cmd.extend(["--genes-file", str(genes_file)])
69
+ if numgenes is not None:
70
+ cmd.extend(["--numgenes", str(numgenes)])
71
+ if tpm:
72
+ cmd.extend(["--tpm", str(tpm)])
73
+ if max_nmf_iter != 1000:
74
+ cmd.extend(["--max-nmf-iter", str(max_nmf_iter)])
75
+ if beta_loss != "frobenius":
76
+ cmd.extend(["--beta-loss", beta_loss])
77
+ if init != "random":
78
+ cmd.extend(["--init", init])
79
+ if densify:
80
+ cmd.append("--densify")
81
+
82
+ # --- Subprocess Execution ---
83
+ try:
84
+ # Ensure output directory exists
85
+ output_dir.mkdir(parents=True, exist_ok=True)
86
+
87
+ process = subprocess.run(
88
+ cmd,
89
+ capture_output=True,
90
+ text=True,
91
+ check=True,
92
+ )
93
+ except FileNotFoundError:
94
+ return {
95
+ "command_executed": shlex.join(cmd),
96
+ "stdout": "",
97
+ "stderr": "Error: 'cnmf' command not found. Please ensure it is in your PATH.",
98
+ "output_files": []
99
+ }
100
+ except subprocess.CalledProcessError as e:
101
+ return {
102
+ "command_executed": shlex.join(cmd),
103
+ "stdout": e.stdout,
104
+ "stderr": e.stderr,
105
+ "output_files": []
106
+ }
107
+
108
+ # --- Structured Result Return ---
109
+ # The prepare step creates the main output directory for the analysis.
110
+ output_path = output_dir / name
111
+ return {
112
+ "command_executed": shlex.join(cmd),
113
+ "stdout": process.stdout,
114
+ "stderr": process.stderr,
115
+ "output_files": [str(output_path)]
116
+ }
117
+
118
+
119
+ # @mcp.tool()
120
+ def cnmf_factorize(
121
+ name: str,
122
+ output_dir: Path,
123
+ worker_index: Optional[int] = None,
124
+ total_workers: Optional[int] = None,
125
+ skip_completed_runs: bool = False,
126
+ ) -> dict:
127
+ """
128
+ Runs the NMF factorizations for a cNMF analysis.
129
+
130
+ This step can be parallelized across multiple workers.
131
+ """
132
+ # --- Input Validation ---
133
+ if worker_index is not None and worker_index < 0:
134
+ raise ValueError("--worker-index must be a non-negative integer.")
135
+ if total_workers is not None and total_workers <= 0:
136
+ raise ValueError("--total-workers must be a positive integer.")
137
+
138
+ # --- Command Construction ---
139
+ cmd = ["cnmf", "factorize"]
140
+ cmd.extend(["--output-dir", str(output_dir)])
141
+ cmd.extend(["--name", name])
142
+
143
+ if worker_index is not None:
144
+ cmd.extend(["--worker-index", str(worker_index)])
145
+ if total_workers is not None:
146
+ cmd.extend(["--total-workers", str(total_workers)])
147
+ if skip_completed_runs:
148
+ cmd.append("--skip-completed-runs")
149
+
150
+ # --- Subprocess Execution ---
151
+ try:
152
+ process = subprocess.run(
153
+ cmd,
154
+ capture_output=True,
155
+ text=True,
156
+ check=True,
157
+ )
158
+ except FileNotFoundError:
159
+ return {
160
+ "command_executed": shlex.join(cmd),
161
+ "stdout": "",
162
+ "stderr": "Error: 'cnmf' command not found. Please ensure it is in your PATH.",
163
+ "output_files": []
164
+ }
165
+ except subprocess.CalledProcessError as e:
166
+ return {
167
+ "command_executed": shlex.join(cmd),
168
+ "stdout": e.stdout,
169
+ "stderr": e.stderr,
170
+ "output_files": []
171
+ }
172
+
173
+ # --- Structured Result Return ---
174
+ # Factorize populates the directory created by 'prepare'.
175
+ output_path = output_dir / name
176
+ return {
177
+ "command_executed": shlex.join(cmd),
178
+ "stdout": process.stdout,
179
+ "stderr": process.stderr,
180
+ "output_files": [str(output_path)]
181
+ }
182
+
183
+
184
+ # @mcp.tool()
185
+ def cnmf_combine(
186
+ name: str,
187
+ output_dir: Path,
188
+ ) -> dict:
189
+ """
190
+ Combines the factorization results from multiple workers into a single file.
191
+ """
192
+ # --- Command Construction ---
193
+ cmd = ["cnmf", "combine"]
194
+ cmd.extend(["--output-dir", str(output_dir)])
195
+ cmd.extend(["--name", name])
196
+
197
+ # --- Subprocess Execution ---
198
+ try:
199
+ process = subprocess.run(
200
+ cmd,
201
+ capture_output=True,
202
+ text=True,
203
+ check=True,
204
+ )
205
+ except FileNotFoundError:
206
+ return {
207
+ "command_executed": shlex.join(cmd),
208
+ "stdout": "",
209
+ "stderr": "Error: 'cnmf' command not found. Please ensure it is in your PATH.",
210
+ "output_files": []
211
+ }
212
+ except subprocess.CalledProcessError as e:
213
+ return {
214
+ "command_executed": shlex.join(cmd),
215
+ "stdout": e.stdout,
216
+ "stderr": e.stderr,
217
+ "output_files": []
218
+ }
219
+
220
+ # --- Structured Result Return ---
221
+ # Combine creates merged files within the main output directory.
222
+ output_path = output_dir / name
223
+ return {
224
+ "command_executed": shlex.join(cmd),
225
+ "stdout": process.stdout,
226
+ "stderr": process.stderr,
227
+ "output_files": [str(output_path)]
228
+ }
229
+
230
+
231
+ # @mcp.tool()
232
+ def cnmf_consensus(
233
+ name: str,
234
+ output_dir: Path,
235
+ local_density_threshold: Optional[float] = None,
236
+ local_neighborhood_size: Optional[float] = None,
237
+ show_clustering: bool = False,
238
+ build_reference: bool = False,
239
+ ) -> dict:
240
+ """
241
+ Performs consensus clustering and filtering on the factorization results.
242
+ """
243
+ # --- Input Validation ---
244
+ if local_density_threshold is not None:
245
+ if not (0 < local_density_threshold <= 2):
246
+ raise ValueError("--local-density-threshold must be a float > 0 and <= 2.")
247
+ if local_neighborhood_size is not None and not (0 < local_neighborhood_size <= 1):
248
+ raise ValueError("--local-neighborhood-size must be a float > 0 and <= 1.")
249
+
250
+ # --- Command Construction ---
251
+ cmd = ["cnmf", "consensus"]
252
+ cmd.extend(["--output-dir", str(output_dir)])
253
+ cmd.extend(["--name", name])
254
+
255
+ if local_density_threshold is not None:
256
+ cmd.extend(["--local-density-threshold", str(local_density_threshold)])
257
+ if local_neighborhood_size is not None:
258
+ cmd.extend(["--local-neighborhood-size", str(local_neighborhood_size)])
259
+ if show_clustering:
260
+ cmd.append("--show-clustering")
261
+ if build_reference:
262
+ cmd.append("--build-reference")
263
+
264
+ # --- Subprocess Execution ---
265
+ try:
266
+ process = subprocess.run(
267
+ cmd,
268
+ capture_output=True,
269
+ text=True,
270
+ check=True,
271
+ )
272
+ except FileNotFoundError:
273
+ return {
274
+ "command_executed": shlex.join(cmd),
275
+ "stdout": "",
276
+ "stderr": "Error: 'cnmf' command not found. Please ensure it is in your PATH.",
277
+ "output_files": []
278
+ }
279
+ except subprocess.CalledProcessError as e:
280
+ return {
281
+ "command_executed": shlex.join(cmd),
282
+ "stdout": e.stdout,
283
+ "stderr": e.stderr,
284
+ "output_files": []
285
+ }
286
+
287
+ # --- Structured Result Return ---
288
+ output_path = output_dir / name
289
+ outputs = [str(output_path)]
290
+ # Assuming standard output file names for optional plots
291
+ if show_clustering:
292
+ outputs.append(str(output_path / f"{name}.clustering.pdf"))
293
+
294
+ return {
295
+ "command_executed": shlex.join(cmd),
296
+ "stdout": process.stdout,
297
+ "stderr": process.stderr,
298
+ "output_files": outputs
299
+ }
300
+
301
+
302
+ # @mcp.tool()
303
+ def cnmf_k_selection_plot(
304
+ name: str,
305
+ output_dir: Path,
306
+ ) -> dict:
307
+ """
308
+ Generates plots to help select the number of components (K).
309
+ """
310
+ # --- Command Construction ---
311
+ cmd = ["cnmf", "k_selection_plot"]
312
+ cmd.extend(["--output-dir", str(output_dir)])
313
+ cmd.extend(["--name", name])
314
+
315
+ # --- Subprocess Execution ---
316
+ try:
317
+ process = subprocess.run(
318
+ cmd,
319
+ capture_output=True,
320
+ text=True,
321
+ check=True,
322
+ )
323
+ except FileNotFoundError:
324
+ return {
325
+ "command_executed": shlex.join(cmd),
326
+ "stdout": "",
327
+ "stderr": "Error: 'cnmf' command not found. Please ensure it is in your PATH.",
328
+ "output_files": []
329
+ }
330
+ except subprocess.CalledProcessError as e:
331
+ return {
332
+ "command_executed": shlex.join(cmd),
333
+ "stdout": e.stdout,
334
+ "stderr": e.stderr,
335
+ "output_files": []
336
+ }
337
+
338
+ # --- Structured Result Return ---
339
+ output_path = output_dir / name
340
+ # Assuming a standard output file name for the plot
341
+ plot_file = output_path / f"{name}.k_selection.pdf"
342
+
343
+ return {
344
+ "command_executed": shlex.join(cmd),
345
+ "stdout": process.stdout,
346
+ "stderr": process.stderr,
347
+ "output_files": [str(plot_file)]
348
+ }
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cnmf/app/cnmf_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_help_txt/mcp_cnmf/app/cnmf_server.py')
11
+ SERVER_NAME = 'biosci_cnmf'
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_help_txt/mcp_cnmf/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-cnmf:
5
+ build: .
6
+ image: mcp-cnmf:latest
7
+ container_name: mcp-cnmf
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=cnmf
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_help_txt/mcp_cnmf/environment.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ name: mcp-tool
3
+ channels:
4
+ - bioconda
5
+ - conda-forge
6
+ - defaults
7
+ dependencies:
8
+ - cnmf
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cnmf/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_csvtk/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 csvtk via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda csvtk -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/csvtk_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/csvtk_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/csvtk_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_csvtk/app/csvtk_server.py ADDED
@@ -0,0 +1,548 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ from pathlib import Path
3
+ from typing import List, Optional, Dict, Any
4
+
5
+ def _execute_csvtk(
6
+ subcommand: str,
7
+ args: List[str],
8
+ in_file: Optional[str] = None,
9
+ tabs: bool = False,
10
+ no_header_row: bool = False,
11
+ comment_char: str = "#",
12
+ ignore_illegal_row: bool = False,
13
+ ignore_empty_row: bool = False,
14
+ lazy_quotes: bool = False,
15
+ out_tabs: bool = False,
16
+ out_file: str = "-",
17
+ num_cpus: int = 4,
18
+ ) -> Dict[str, Any]:
19
+ """Helper function to execute csvtk commands with global flags."""
20
+ cmd = ["csvtk", subcommand]
21
+
22
+ # Global flags
23
+ if tabs:
24
+ cmd.append("-t")
25
+ if no_header_row:
26
+ cmd.append("-H")
27
+ if comment_char != "#":
28
+ cmd.extend(["-C", comment_char])
29
+ if ignore_illegal_row:
30
+ cmd.append("-I")
31
+ if ignore_empty_row:
32
+ cmd.append("-E")
33
+ if lazy_quotes:
34
+ cmd.append("-l")
35
+ if out_tabs:
36
+ cmd.append("-T")
37
+ if out_file != "-":
38
+ cmd.extend(["-o", out_file])
39
+
40
+ cmd.extend(["-j", str(num_cpus)])
41
+
42
+ # Subcommand specific args
43
+ cmd.extend(args)
44
+
45
+ # Input file
46
+ if in_file and in_file != "-":
47
+ input_path = Path(in_file)
48
+ if not input_path.exists():
49
+ raise FileNotFoundError(f"Input file not found: {in_file}")
50
+ cmd.append(in_file)
51
+
52
+ try:
53
+ result = subprocess.run(cmd, capture_output=True, text=True, check=True)
54
+ return {
55
+ "command_executed": " ".join(cmd),
56
+ "stdout": result.stdout,
57
+ "stderr": result.stderr,
58
+ "output_files": [out_file] if out_file != "-" else []
59
+ }
60
+ except subprocess.CalledProcessError as e:
61
+ return {
62
+ "command_executed": " ".join(cmd),
63
+ "stdout": e.stdout,
64
+ "stderr": e.stderr,
65
+ "error": str(e)
66
+ }
67
+
68
+ @mcp.tool()
69
+ def csvtk_headers(
70
+ in_file: str,
71
+ tabs: bool = False,
72
+ no_header_row: bool = False,
73
+ ) -> Dict[str, Any]:
74
+ """Print headers of a CSV/TSV file."""
75
+ return _execute_csvtk("headers", [], in_file=in_file, tabs=tabs, no_header_row=no_header_row)
76
+
77
+ @mcp.tool()
78
+ def csvtk_dim(
79
+ in_file: str,
80
+ tabs: bool = False,
81
+ no_header_row: bool = False,
82
+ ) -> Dict[str, Any]:
83
+ """Dimensions of CSV file (rows and columns)."""
84
+ return _execute_csvtk("dim", [], in_file=in_file, tabs=tabs, no_header_row=no_header_row)
85
+
86
+ @mcp.tool()
87
+ def csvtk_ncol(
88
+ in_file: str,
89
+ tabs: bool = False,
90
+ ) -> Dict[str, Any]:
91
+ """Print number of columns."""
92
+ return _execute_csvtk("ncol", [], in_file=in_file, tabs=tabs)
93
+
94
+ @mcp.tool()
95
+ def csvtk_nrow(
96
+ in_file: str,
97
+ tabs: bool = False,
98
+ no_header_row: bool = False,
99
+ ) -> Dict[str, Any]:
100
+ """Print number of records (rows)."""
101
+ return _execute_csvtk("nrow", [], in_file=in_file, tabs=tabs, no_header_row=no_header_row)
102
+
103
+ @mcp.tool()
104
+ def csvtk_corr(
105
+ in_file: str,
106
+ fields: str,
107
+ tabs: bool = False,
108
+ ignore_illegal_row: bool = False,
109
+ ) -> Dict[str, Any]:
110
+ """Calculate Pearson correlation between two columns."""
111
+ return _execute_csvtk("corr", ["-f", fields], in_file=in_file, tabs=tabs, ignore_illegal_row=ignore_illegal_row)
112
+
113
+ @mcp.tool()
114
+ def csvtk_summary(
115
+ in_file: str,
116
+ fields: str,
117
+ groups: str = "",
118
+ tabs: bool = False,
119
+ no_header_row: bool = False,
120
+ ) -> Dict[str, Any]:
121
+ """Summary statistics of selected numeric or text fields (groupby group fields).
122
+ Fields format: col:stats (e.g., price:sum,price:mean).
123
+ """
124
+ args = ["-f", fields]
125
+ if groups:
126
+ args.extend(["-g", groups])
127
+ return _execute_csvtk("summary", args, in_file=in_file, tabs=tabs, no_header_row=no_header_row)
128
+
129
+ @mcp.tool()
130
+ def csvtk_cut(
131
+ in_file: str,
132
+ fields: str,
133
+ tabs: bool = False,
134
+ no_header_row: bool = False,
135
+ out_file: str = "-",
136
+ ) -> Dict[str, Any]:
137
+ """Select and arrange fields/columns."""
138
+ return _execute_csvtk("cut", ["-f", fields], in_file=in_file, tabs=tabs, no_header_row=no_header_row, out_file=out_file)
139
+
140
+ @mcp.tool()
141
+ def csvtk_grep(
142
+ in_file: str,
143
+ fields: str,
144
+ pattern: str,
145
+ ignore_case: bool = False,
146
+ invert_match: bool = False,
147
+ use_regexp: bool = False,
148
+ tabs: bool = False,
149
+ no_header_row: bool = False,
150
+ out_file: str = "-",
151
+ ) -> Dict[str, Any]:
152
+ """Grep data by selected fields with patterns/regular expressions."""
153
+ args = ["-f", fields, "-p", pattern]
154
+ if ignore_case:
155
+ args.append("-i")
156
+ if invert_match:
157
+ args.append("-v")
158
+ if use_regexp:
159
+ args.append("-r")
160
+ return _execute_csvtk("grep", args, in_file=in_file, tabs=tabs, no_header_row=no_header_row, out_file=out_file)
161
+
162
+ @mcp.tool()
163
+ def csvtk_filter(
164
+ in_file: str,
165
+ filter_expr: str,
166
+ tabs: bool = False,
167
+ no_header_row: bool = False,
168
+ out_file: str = "-",
169
+ ) -> Dict[str, Any]:
170
+ """Filter rows by values of selected fields with arithmetic expression (e.g., "col1 > 10")."""
171
+ return _execute_csvtk("filter", ["-f", filter_expr], in_file=in_file, tabs=tabs, no_header_row=no_header_row, out_file=out_file)
172
+
173
+ @mcp.tool()
174
+ def csvtk_filter2(
175
+ in_file: str,
176
+ expression: str,
177
+ tabs: bool = False,
178
+ no_header_row: bool = False,
179
+ out_file: str = "-",
180
+ ) -> Dict[str, Any]:
181
+ """Filter rows by awk-like arithmetic/string expressions (e.g., '$1 > 10 && $2 == "A"')."""
182
+ return _execute_csvtk("filter2", ["-f", expression], in_file=in_file, tabs=tabs, no_header_row=no_header_row, out_file=out_file)
183
+
184
+ @mcp.tool()
185
+ def csvtk_sort(
186
+ in_file: str,
187
+ keys: str,
188
+ tabs: bool = False,
189
+ no_header_row: bool = False,
190
+ out_file: str = "-",
191
+ ) -> Dict[str, Any]:
192
+ """Sort by selected fields. Keys format: 1:n (numeric), 2:r (reverse)."""
193
+ return _execute_csvtk("sort", ["-k", keys], in_file=in_file, tabs=tabs, no_header_row=no_header_row, out_file=out_file)
194
+
195
+ @mcp.tool()
196
+ def csvtk_join(
197
+ file1: str,
198
+ file2: str,
199
+ fields: str,
200
+ left_join: bool = False,
201
+ outer_join: bool = False,
202
+ tabs: bool = False,
203
+ no_header_row: bool = False,
204
+ out_file: str = "-",
205
+ ) -> Dict[str, Any]:
206
+ """Join files by selected fields."""
207
+ args = ["-f", fields]
208
+ if left_join:
209
+ args.append("--left-join")
210
+ if outer_join:
211
+ args.append("--outer-join")
212
+ args.append(file2)
213
+ return _execute_csvtk("join", args, in_file=file1, tabs=tabs, no_header_row=no_header_row, out_file=out_file)
214
+
215
+ @mcp.tool()
216
+ def csvtk_concat(
217
+ files: List[str],
218
+ tabs: bool = False,
219
+ no_header_row: bool = False,
220
+ out_file: str = "-",
221
+ ) -> Dict[str, Any]:
222
+ """Concatenate CSV/TSV files by rows."""
223
+ return _execute_csvtk("concat", files, tabs=tabs, no_header_row=no_header_row, out_file=out_file)
224
+
225
+ @mcp.tool()
226
+ def csvtk_uniq(
227
+ in_file: str,
228
+ fields: str,
229
+ tabs: bool = False,
230
+ no_header_row: bool = False,
231
+ out_file: str = "-",
232
+ ) -> Dict[str, Any]:
233
+ """Unique data without sorting."""
234
+ return _execute_csvtk("uniq", ["-f", fields], in_file=in_file, tabs=tabs, no_header_row=no_header_row, out_file=out_file)
235
+
236
+ @mcp.tool()
237
+ def csvtk_freq(
238
+ in_file: str,
239
+ fields: str,
240
+ sort_by_freq: bool = False,
241
+ tabs: bool = False,
242
+ no_header_row: bool = False,
243
+ out_file: str = "-",
244
+ ) -> Dict[str, Any]:
245
+ """Frequencies of selected fields."""
246
+ args = ["-f", fields]
247
+ if sort_by_freq:
248
+ args.extend(["-n", "-r"])
249
+ return _execute_csvtk("freq", args, in_file=in_file, tabs=tabs, no_header_row=no_header_row, out_file=out_file)
250
+
251
+ @mcp.tool()
252
+ def csvtk_mutate(
253
+ in_file: str,
254
+ fields: str,
255
+ name: str,
256
+ pattern: str,
257
+ tabs: bool = False,
258
+ no_header_row: bool = False,
259
+ out_file: str = "-",
260
+ ) -> Dict[str, Any]:
261
+ """Create new column from selected fields by regular expression."""
262
+ args = ["-f", fields, "-n", name, "-p", pattern]
263
+ return _execute_csvtk("mutate", args, in_file=in_file, tabs=tabs, no_header_row=no_header_row, out_file=out_file)
264
+
265
+ @mcp.tool()
266
+ def csvtk_mutate2(
267
+ in_file: str,
268
+ name: str,
269
+ expression: str,
270
+ tabs: bool = False,
271
+ no_header_row: bool = False,
272
+ out_file: str = "-",
273
+ ) -> Dict[str, Any]:
274
+ """Create a new column from selected fields by awk-like arithmetic/string expressions."""
275
+ args = ["-n", name, "-e", expression]
276
+ return _execute_csvtk("mutate2", args, in_file=in_file, tabs=tabs, no_header_row=no_header_row, out_file=out_file)
277
+
278
+ @mcp.tool()
279
+ def csvtk_rename(
280
+ in_file: str,
281
+ fields: str,
282
+ names: str,
283
+ tabs: bool = False,
284
+ no_header_row: bool = False,
285
+ out_file: str = "-",
286
+ ) -> Dict[str, Any]:
287
+ """Rename column names with new names."""
288
+ args = ["-f", fields, "-n", names]
289
+ return _execute_csvtk("rename", args, in_file=in_file, tabs=tabs, no_header_row=no_header_row, out_file=out_file)
290
+
291
+ @mcp.tool()
292
+ def csvtk_replace(
293
+ in_file: str,
294
+ fields: str,
295
+ pattern: str,
296
+ replacement: str,
297
+ tabs: bool = False,
298
+ no_header_row: bool = False,
299
+ out_file: str = "-",
300
+ ) -> Dict[str, Any]:
301
+ """Replace data of selected fields by regular expression."""
302
+ args = ["-f", fields, "-p", pattern, "-r", replacement]
303
+ return _execute_csvtk("replace", args, in_file=in_file, tabs=tabs, no_header_row=no_header_row, out_file=out_file)
304
+
305
+ @mcp.tool()
306
+ def csvtk_round(
307
+ in_file: str,
308
+ fields: str,
309
+ decimal_places: int = 2,
310
+ tabs: bool = False,
311
+ no_header_row: bool = False,
312
+ out_file: str = "-",
313
+ ) -> Dict[str, Any]:
314
+ """Round float to n decimal places."""
315
+ args = ["-f", fields, "-n", str(decimal_places)]
316
+ return _execute_csvtk("round", args, in_file=in_file, tabs=tabs, no_header_row=no_header_row, out_file=out_file)
317
+
318
+ @mcp.tool()
319
+ def csvtk_transpose(
320
+ in_file: str,
321
+ tabs: bool = False,
322
+ no_header_row: bool = False,
323
+ out_file: str = "-",
324
+ ) -> Dict[str, Any]:
325
+ """Transpose CSV data."""
326
+ return _execute_csvtk("transpose", [], in_file=in_file, tabs=tabs, no_header_row=no_header_row, out_file=out_file)
327
+
328
+ @mcp.tool()
329
+ def csvtk_sep(
330
+ in_file: str,
331
+ fields: str,
332
+ sep_char: str,
333
+ names: str,
334
+ tabs: bool = False,
335
+ no_header_row: bool = False,
336
+ out_file: str = "-",
337
+ ) -> Dict[str, Any]:
338
+ """Separate column into multiple columns."""
339
+ args = ["-f", fields, "-s", sep_char, "-n", names]
340
+ return _execute_csvtk("sep", args, in_file=in_file, tabs=tabs, no_header_row=no_header_row, out_file=out_file)
341
+
342
+ @mcp.tool()
343
+ def csvtk_gather(
344
+ in_file: str,
345
+ key_col: str,
346
+ value_col: str,
347
+ fields: str,
348
+ tabs: bool = False,
349
+ no_header_row: bool = False,
350
+ out_file: str = "-",
351
+ ) -> Dict[str, Any]:
352
+ """Gather columns into key-value pairs (pivot_longer)."""
353
+ args = ["-k", key_col, "-v", value_col, "-f", fields]
354
+ return _execute_csvtk("gather", args, in_file=in_file, tabs=tabs, no_header_row=no_header_row, out_file=out_file)
355
+
356
+ @mcp.tool()
357
+ def csvtk_spread(
358
+ in_file: str,
359
+ key_col: str,
360
+ value_col: str,
361
+ tabs: bool = False,
362
+ no_header_row: bool = False,
363
+ out_file: str = "-",
364
+ ) -> Dict[str, Any]:
365
+ """Spread a key-value pair across multiple columns (pivot_wider)."""
366
+ args = ["-k", key_col, "-v", value_col]
367
+ return _execute_csvtk("spread", args, in_file=in_file, tabs=tabs, no_header_row=no_header_row, out_file=out_file)
368
+
369
+ @mcp.tool()
370
+ def csvtk_pretty(
371
+ in_file: str,
372
+ tabs: bool = False,
373
+ no_header_row: bool = False,
374
+ ) -> Dict[str, Any]:
375
+ """Convert CSV to a readable aligned table."""
376
+ return _execute_csvtk("pretty", [], in_file=in_file, tabs=tabs, no_header_row=no_header_row)
377
+
378
+ @mcp.tool()
379
+ def csvtk_csv2md(
380
+ in_file: str,
381
+ tabs: bool = False,
382
+ no_header_row: bool = False,
383
+ ) -> Dict[str, Any]:
384
+ """Convert CSV to markdown format."""
385
+ return _execute_csvtk("csv2md", [], in_file=in_file, tabs=tabs, no_header_row=no_header_row)
386
+
387
+ @mcp.tool()
388
+ def csvtk_csv2json(
389
+ in_file: str,
390
+ tabs: bool = False,
391
+ no_header_row: bool = False,
392
+ out_file: str = "-",
393
+ ) -> Dict[str, Any]:
394
+ """Convert CSV to JSON format."""
395
+ return _execute_csvtk("csv2json", [], in_file=in_file, tabs=tabs, no_header_row=no_header_row, out_file=out_file)
396
+
397
+ @mcp.tool()
398
+ def csvtk_xlsx2csv(
399
+ in_file: str,
400
+ sheet_index: int = 1,
401
+ sheet_name: str = "",
402
+ out_file: str = "-",
403
+ ) -> Dict[str, Any]:
404
+ """Convert XLSX to CSV format."""
405
+ args = []
406
+ if sheet_name:
407
+ args.extend(["-n", sheet_name])
408
+ else:
409
+ args.extend(["-i", str(sheet_index)])
410
+ return _execute_csvtk("xlsx2csv", args, in_file=in_file, out_file=out_file)
411
+
412
+ @mcp.tool()
413
+ def csvtk_fix(
414
+ in_file: str,
415
+ tabs: bool = False,
416
+ out_file: str = "-",
417
+ ) -> Dict[str, Any]:
418
+ """Fix CSV/TSV with different numbers of columns in rows."""
419
+ return _execute_csvtk("fix", [], in_file=in_file, tabs=tabs, out_file=out_file)
420
+
421
+ @mcp.tool()
422
+ def csvtk_fix_quotes(
423
+ in_file: str,
424
+ tabs: bool = False,
425
+ out_file: str = "-",
426
+ ) -> Dict[str, Any]:
427
+ """Fix malformed CSV/TSV caused by double-quotes."""
428
+ return _execute_csvtk("fix-quotes", [], in_file=in_file, tabs=tabs, out_file=out_file)
429
+
430
+ @mcp.tool()
431
+ def csvtk_del_quotes(
432
+ in_file: str,
433
+ tabs: bool = False,
434
+ out_file: str = "-",
435
+ ) -> Dict[str, Any]:
436
+ """Remove extra double quotes added by 'fix-quotes'."""
437
+ return _execute_csvtk("del-quotes", [], in_file=in_file, tabs=tabs, out_file=out_file)
438
+
439
+ @mcp.tool()
440
+ def csvtk_head(
441
+ in_file: str,
442
+ number: int = 10,
443
+ tabs: bool = False,
444
+ no_header_row: bool = False,
445
+ out_file: str = "-",
446
+ ) -> Dict[str, Any]:
447
+ """Print first N records."""
448
+ return _execute_csvtk("head", ["-n", str(number)], in_file=in_file, tabs=tabs, no_header_row=no_header_row, out_file=out_file)
449
+
450
+ @mcp.tool()
451
+ def csvtk_sample(
452
+ in_file: str,
453
+ proportion: float = 0.1,
454
+ tabs: bool = False,
455
+ no_header_row: bool = False,
456
+ out_file: str = "-",
457
+ ) -> Dict[str, Any]:
458
+ """Sampling by proportion."""
459
+ return _execute_csvtk("sample", ["-p", str(proportion)], in_file=in_file, tabs=tabs, no_header_row=no_header_row, out_file=out_file)
460
+
461
+ @mcp.tool()
462
+ def csvtk_split(
463
+ in_file: str,
464
+ fields: str,
465
+ out_dir: str = ".",
466
+ tabs: bool = False,
467
+ no_header_row: bool = False,
468
+ ) -> Dict[str, Any]:
469
+ """Split CSV/TSV into multiple files according to column values."""
470
+ args = ["-f", fields, "-out-dir", out_dir]
471
+ return _execute_csvtk("split", args, in_file=in_file, tabs=tabs, no_header_row=no_header_row)
472
+
473
+ @mcp.tool()
474
+ def csvtk_comb(
475
+ in_file: str,
476
+ fields: str,
477
+ number: int = 2,
478
+ tabs: bool = False,
479
+ no_header_row: bool = False,
480
+ out_file: str = "-",
481
+ ) -> Dict[str, Any]:
482
+ """Compute combinations of items at every row."""
483
+ args = ["-f", fields, "-n", str(number)]
484
+ return _execute_csvtk("comb", args, in_file=in_file, tabs=tabs, no_header_row=no_header_row, out_file=out_file)
485
+
486
+ @mcp.tool()
487
+ def csvtk_fmtdate(
488
+ in_file: str,
489
+ fields: str,
490
+ format_str: str,
491
+ tabs: bool = False,
492
+ no_header_row: bool = False,
493
+ out_file: str = "-",
494
+ ) -> Dict[str, Any]:
495
+ """Format date of selected fields."""
496
+ args = ["-f", fields, "--format", format_str]
497
+ return _execute_csvtk("fmtdate", args, in_file=in_file, tabs=tabs, no_header_row=no_header_row, out_file=out_file)
498
+
499
+ @mcp.tool()
500
+ def csvtk_fold(
501
+ in_file: str,
502
+ fields: str,
503
+ groups: str = "",
504
+ tabs: bool = False,
505
+ no_header_row: bool = False,
506
+ out_file: str = "-",
507
+ ) -> Dict[str, Any]:
508
+ """Fold multiple values of a field into cells of groups."""
509
+ args = ["-f", fields]
510
+ if groups:
511
+ args.extend(["-g", groups])
512
+ return _execute_csvtk("fold", args, in_file=in_file, tabs=tabs, no_header_row=no_header_row, out_file=out_file)
513
+
514
+ @mcp.tool()
515
+ def csvtk_unfold(
516
+ in_file: str,
517
+ fields: str,
518
+ sep_char: str = ",",
519
+ tabs: bool = False,
520
+ no_header_row: bool = False,
521
+ out_file: str = "-",
522
+ ) -> Dict[str, Any]:
523
+ """Unfold multiple values in cells of a field."""
524
+ args = ["-f", fields, "-s", sep_char]
525
+ return _execute_csvtk("unfold", args, in_file=in_file, tabs=tabs, no_header_row=no_header_row, out_file=out_file)
526
+
527
+ @mcp.tool()
528
+ def csvtk_plot(
529
+ in_file: str,
530
+ plot_type: str,
531
+ x_field: str,
532
+ y_field: str = "",
533
+ title: str = "",
534
+ tabs: bool = False,
535
+ out_file: str = "plot.png",
536
+ ) -> Dict[str, Any]:
537
+ """Plot common figures (line, hist, box, etc.)."""
538
+ args = [plot_type, "-x", x_field]
539
+ if y_field:
540
+ args.extend(["-y", y_field])
541
+ if title:
542
+ args.extend(["--title", title])
543
+ return _execute_csvtk("plot", args, in_file=in_file, tabs=tabs, out_file=out_file)
544
+
545
+ @mcp.tool()
546
+ def csvtk_version() -> Dict[str, Any]:
547
+ """Print version information."""
548
+ return _execute_csvtk("version", [])
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_csvtk/app/csvtk_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_help_txt/mcp_csvtk/app/csvtk_server.py')
11
+ SERVER_NAME = 'biosci_csvtk'
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_help_txt/mcp_csvtk/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_csvtk/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-csvtk:
5
+ build: .
6
+ image: mcp-csvtk:latest
7
+ container_name: mcp-csvtk
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=csvtk
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_help_txt/mcp_csvtk/environment.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ name: mcp-tool
3
+ channels:
4
+ - bioconda
5
+ - conda-forge
6
+ - defaults
7
+ dependencies:
8
+ - csvtk
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_csvtk/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cytotrace2-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 cytotrace2-python via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda cytotrace2-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 cytotrace2-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/cytotrace2-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/cytotrace2-python_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cytotrace2-python/app/cytotrace2-python_server.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ from pathlib import Path
3
+ from typing import List, Optional, Dict, Any
4
+
5
+ # Assume mcp is imported elsewhere, as per instructions "NO NEED to import mcp"
6
+
7
+ @mcp.tool()
8
+ def run_rscript(
9
+ script_file: Optional[Path] = None,
10
+ expressions: Optional[List[str]] = None,
11
+ verbose: bool = False,
12
+ default_packages: Optional[str] = None,
13
+ save: bool = False,
14
+ no_environ: bool = False,
15
+ no_site_file: bool = False,
16
+ no_init_file: bool = False,
17
+ restore: bool = False,
18
+ vanilla: bool = False,
19
+ script_args: Optional[List[str]] = None,
20
+ ) -> Dict[str, Any]:
21
+ """
22
+ Executes an R script or R expressions using the Rscript command-line utility.
23
+
24
+ This tool provides an interface to the Rscript command, allowing users to run
25
+ R scripts or evaluate R expressions directly from the command line with
26
+ various R environment configuration options.
27
+
28
+ Args:
29
+ script_file: Path to the R script file (.R) to execute.
30
+ This parameter is mutually exclusive with 'expressions'.
31
+ If provided, the file must exist.
32
+ expressions: A list of R expressions (strings) to evaluate. Each string
33
+ in the list will be passed with a separate '-e' flag.
34
+ This parameter is mutually exclusive with 'script_file'.
35
+ verbose: If True, print information on R's progress during execution.
36
+ default_packages: A comma-separated list of package names (e.g., "stats,utils")
37
+ to load by default, or 'NULL' to load no default packages.
38
+ save: If True, save the R workspace at the end of the session.
39
+ no_environ: If True, do not read the site and user environment files.
40
+ no_site_file: If True, do not read the site-wide Rprofile.
41
+ no_init_file: If True, do not read the user R profile.
42
+ restore: If True, restore previously saved objects at startup.
43
+ vanilla: If True, combine --no-save, --no-restore, --no-site-file,
44
+ --no-init-file, and --no-environ. This option overrides
45
+ individual settings for these flags.
46
+ script_args: A list of additional arguments (strings) to pass directly
47
+ to the R script being executed. These arguments are accessible
48
+ within the R script via `commandArgs(trailingOnly=TRUE)`.
49
+
50
+ Returns:
51
+ A dictionary containing the command executed, standard output, standard error,
52
+ and a list of any output files generated (though Rscript itself doesn't
53
+ produce named output files unless specified within the R script).
54
+
55
+ Raises:
56
+ ValueError: If neither 'script_file' nor 'expressions' is provided,
57
+ or if both are provided.
58
+ FileNotFoundError: If 'script_file' is provided but the file does not exist.
59
+ """
60
+ # Input validation for mutually exclusive parameters
61
+ if script_file is None and expressions is None:
62
+ raise ValueError("Either 'script_file' or 'expressions' must be provided.")
63
+ if script_file is not None and expressions is not None:
64
+ raise ValueError("Cannot provide both 'script_file' and 'expressions'. Choose one.")
65
+
66
+ # Validate script_file existence if provided
67
+ if script_file:
68
+ if not script_file.is_file():
69
+ raise FileNotFoundError(f"R script file not found: {script_file}")
70
+ # Optional: Check for .R extension, though Rscript can run any file
71
+ if script_file.suffix.lower() != ".r":
72
+ print(f"Warning: Script file '{script_file}' does not have a '.R' extension. "
73
+ "Rscript will attempt to execute it regardless.")
74
+
75
+ command: List[str] = ["Rscript"]
76
+
77
+ # Add Rscript options
78
+ if verbose:
79
+ command.append("--verbose")
80
+ if default_packages is not None:
81
+ command.append(f"--default-packages={default_packages}")
82
+ if save:
83
+ command.append("--save")
84
+ if no_environ:
85
+ command.append("--no-environ")
86
+ if no_site_file:
87
+ command.append("--no-site-file")
88
+ if no_init_file:
89
+ command.append("--no-init-file")
90
+ if restore:
91
+ command.append("--restore")
92
+ if vanilla:
93
+ command.append("--vanilla")
94
+
95
+ # Add expressions or script file
96
+ if expressions:
97
+ for expr in expressions:
98
+ command.extend(["-e", expr])
99
+ elif script_file:
100
+ command.append(str(script_file))
101
+
102
+ # Add arguments to be passed to the R script
103
+ if script_args:
104
+ command.extend(script_args)
105
+
106
+ command_str = " ".join(command)
107
+ output_files: List[Path] = [] # Rscript itself doesn't produce standard output files.
108
+
109
+ try:
110
+ process = subprocess.run(
111
+ command,
112
+ capture_output=True,
113
+ text=True,
114
+ check=True,
115
+ encoding='utf-8'
116
+ )
117
+ stdout = process.stdout
118
+ stderr = process.stderr
119
+ except subprocess.CalledProcessError as e:
120
+ return {
121
+ "command_executed": command_str,
122
+ "stdout": e.stdout,
123
+ "stderr": e.stderr,
124
+ "error": f"Rscript execution failed with exit code {e.returncode}. "
125
+ f"Command: {command_str}",
126
+ "output_files": output_files,
127
+ }
128
+ except FileNotFoundError:
129
+ return {
130
+ "command_executed": command_str,
131
+ "stdout": "",
132
+ "stderr": "Rscript command not found. Please ensure R is installed and Rscript is in your system's PATH.",
133
+ "error": "Rscript executable not found.",
134
+ "output_files": output_files,
135
+ }
136
+ except Exception as e:
137
+ return {
138
+ "command_executed": command_str,
139
+ "stdout": "",
140
+ "stderr": str(e),
141
+ "error": f"An unexpected error occurred during Rscript execution: {e}",
142
+ "output_files": output_files,
143
+ }
144
+
145
+ return {
146
+ "command_executed": command_str,
147
+ "stdout": stdout,
148
+ "stderr": stderr,
149
+ "output_files": output_files,
150
+ }
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cytotrace2-python/app/cytotrace2-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_help_txt/mcp_cytotrace2-python/app/cytotrace2-python_server.py')
11
+ SERVER_NAME = 'biosci_cytotrace2_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_help_txt/mcp_cytotrace2-python/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-cytotrace2-python:
5
+ build: .
6
+ image: mcp-cytotrace2-python:latest
7
+ container_name: mcp-cytotrace2-python
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=cytotrace2-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_help_txt/mcp_cytotrace2-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
+ - cytotrace2-python
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_cytotrace2-python/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_decoupler/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 decoupler via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda decoupler -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 decoupler_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/decoupler_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/decoupler_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_decoupler/app/decoupler_server.py ADDED
@@ -0,0 +1,692 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import tempfile
3
+ from pathlib import Path
4
+ from typing import List, Literal, Optional
5
+
6
+ # Mock mcp decorator for standalone execution
7
+ class mcp:
8
+ @staticmethod
9
+ def tool(func):
10
+ return func
11
+
12
+ @mcp.tool
13
+ def decoupler_mlm(
14
+ mat: Path,
15
+ net: Path,
16
+ output: Path,
17
+ mat_source_col: str = 'genes',
18
+ mat_target_col: str = 'cells',
19
+ mat_value_col: str = 'expression',
20
+ net_source_col: str = 'tf',
21
+ net_target_col: str = 'target',
22
+ net_weight_col: str = 'weight',
23
+ min_n: int = 5,
24
+ batch_size: int = 10000,
25
+ verbose: bool = False,
26
+ ):
27
+ """
28
+ Runs transcription factor/pathway activities using the Multivariate Linear Model (mlm) method from decoupler.
29
+
30
+ This method is equivalent to the `run_mlm` function in the decoupler library.
31
+ It models the relationship between a set of regulators and their target features using a linear model.
32
+
33
+ Args:
34
+ mat: Path to the input matrix file (e.g., gene expression). Should be a long-format CSV/TSV.
35
+ net: Path to the input network file (e.g., TF-target interactions). Should be a long-format CSV/TSV.
36
+ output: Path to the output file where the inferred activities will be saved.
37
+ mat_source_col: Column name in the matrix file for the features (e.g., 'genes').
38
+ mat_target_col: Column name in the matrix file for the samples (e.g., 'cells').
39
+ mat_value_col: Column name in the matrix file for the values (e.g., 'expression').
40
+ net_source_col: Column name in the network file for the regulators (e.g., 'tf').
41
+ net_target_col: Column name in the network file for the targets (e.g., 'target').
42
+ net_weight_col: Column name in the network file for the interaction weights (e.g., 'weight').
43
+ min_n: Minimum number of targets per regulator in the network to be considered.
44
+ batch_size: Number of samples to process in each batch to manage memory usage.
45
+ verbose: If True, increases verbosity of the tool's output.
46
+ """
47
+ # Input validation
48
+ if not mat.is_file():
49
+ raise FileNotFoundError(f"Input matrix file not found: {mat}")
50
+ if not net.is_file():
51
+ raise FileNotFoundError(f"Input network file not found: {net}")
52
+ if min_n < 1:
53
+ raise ValueError("min_n must be a positive integer.")
54
+ if batch_size < 1:
55
+ raise ValueError("batch_size must be a positive integer.")
56
+
57
+ output.parent.mkdir(parents=True, exist_ok=True)
58
+
59
+ cmd = [
60
+ "python", "-m", "decoupler", "mlm",
61
+ "--mat", str(mat),
62
+ "--net", str(net),
63
+ "--output", str(output),
64
+ "--mat-source-col", mat_source_col,
65
+ "--mat-target-col", mat_target_col,
66
+ "--mat-value-col", mat_value_col,
67
+ "--net-source-col", net_source_col,
68
+ "--net-target-col", net_target_col,
69
+ "--net-weight-col", net_weight_col,
70
+ "--min-n", str(min_n),
71
+ "--batch-size", str(batch_size),
72
+ ]
73
+ if verbose:
74
+ cmd.append("--verbose")
75
+
76
+ try:
77
+ process = subprocess.run(
78
+ cmd,
79
+ capture_output=True,
80
+ text=True,
81
+ check=True,
82
+ )
83
+ except subprocess.CalledProcessError as e:
84
+ return {
85
+ "command_executed": " ".join(e.cmd),
86
+ "stdout": e.stdout,
87
+ "stderr": e.stderr,
88
+ "return_code": e.returncode,
89
+ "output_files": []
90
+ }
91
+
92
+ return {
93
+ "command_executed": " ".join(cmd),
94
+ "stdout": process.stdout,
95
+ "stderr": process.stderr,
96
+ "output_files": [str(output)]
97
+ }
98
+
99
+ @mcp.tool
100
+ def decoupler_ulm(
101
+ mat: Path,
102
+ net: Path,
103
+ output: Path,
104
+ mat_source_col: str = 'genes',
105
+ mat_target_col: str = 'cells',
106
+ mat_value_col: str = 'expression',
107
+ net_source_col: str = 'tf',
108
+ net_target_col: str = 'target',
109
+ net_weight_col: str = 'weight',
110
+ min_n: int = 5,
111
+ batch_size: int = 10000,
112
+ verbose: bool = False,
113
+ ):
114
+ """
115
+ Runs transcription factor/pathway activities using the Univariate Linear Model (ulm) method from decoupler.
116
+
117
+ This method is equivalent to the `run_ulm` function in the decoupler library.
118
+ It models the relationship between each regulator and its target features independently.
119
+
120
+ Args:
121
+ mat: Path to the input matrix file (e.g., gene expression). Should be a long-format CSV/TSV.
122
+ net: Path to the input network file (e.g., TF-target interactions). Should be a long-format CSV/TSV.
123
+ output: Path to the output file where the inferred activities will be saved.
124
+ mat_source_col: Column name in the matrix file for the features (e.g., 'genes').
125
+ mat_target_col: Column name in the matrix file for the samples (e.g., 'cells').
126
+ mat_value_col: Column name in the matrix file for the values (e.g., 'expression').
127
+ net_source_col: Column name in the network file for the regulators (e.g., 'tf').
128
+ net_target_col: Column name in the network file for the targets (e.g., 'target').
129
+ net_weight_col: Column name in the network file for the interaction weights (e.g., 'weight').
130
+ min_n: Minimum number of targets per regulator in the network to be considered.
131
+ batch_size: Number of samples to process in each batch to manage memory usage.
132
+ verbose: If True, increases verbosity of the tool's output.
133
+ """
134
+ # Input validation
135
+ if not mat.is_file():
136
+ raise FileNotFoundError(f"Input matrix file not found: {mat}")
137
+ if not net.is_file():
138
+ raise FileNotFoundError(f"Input network file not found: {net}")
139
+ if min_n < 1:
140
+ raise ValueError("min_n must be a positive integer.")
141
+ if batch_size < 1:
142
+ raise ValueError("batch_size must be a positive integer.")
143
+
144
+ output.parent.mkdir(parents=True, exist_ok=True)
145
+
146
+ cmd = [
147
+ "python", "-m", "decoupler", "ulm",
148
+ "--mat", str(mat),
149
+ "--net", str(net),
150
+ "--output", str(output),
151
+ "--mat-source-col", mat_source_col,
152
+ "--mat-target-col", mat_target_col,
153
+ "--mat-value-col", mat_value_col,
154
+ "--net-source-col", net_source_col,
155
+ "--net-target-col", net_target_col,
156
+ "--net-weight-col", net_weight_col,
157
+ "--min-n", str(min_n),
158
+ "--batch-size", str(batch_size),
159
+ ]
160
+ if verbose:
161
+ cmd.append("--verbose")
162
+
163
+ try:
164
+ process = subprocess.run(
165
+ cmd,
166
+ capture_output=True,
167
+ text=True,
168
+ check=True,
169
+ )
170
+ except subprocess.CalledProcessError as e:
171
+ return {
172
+ "command_executed": " ".join(e.cmd),
173
+ "stdout": e.stdout,
174
+ "stderr": e.stderr,
175
+ "return_code": e.returncode,
176
+ "output_files": []
177
+ }
178
+
179
+ return {
180
+ "command_executed": " ".join(cmd),
181
+ "stdout": process.stdout,
182
+ "stderr": process.stderr,
183
+ "output_files": [str(output)]
184
+ }
185
+
186
+ @mcp.tool
187
+ def decoupler_wsum(
188
+ mat: Path,
189
+ net: Path,
190
+ output: Path,
191
+ mat_source_col: str = 'genes',
192
+ mat_target_col: str = 'cells',
193
+ mat_value_col: str = 'expression',
194
+ net_source_col: str = 'tf',
195
+ net_target_col: str = 'target',
196
+ net_weight_col: str = 'weight',
197
+ min_n: int = 5,
198
+ batch_size: int = 10000,
199
+ nes: bool = False,
200
+ times: int = 100,
201
+ seed: int = 42,
202
+ verbose: bool = False,
203
+ ):
204
+ """
205
+ Runs transcription factor/pathway activities using the Weighted Sum (wsum) method from decoupler.
206
+
207
+ This method calculates scores by multiplying the feature matrix by the network matrix.
208
+ It can optionally compute a normalized enrichment score (NES) through permutations.
209
+
210
+ Args:
211
+ mat: Path to the input matrix file.
212
+ net: Path to the input network file.
213
+ output: Path to the output file.
214
+ mat_source_col: Column name for features in the matrix file.
215
+ mat_target_col: Column name for samples in the matrix file.
216
+ mat_value_col: Column name for values in the matrix file.
217
+ net_source_col: Column name for regulators in the network file.
218
+ net_target_col: Column name for targets in the network file.
219
+ net_weight_col: Column name for interaction weights in the network file.
220
+ min_n: Minimum number of targets per regulator.
221
+ batch_size: Number of samples to process per batch.
222
+ nes: If True, compute Normalized Enrichment Scores (NES) by permutation.
223
+ times: Number of permutations to perform if `nes` is True.
224
+ seed: Random seed for permutations.
225
+ verbose: If True, increases verbosity.
226
+ """
227
+ # Input validation
228
+ if not mat.is_file():
229
+ raise FileNotFoundError(f"Input matrix file not found: {mat}")
230
+ if not net.is_file():
231
+ raise FileNotFoundError(f"Input network file not found: {net}")
232
+ if min_n < 1:
233
+ raise ValueError("min_n must be a positive integer.")
234
+ if batch_size < 1:
235
+ raise ValueError("batch_size must be a positive integer.")
236
+ if times < 1:
237
+ raise ValueError("times must be a positive integer.")
238
+
239
+ output.parent.mkdir(parents=True, exist_ok=True)
240
+
241
+ cmd = [
242
+ "python", "-m", "decoupler", "wsum",
243
+ "--mat", str(mat),
244
+ "--net", str(net),
245
+ "--output", str(output),
246
+ "--mat-source-col", mat_source_col,
247
+ "--mat-target-col", mat_target_col,
248
+ "--mat-value-col", mat_value_col,
249
+ "--net-source-col", net_source_col,
250
+ "--net-target-col", net_target_col,
251
+ "--net-weight-col", net_weight_col,
252
+ "--min-n", str(min_n),
253
+ "--batch-size", str(batch_size),
254
+ "--times", str(times),
255
+ "--seed", str(seed),
256
+ ]
257
+ if nes:
258
+ cmd.append("--nes")
259
+ if verbose:
260
+ cmd.append("--verbose")
261
+
262
+ try:
263
+ process = subprocess.run(
264
+ cmd,
265
+ capture_output=True,
266
+ text=True,
267
+ check=True,
268
+ )
269
+ except subprocess.CalledProcessError as e:
270
+ return {
271
+ "command_executed": " ".join(e.cmd),
272
+ "stdout": e.stdout,
273
+ "stderr": e.stderr,
274
+ "return_code": e.returncode,
275
+ "output_files": []
276
+ }
277
+
278
+ return {
279
+ "command_executed": " ".join(cmd),
280
+ "stdout": process.stdout,
281
+ "stderr": process.stderr,
282
+ "output_files": [str(output)]
283
+ }
284
+
285
+ @mcp.tool
286
+ def decoupler_ora(
287
+ mat: Path,
288
+ net: Path,
289
+ output: Path,
290
+ mat_source_col: str = 'genes',
291
+ mat_target_col: str = 'cells',
292
+ mat_value_col: str = 'expression',
293
+ net_source_col: str = 'tf',
294
+ net_target_col: str = 'target',
295
+ net_weight_col: str = 'weight',
296
+ min_n: int = 5,
297
+ batch_size: int = 10000,
298
+ top: int = 100,
299
+ verbose: bool = False,
300
+ ):
301
+ """
302
+ Runs Over-Representation Analysis (ORA) using decoupler.
303
+
304
+ This method performs a statistical test (Fisher's exact test) to determine if a set of features
305
+ (e.g., differentially expressed genes) is enriched in a given pathway/regulon.
306
+
307
+ Args:
308
+ mat: Path to the input matrix file.
309
+ net: Path to the input network file.
310
+ output: Path to the output file.
311
+ mat_source_col: Column name for features in the matrix file.
312
+ mat_target_col: Column name for samples in the matrix file.
313
+ mat_value_col: Column name for values in the matrix file.
314
+ net_source_col: Column name for regulators in the network file.
315
+ net_target_col: Column name for targets in the network file.
316
+ net_weight_col: Column name for interaction weights in the network file.
317
+ min_n: Minimum number of targets per regulator.
318
+ batch_size: Number of samples to process per batch.
319
+ top: Number of top features from the matrix to use for the enrichment analysis.
320
+ verbose: If True, increases verbosity.
321
+ """
322
+ # Input validation
323
+ if not mat.is_file():
324
+ raise FileNotFoundError(f"Input matrix file not found: {mat}")
325
+ if not net.is_file():
326
+ raise FileNotFoundError(f"Input network file not found: {net}")
327
+ if min_n < 1:
328
+ raise ValueError("min_n must be a positive integer.")
329
+ if batch_size < 1:
330
+ raise ValueError("batch_size must be a positive integer.")
331
+ if top < 1:
332
+ raise ValueError("top must be a positive integer.")
333
+
334
+ output.parent.mkdir(parents=True, exist_ok=True)
335
+
336
+ cmd = [
337
+ "python", "-m", "decoupler", "ora",
338
+ "--mat", str(mat),
339
+ "--net", str(net),
340
+ "--output", str(output),
341
+ "--mat-source-col", mat_source_col,
342
+ "--mat-target-col", mat_target_col,
343
+ "--mat-value-col", mat_value_col,
344
+ "--net-source-col", net_source_col,
345
+ "--net-target-col", net_target_col,
346
+ "--net-weight-col", net_weight_col,
347
+ "--min-n", str(min_n),
348
+ "--batch-size", str(batch_size),
349
+ "--top", str(top),
350
+ ]
351
+ if verbose:
352
+ cmd.append("--verbose")
353
+
354
+ try:
355
+ process = subprocess.run(
356
+ cmd,
357
+ capture_output=True,
358
+ text=True,
359
+ check=True,
360
+ )
361
+ except subprocess.CalledProcessError as e:
362
+ return {
363
+ "command_executed": " ".join(e.cmd),
364
+ "stdout": e.stdout,
365
+ "stderr": e.stderr,
366
+ "return_code": e.returncode,
367
+ "output_files": []
368
+ }
369
+
370
+ return {
371
+ "command_executed": " ".join(cmd),
372
+ "stdout": process.stdout,
373
+ "stderr": process.stderr,
374
+ "output_files": [str(output)]
375
+ }
376
+
377
+ @mcp.tool
378
+ def decoupler_gsva(
379
+ mat: Path,
380
+ net: Path,
381
+ output: Path,
382
+ mat_source_col: str = 'genes',
383
+ mat_target_col: str = 'cells',
384
+ mat_value_col: str = 'expression',
385
+ net_source_col: str = 'tf',
386
+ net_target_col: str = 'target',
387
+ net_weight_col: str = 'weight',
388
+ min_n: int = 5,
389
+ batch_size: int = 10000,
390
+ mx_diff: bool = True,
391
+ abs_ranking: bool = False,
392
+ min_sz: int = 5,
393
+ max_sz: int = 500,
394
+ kcdf: Literal['Gaussian', 'Poisson'] = 'Gaussian',
395
+ seed: int = 42,
396
+ verbose: bool = False,
397
+ ):
398
+ """
399
+ Runs Gene Set Variation Analysis (GSVA) using decoupler.
400
+
401
+ GSVA estimates variation of pathway activity over a sample population in an unsupervised manner.
402
+
403
+ Args:
404
+ mat: Path to the input matrix file.
405
+ net: Path to the input network file.
406
+ output: Path to the output file.
407
+ mat_source_col: Column name for features in the matrix file.
408
+ mat_target_col: Column name for samples in the matrix file.
409
+ mat_value_col: Column name for values in the matrix file.
410
+ net_source_col: Column name for regulators in the network file.
411
+ net_target_col: Column name for targets in the network file.
412
+ net_weight_col: Column name for interaction weights in the network file.
413
+ min_n: Minimum number of targets per regulator.
414
+ batch_size: Number of samples to process per batch.
415
+ mx_diff: The maximum absolute difference between the minimum and maximum.
416
+ abs_ranking: If True, gene expression values are ranked by their absolute values.
417
+ min_sz: Minimum size of a gene set to be considered.
418
+ max_sz: Maximum size of a gene set to be considered.
419
+ kcdf: Kernel cumulative distribution function to use.
420
+ seed: Random seed.
421
+ verbose: If True, increases verbosity.
422
+ """
423
+ # Input validation
424
+ if not mat.is_file():
425
+ raise FileNotFoundError(f"Input matrix file not found: {mat}")
426
+ if not net.is_file():
427
+ raise FileNotFoundError(f"Input network file not found: {net}")
428
+ if min_n < 1:
429
+ raise ValueError("min_n must be a positive integer.")
430
+ if batch_size < 1:
431
+ raise ValueError("batch_size must be a positive integer.")
432
+ if min_sz < 1:
433
+ raise ValueError("min_sz must be a positive integer.")
434
+ if max_sz < min_sz:
435
+ raise ValueError("max_sz must be greater than or equal to min_sz.")
436
+
437
+ output.parent.mkdir(parents=True, exist_ok=True)
438
+
439
+ cmd = [
440
+ "python", "-m", "decoupler", "gsva",
441
+ "--mat", str(mat),
442
+ "--net", str(net),
443
+ "--output", str(output),
444
+ "--mat-source-col", mat_source_col,
445
+ "--mat-target-col", mat_target_col,
446
+ "--mat-value-col", mat_value_col,
447
+ "--net-source-col", net_source_col,
448
+ "--net-target-col", net_target_col,
449
+ "--net-weight-col", net_weight_col,
450
+ "--min-n", str(min_n),
451
+ "--batch-size", str(batch_size),
452
+ "--min-sz", str(min_sz),
453
+ "--max-sz", str(max_sz),
454
+ "--kcdf", kcdf,
455
+ "--seed", str(seed),
456
+ ]
457
+ if mx_diff:
458
+ cmd.append("--mx-diff")
459
+ if abs_ranking:
460
+ cmd.append("--abs-ranking")
461
+ if verbose:
462
+ cmd.append("--verbose")
463
+
464
+ try:
465
+ process = subprocess.run(
466
+ cmd,
467
+ capture_output=True,
468
+ text=True,
469
+ check=True,
470
+ )
471
+ except subprocess.CalledProcessError as e:
472
+ return {
473
+ "command_executed": " ".join(e.cmd),
474
+ "stdout": e.stdout,
475
+ "stderr": e.stderr,
476
+ "return_code": e.returncode,
477
+ "output_files": []
478
+ }
479
+
480
+ return {
481
+ "command_executed": " ".join(cmd),
482
+ "stdout": process.stdout,
483
+ "stderr": process.stderr,
484
+ "output_files": [str(output)]
485
+ }
486
+
487
+ @mcp.tool
488
+ def decoupler_viper(
489
+ mat: Path,
490
+ net: Path,
491
+ output: Path,
492
+ mat_source_col: str = 'genes',
493
+ mat_target_col: str = 'cells',
494
+ mat_value_col: str = 'expression',
495
+ net_source_col: str = 'tf',
496
+ net_target_col: str = 'target',
497
+ net_weight_col: str = 'weight',
498
+ min_n: int = 5,
499
+ batch_size: int = 10000,
500
+ nes: bool = True,
501
+ pleiotropy: bool = True,
502
+ eset_filter: bool = False,
503
+ seed: int = 42,
504
+ verbose: bool = False,
505
+ ):
506
+ """
507
+ Runs Virtual Inference of Protein-activity by Enriched Regulon analysis (VIPER).
508
+
509
+ VIPER is a method to infer protein activity from gene expression data based on the enrichment
510
+ of its transcriptional targets (regulon).
511
+
512
+ Args:
513
+ mat: Path to the input matrix file.
514
+ net: Path to the input network file.
515
+ output: Path to the output file.
516
+ mat_source_col: Column name for features in the matrix file.
517
+ mat_target_col: Column name for samples in the matrix file.
518
+ mat_value_col: Column name for values in the matrix file.
519
+ net_source_col: Column name for regulators in the network file.
520
+ net_target_col: Column name for targets in the network file.
521
+ net_weight_col: Column name for interaction weights in the network file.
522
+ min_n: Minimum number of targets per regulator.
523
+ batch_size: Number of samples to process per batch.
524
+ nes: If True, compute Normalized Enrichment Scores (NES).
525
+ pleiotropy: If True, correct for pleiotropy (regulators sharing targets).
526
+ eset_filter: If True, filter by eset size.
527
+ seed: Random seed.
528
+ verbose: If True, increases verbosity.
529
+ """
530
+ # Input validation
531
+ if not mat.is_file():
532
+ raise FileNotFoundError(f"Input matrix file not found: {mat}")
533
+ if not net.is_file():
534
+ raise FileNotFoundError(f"Input network file not found: {net}")
535
+ if min_n < 1:
536
+ raise ValueError("min_n must be a positive integer.")
537
+ if batch_size < 1:
538
+ raise ValueError("batch_size must be a positive integer.")
539
+
540
+ output.parent.mkdir(parents=True, exist_ok=True)
541
+
542
+ cmd = [
543
+ "python", "-m", "decoupler", "viper",
544
+ "--mat", str(mat),
545
+ "--net", str(net),
546
+ "--output", str(output),
547
+ "--mat-source-col", mat_source_col,
548
+ "--mat-target-col", mat_target_col,
549
+ "--mat-value-col", mat_value_col,
550
+ "--net-source-col", net_source_col,
551
+ "--net-target-col", net_target_col,
552
+ "--net-weight-col", net_weight_col,
553
+ "--min-n", str(min_n),
554
+ "--batch-size", str(batch_size),
555
+ "--seed", str(seed),
556
+ ]
557
+ if nes:
558
+ cmd.append("--nes")
559
+ if pleiotropy:
560
+ cmd.append("--pleiotropy")
561
+ if eset_filter:
562
+ cmd.append("--eset-filter")
563
+ if verbose:
564
+ cmd.append("--verbose")
565
+
566
+ try:
567
+ process = subprocess.run(
568
+ cmd,
569
+ capture_output=True,
570
+ text=True,
571
+ check=True,
572
+ )
573
+ except subprocess.CalledProcessError as e:
574
+ return {
575
+ "command_executed": " ".join(e.cmd),
576
+ "stdout": e.stdout,
577
+ "stderr": e.stderr,
578
+ "return_code": e.returncode,
579
+ "output_files": []
580
+ }
581
+
582
+ return {
583
+ "command_executed": " ".join(cmd),
584
+ "stdout": process.stdout,
585
+ "stderr": process.stderr,
586
+ "output_files": [str(output)]
587
+ }
588
+
589
+ @mcp.tool
590
+ def decoupler_gsea(
591
+ mat: Path,
592
+ net: Path,
593
+ output: Path,
594
+ mat_source_col: str = 'genes',
595
+ mat_target_col: str = 'cells',
596
+ mat_value_col: str = 'expression',
597
+ net_source_col: str = 'tf',
598
+ net_target_col: str = 'target',
599
+ net_weight_col: str = 'weight',
600
+ min_n: int = 5,
601
+ batch_size: int = 10000,
602
+ times: int = 100,
603
+ min_sz: int = 5,
604
+ max_sz: int = 500,
605
+ seed: int = 42,
606
+ verbose: bool = False,
607
+ ):
608
+ """
609
+ Runs Gene Set Enrichment Analysis (GSEA) using decoupler.
610
+
611
+ GSEA determines whether a defined set of genes shows statistically significant, concordant
612
+ differences between two biological states.
613
+
614
+ Args:
615
+ mat: Path to the input matrix file.
616
+ net: Path to the input network file.
617
+ output: Path to the output file.
618
+ mat_source_col: Column name for features in the matrix file.
619
+ mat_target_col: Column name for samples in the matrix file.
620
+ mat_value_col: Column name for values in the matrix file.
621
+ net_source_col: Column name for regulators in the network file.
622
+ net_target_col: Column name for targets in the network file.
623
+ net_weight_col: Column name for interaction weights in the network file.
624
+ min_n: Minimum number of targets per regulator.
625
+ batch_size: Number of samples to process per batch.
626
+ times: Number of permutations to perform.
627
+ min_sz: Minimum size of a gene set to be considered.
628
+ max_sz: Maximum size of a gene set to be considered.
629
+ seed: Random seed for permutations.
630
+ verbose: If True, increases verbosity.
631
+ """
632
+ # Input validation
633
+ if not mat.is_file():
634
+ raise FileNotFoundError(f"Input matrix file not found: {mat}")
635
+ if not net.is_file():
636
+ raise FileNotFoundError(f"Input network file not found: {net}")
637
+ if min_n < 1:
638
+ raise ValueError("min_n must be a positive integer.")
639
+ if batch_size < 1:
640
+ raise ValueError("batch_size must be a positive integer.")
641
+ if times < 1:
642
+ raise ValueError("times must be a positive integer.")
643
+ if min_sz < 1:
644
+ raise ValueError("min_sz must be a positive integer.")
645
+ if max_sz < min_sz:
646
+ raise ValueError("max_sz must be greater than or equal to min_sz.")
647
+
648
+ output.parent.mkdir(parents=True, exist_ok=True)
649
+
650
+ cmd = [
651
+ "python", "-m", "decoupler", "gsea",
652
+ "--mat", str(mat),
653
+ "--net", str(net),
654
+ "--output", str(output),
655
+ "--mat-source-col", mat_source_col,
656
+ "--mat-target-col", mat_target_col,
657
+ "--mat-value-col", mat_value_col,
658
+ "--net-source-col", net_source_col,
659
+ "--net-target-col", net_target_col,
660
+ "--net-weight-col", net_weight_col,
661
+ "--min-n", str(min_n),
662
+ "--batch-size", str(batch_size),
663
+ "--times", str(times),
664
+ "--min-sz", str(min_sz),
665
+ "--max-sz", str(max_sz),
666
+ "--seed", str(seed),
667
+ ]
668
+ if verbose:
669
+ cmd.append("--verbose")
670
+
671
+ try:
672
+ process = subprocess.run(
673
+ cmd,
674
+ capture_output=True,
675
+ text=True,
676
+ check=True,
677
+ )
678
+ except subprocess.CalledProcessError as e:
679
+ return {
680
+ "command_executed": " ".join(e.cmd),
681
+ "stdout": e.stdout,
682
+ "stderr": e.stderr,
683
+ "return_code": e.returncode,
684
+ "output_files": []
685
+ }
686
+
687
+ return {
688
+ "command_executed": " ".join(cmd),
689
+ "stdout": process.stdout,
690
+ "stderr": process.stderr,
691
+ "output_files": [str(output)]
692
+ }
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_decoupler/app/decoupler_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_help_txt/mcp_decoupler/app/decoupler_server.py')
11
+ SERVER_NAME = 'biosci_decoupler'
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_help_txt/mcp_decoupler/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-decoupler:
5
+ build: .
6
+ image: mcp-decoupler:latest
7
+ container_name: mcp-decoupler
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=decoupler
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_help_txt/mcp_decoupler/environment.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ name: mcp-tool
3
+ channels:
4
+ - bioconda
5
+ - conda-forge
6
+ - defaults
7
+ dependencies:
8
+ - decoupler
9
+ - python=3.10
10
+