czty commited on
Commit
d4db0f6
·
verified ·
1 Parent(s): 3f8ed95

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

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_bbmap/docker-compose.yml +22 -0
  2. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bbmap/environment.yaml +10 -0
  3. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bbmap/requirements.txt +2 -0
  4. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bcftools/Dockerfile +40 -0
  5. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bcftools/app/bcftools_server.py +858 -0
  6. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bcftools/app/bcftools_shim_server.py +45 -0
  7. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bcftools/docker-compose.yml +22 -0
  8. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bcftools/environment.yaml +10 -0
  9. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bcftools/requirements.txt +2 -0
  10. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/Dockerfile +40 -0
  11. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/app/bedops_server.py +819 -0
  12. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/app/bedops_shim_server.py +45 -0
  13. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/app/requirements.txt +1 -0
  14. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/docker-compose.yml +22 -0
  15. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/environment.yaml +10 -0
  16. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/requirements.txt +2 -0
  17. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedtools/Dockerfile +40 -0
  18. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedtools/app/bedtools_server.py +700 -0
  19. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedtools/app/bedtools_shim_server.py +45 -0
  20. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedtools/docker-compose.yml +22 -0
  21. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedtools/environment.yaml +10 -0
  22. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedtools/requirements.txt +2 -0
  23. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/Dockerfile +40 -0
  24. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/app/bioawk_server.py +132 -0
  25. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/app/bioawk_shim_server.py +45 -0
  26. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/app/requirements.txt +1 -0
  27. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/docker-compose.yml +22 -0
  28. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/environment.yaml +10 -0
  29. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/requirements.txt +2 -0
  30. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/Dockerfile +40 -0
  31. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/app/bioconductor-affyio_server.py +208 -0
  32. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/app/bioconductor-affyio_shim_server.py +45 -0
  33. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/app/requirements.txt +1 -0
  34. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/docker-compose.yml +22 -0
  35. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/environment.yaml +10 -0
  36. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/requirements.txt +2 -0
  37. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotate/Dockerfile +40 -0
  38. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotate/app/bioconductor-annotate_server.py +141 -0
  39. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotate/app/bioconductor-annotate_shim_server.py +45 -0
  40. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotate/docker-compose.yml +22 -0
  41. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotate/environment.yaml +10 -0
  42. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotate/requirements.txt +2 -0
  43. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotationdbi/Dockerfile +40 -0
  44. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotationdbi/app/bioconductor-annotationdbi_server.py +456 -0
  45. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotationdbi/app/bioconductor-annotationdbi_shim_server.py +45 -0
  46. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotationdbi/docker-compose.yml +22 -0
  47. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotationdbi/environment.yaml +10 -0
  48. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotationdbi/requirements.txt +2 -0
  49. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-apeglm/Dockerfile +40 -0
  50. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-apeglm/app/bioconductor-apeglm_server.py +125 -0
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bbmap/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-bbmap:
5
+ build: .
6
+ image: mcp-bbmap:latest
7
+ container_name: mcp-bbmap
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=bbmap
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_bbmap/environment.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ name: mcp-tool
3
+ channels:
4
+ - bioconda
5
+ - conda-forge
6
+ - defaults
7
+ dependencies:
8
+ - bbmap
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bbmap/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bcftools/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 bcftools via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bcftools -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 bcftools_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/bcftools_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/bcftools_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bcftools/app/bcftools_server.py ADDED
@@ -0,0 +1,858 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import tempfile
3
+ from pathlib import Path
4
+ from typing import List, Optional
5
+
6
+ # Note: The @mcp.tool decorator is not defined here.
7
+ # It is assumed to be provided by the Model Context Protocol (MCP) framework.
8
+ # This code is designed to be used within that framework.
9
+
10
+ # Helper function to handle subprocess execution and error reporting
11
+ def _run_bcftools_command(cmd: List[str], output_file: Optional[Path] = None):
12
+ """
13
+ A helper function to execute a bcftools command, handle errors,
14
+ and return a structured dictionary.
15
+ """
16
+ command_str = " ".join(cmd)
17
+ try:
18
+ result = subprocess.run(
19
+ cmd,
20
+ capture_output=True,
21
+ text=True,
22
+ check=True,
23
+ )
24
+ output_files = [str(output_file)] if output_file and output_file.exists() else []
25
+
26
+ # For commands that create index files automatically
27
+ if output_file and str(output_file).endswith((".bcf", ".vcf.gz")):
28
+ index_extensions = [".csi", ".tbi"]
29
+ for ext in index_extensions:
30
+ index_file = Path(str(output_file) + ext)
31
+ if index_file.exists():
32
+ output_files.append(str(index_file))
33
+
34
+ return {
35
+ "command_executed": command_str,
36
+ "stdout": result.stdout,
37
+ "stderr": result.stderr,
38
+ "output_files": output_files,
39
+ "return_code": 0,
40
+ }
41
+ except FileNotFoundError:
42
+ return {
43
+ "command_executed": command_str,
44
+ "stdout": "",
45
+ "stderr": "Error: 'bcftools' command not found. Please ensure it is in your PATH.",
46
+ "output_files": [],
47
+ "return_code": 1,
48
+ "error": "FileNotFoundError"
49
+ }
50
+ except subprocess.CalledProcessError as e:
51
+ return {
52
+ "command_executed": command_str,
53
+ "stdout": e.stdout,
54
+ "stderr": e.stderr,
55
+ "output_files": [],
56
+ "return_code": e.returncode,
57
+ "error": "CalledProcessError"
58
+ }
59
+
60
+ @mcp.tool()
61
+ def bcftools_annotate(
62
+ input_file: Path,
63
+ annotations: Optional[Path] = None,
64
+ columns: Optional[str] = None,
65
+ header_lines: Optional[Path] = None,
66
+ output: Optional[Path] = None,
67
+ output_type: str = "v",
68
+ remove: Optional[str] = None,
69
+ set_id: Optional[str] = None,
70
+ regions: Optional[str] = None,
71
+ regions_file: Optional[Path] = None,
72
+ targets: Optional[str] = None,
73
+ targets_file: Optional[Path] = None,
74
+ include: Optional[str] = None,
75
+ exclude: Optional[str] = None,
76
+ samples: Optional[str] = None,
77
+ samples_file: Optional[Path] = None,
78
+ threads: int = 1,
79
+ rename_chrs: Optional[Path] = None,
80
+ no_version: bool = False,
81
+ single_overlaps: bool = False,
82
+ mark_sites: Optional[str] = None,
83
+ ):
84
+ """
85
+ Annotate VCF/BCF files with information from other files.
86
+ """
87
+ if not input_file.exists():
88
+ raise FileNotFoundError(f"Input file not found: {input_file}")
89
+ if annotations and not annotations.exists():
90
+ raise FileNotFoundError(f"Annotations file not found: {annotations}")
91
+ if header_lines and not header_lines.exists():
92
+ raise FileNotFoundError(f"Header lines file not found: {header_lines}")
93
+ if output_type not in ["b", "u", "z", "v"]:
94
+ raise ValueError("output_type must be one of 'b', 'u', 'z', 'v'.")
95
+
96
+ cmd = ["bcftools", "annotate", str(input_file)]
97
+
98
+ if annotations:
99
+ cmd.extend(["-a", str(annotations)])
100
+ if columns:
101
+ cmd.extend(["-c", columns])
102
+ if header_lines:
103
+ cmd.extend(["-h", str(header_lines)])
104
+ if output:
105
+ cmd.extend(["-o", str(output)])
106
+ if output_type:
107
+ cmd.extend(["-O", output_type])
108
+ if remove:
109
+ cmd.extend(["-x", remove])
110
+ if set_id:
111
+ cmd.extend(["--set-id", set_id])
112
+ if regions:
113
+ cmd.extend(["-r", regions])
114
+ if regions_file:
115
+ cmd.extend(["-R", str(regions_file)])
116
+ if targets:
117
+ cmd.extend(["-t", targets])
118
+ if targets_file:
119
+ cmd.extend(["-T", str(targets_file)])
120
+ if include:
121
+ cmd.extend(["-i", include])
122
+ if exclude:
123
+ cmd.extend(["-e", exclude])
124
+ if samples:
125
+ cmd.extend(["-s", samples])
126
+ if samples_file:
127
+ cmd.extend(["-S", str(samples_file)])
128
+ if threads > 1:
129
+ cmd.extend(["--threads", str(threads)])
130
+ if rename_chrs:
131
+ cmd.extend(["--rename-chrs", str(rename_chrs)])
132
+ if no_version:
133
+ cmd.append("--no-version")
134
+ if single_overlaps:
135
+ cmd.append("--single-overlaps")
136
+ if mark_sites:
137
+ cmd.extend(["--mark-sites", mark_sites])
138
+
139
+ return _run_bcftools_command(cmd, output)
140
+
141
+ @mcp.tool()
142
+ def bcftools_call(
143
+ input_file: Path,
144
+ output: Optional[Path] = None,
145
+ output_type: str = "v",
146
+ ploidy: Optional[str] = None,
147
+ ploidy_file: Optional[Path] = None,
148
+ call_method: str = "multiallelic",
149
+ constrain_alleles: bool = False,
150
+ group_samples: Optional[str] = None,
151
+ samples: Optional[str] = None,
152
+ samples_file: Optional[Path] = None,
153
+ format_fields: Optional[str] = None,
154
+ keep_alts: bool = False,
155
+ keep_masked_ref: bool = False,
156
+ skip_variants: bool = False,
157
+ threads: int = 1,
158
+ ):
159
+ """
160
+ Call genotypes from likelihoods.
161
+ """
162
+ if not input_file.exists():
163
+ raise FileNotFoundError(f"Input file not found: {input_file}")
164
+ if output_type not in ["b", "u", "z", "v"]:
165
+ raise ValueError("output_type must be one of 'b', 'u', 'z', 'v'.")
166
+ if call_method not in ["consensus", "multiallelic"]:
167
+ raise ValueError("call_method must be 'consensus' or 'multiallelic'.")
168
+
169
+ cmd = ["bcftools", "call", str(input_file)]
170
+
171
+ if output:
172
+ cmd.extend(["-o", str(output)])
173
+ if output_type:
174
+ cmd.extend(["-O", output_type])
175
+ if ploidy:
176
+ cmd.extend(["-p", ploidy])
177
+ if ploidy_file:
178
+ cmd.extend(["-P", str(ploidy_file)])
179
+ if call_method == "consensus":
180
+ cmd.append("-c")
181
+ else: # multiallelic is default, but -m is explicit
182
+ cmd.append("-m")
183
+ if constrain_alleles:
184
+ cmd.append("-C alleles")
185
+ if group_samples:
186
+ cmd.extend(["-G", group_samples])
187
+ if samples:
188
+ cmd.extend(["-s", samples])
189
+ if samples_file:
190
+ cmd.extend(["-S", str(samples_file)])
191
+ if format_fields:
192
+ cmd.extend(["-f", format_fields])
193
+ if keep_alts:
194
+ cmd.append("-A")
195
+ if keep_masked_ref:
196
+ cmd.append("-M")
197
+ if skip_variants:
198
+ cmd.append("-V")
199
+ if threads > 1:
200
+ cmd.extend(["--threads", str(threads)])
201
+
202
+ return _run_bcftools_command(cmd, output)
203
+
204
+ @mcp.tool()
205
+ def bcftools_concat(
206
+ input_files: List[Path],
207
+ output: Optional[Path] = None,
208
+ output_type: str = "v",
209
+ allow_overlaps: bool = False,
210
+ remove_duplicates: bool = False,
211
+ naive: bool = False,
212
+ threads: int = 1,
213
+ ):
214
+ """
215
+ Concatenate VCF/BCF files from non-overlapping regions.
216
+ """
217
+ if not input_files:
218
+ raise ValueError("At least one input file must be provided.")
219
+ for f in input_files:
220
+ if not f.exists():
221
+ raise FileNotFoundError(f"Input file not found: {f}")
222
+ if output_type not in ["b", "u", "z", "v"]:
223
+ raise ValueError("output_type must be one of 'b', 'u', 'z', 'v'.")
224
+
225
+ cmd = ["bcftools", "concat"]
226
+
227
+ if allow_overlaps:
228
+ cmd.append("-a")
229
+ if remove_duplicates:
230
+ cmd.append("-d")
231
+ if naive:
232
+ cmd.append("-n")
233
+ if output:
234
+ cmd.extend(["-o", str(output)])
235
+ if output_type:
236
+ cmd.extend(["-O", output_type])
237
+ if threads > 1:
238
+ cmd.extend(["--threads", str(threads)])
239
+
240
+ cmd.extend([str(f) for f in input_files])
241
+
242
+ return _run_bcftools_command(cmd, output)
243
+
244
+ @mcp.tool()
245
+ def bcftools_consensus(
246
+ input_file: Path,
247
+ fasta_ref: Path,
248
+ output: Optional[Path] = None,
249
+ chain: Optional[Path] = None,
250
+ haplotype: Optional[str] = None,
251
+ iupac_codes: bool = False,
252
+ mark_del: Optional[str] = None,
253
+ mark_ins: Optional[str] = None,
254
+ mark_snv: Optional[str] = None,
255
+ missing: Optional[str] = None,
256
+ sample: Optional[str] = None,
257
+ include: Optional[str] = None,
258
+ exclude: Optional[str] = None,
259
+ ):
260
+ """
261
+ Create a consensus sequence by applying VCF variants to a reference FASTA file.
262
+ """
263
+ if not input_file.exists():
264
+ raise FileNotFoundError(f"Input VCF/BCF file not found: {input_file}")
265
+ if not fasta_ref.exists():
266
+ raise FileNotFoundError(f"Reference FASTA file not found: {fasta_ref}")
267
+ if haplotype and haplotype not in ["1", "2", "R", "A", "IUPAC", "all"]:
268
+ raise ValueError("haplotype must be one of '1', '2', 'R', 'A', 'IUPAC', 'all'.")
269
+
270
+ cmd = ["bcftools", "consensus", str(input_file)]
271
+ cmd.extend(["-f", str(fasta_ref)])
272
+
273
+ if output:
274
+ cmd.extend(["-o", str(output)])
275
+ if chain:
276
+ cmd.extend(["-c", str(chain)])
277
+ if haplotype:
278
+ cmd.extend(["-H", haplotype])
279
+ if iupac_codes:
280
+ cmd.append("-i")
281
+ if mark_del:
282
+ cmd.extend(["--mark-del", mark_del])
283
+ if mark_ins:
284
+ cmd.extend(["--mark-ins", mark_ins])
285
+ if mark_snv:
286
+ cmd.extend(["--mark-snv", mark_snv])
287
+ if missing:
288
+ cmd.extend(["-m", missing])
289
+ if sample:
290
+ cmd.extend(["-s", sample])
291
+ if include:
292
+ cmd.extend(["--include", include])
293
+ if exclude:
294
+ cmd.extend(["--exclude", exclude])
295
+
296
+ return _run_bcftools_command(cmd, output)
297
+
298
+ @mcp.tool()
299
+ def bcftools_filter(
300
+ input_file: Path,
301
+ output: Optional[Path] = None,
302
+ output_type: str = "v",
303
+ include: Optional[str] = None,
304
+ exclude: Optional[str] = None,
305
+ soft_filter: Optional[str] = None,
306
+ set_gt: Optional[str] = None,
307
+ mode: str = "+",
308
+ threads: int = 1,
309
+ ):
310
+ """
311
+ Apply filters to VCF/BCF files.
312
+ """
313
+ if not input_file.exists():
314
+ raise FileNotFoundError(f"Input file not found: {input_file}")
315
+ if output_type not in ["b", "u", "z", "v"]:
316
+ raise ValueError("output_type must be one of 'b', 'u', 'z', 'v'.")
317
+ if mode not in ["+", "x", "X"]:
318
+ raise ValueError("mode must be one of '+', 'x', 'X'.")
319
+
320
+ cmd = ["bcftools", "filter", str(input_file)]
321
+
322
+ if output:
323
+ cmd.extend(["-o", str(output)])
324
+ if output_type:
325
+ cmd.extend(["-O", output_type])
326
+ if include:
327
+ cmd.extend(["-i", include])
328
+ if exclude:
329
+ cmd.extend(["-e", exclude])
330
+ if soft_filter:
331
+ cmd.extend(["-s", soft_filter])
332
+ if set_gt:
333
+ cmd.extend(["-S", set_gt])
334
+ if mode != "+":
335
+ cmd.extend(["-m", mode])
336
+ if threads > 1:
337
+ cmd.extend(["--threads", str(threads)])
338
+
339
+ return _run_bcftools_command(cmd, output)
340
+
341
+ @mcp.tool()
342
+ def bcftools_index(
343
+ input_file: Path,
344
+ force: bool = False,
345
+ stats: bool = False,
346
+ threads: int = 1,
347
+ csi: bool = False,
348
+ tbi: bool = False,
349
+ min_csi_shift: int = 14,
350
+ ):
351
+ """
352
+ Index VCF/BCF files for fast random access.
353
+ """
354
+ if not input_file.exists():
355
+ raise FileNotFoundError(f"Input file not found: {input_file}")
356
+ if csi and tbi:
357
+ raise ValueError("Cannot specify both --csi (-c) and --tbi (-t).")
358
+
359
+ cmd = ["bcftools", "index"]
360
+
361
+ if force:
362
+ cmd.append("-f")
363
+ if stats:
364
+ cmd.append("-n")
365
+ if threads > 1:
366
+ cmd.extend(["--threads", str(threads)])
367
+ if csi:
368
+ cmd.append("-c")
369
+ if tbi:
370
+ cmd.append("-t")
371
+ if csi and min_csi_shift != 14:
372
+ cmd.extend(["-m", str(min_csi_shift)])
373
+
374
+ cmd.append(str(input_file))
375
+
376
+ # The output file is the index file itself
377
+ output_idx_file = None
378
+ if csi:
379
+ output_idx_file = Path(str(input_file) + ".csi")
380
+ else: # default is tbi for vcf.gz, csi for bcf
381
+ if str(input_file).endswith(".bcf"):
382
+ output_idx_file = Path(str(input_file) + ".csi")
383
+ else:
384
+ output_idx_file = Path(str(input_file) + ".tbi")
385
+
386
+ return _run_bcftools_command(cmd, output_idx_file)
387
+
388
+ @mcp.tool()
389
+ def bcftools_isec(
390
+ input_files: List[Path],
391
+ output_dir: Path,
392
+ output_type: str = "v",
393
+ complement: bool = False,
394
+ collapse: Optional[str] = None,
395
+ exclude: Optional[str] = None,
396
+ include: Optional[str] = None,
397
+ n_sites: Optional[str] = None,
398
+ regions: Optional[str] = None,
399
+ regions_file: Optional[Path] = None,
400
+ targets: Optional[str] = None,
401
+ targets_file: Optional[Path] = None,
402
+ threads: int = 1,
403
+ ):
404
+ """
405
+ Create intersections, unions, and complements of VCF/BCF files.
406
+ """
407
+ if len(input_files) < 2:
408
+ raise ValueError("At least two input files must be provided for isec.")
409
+ for f in input_files:
410
+ if not f.exists():
411
+ raise FileNotFoundError(f"Input file not found: {f}")
412
+ if output_type not in ["b", "u", "z", "v"]:
413
+ raise ValueError("output_type must be one of 'b', 'u', 'z', 'v'.")
414
+ if collapse and collapse not in ["none", "all", "snps", "indels", "both", "any"]:
415
+ raise ValueError("Invalid value for collapse.")
416
+
417
+ output_dir.mkdir(parents=True, exist_ok=True)
418
+
419
+ cmd = ["bcftools", "isec"]
420
+ cmd.extend(["-p", str(output_dir)])
421
+ cmd.extend(["-O", output_type])
422
+
423
+ if complement:
424
+ cmd.append("-c")
425
+ if collapse:
426
+ cmd.extend(["--collapse", collapse])
427
+ if exclude:
428
+ cmd.extend(["-e", exclude])
429
+ if include:
430
+ cmd.extend(["-i", include])
431
+ if n_sites:
432
+ cmd.extend(["-n", n_sites])
433
+ if regions:
434
+ cmd.extend(["-r", regions])
435
+ if regions_file:
436
+ cmd.extend(["-R", str(regions_file)])
437
+ if targets:
438
+ cmd.extend(["-t", targets])
439
+ if targets_file:
440
+ cmd.extend(["-T", str(targets_file)])
441
+ if threads > 1:
442
+ cmd.extend(["--threads", str(threads)])
443
+
444
+ cmd.extend([str(f) for f in input_files])
445
+
446
+ # isec doesn't have a single output file, it creates a directory
447
+ # We will return the directory path in a structured way if needed,
448
+ # but for now, we'll rely on the user knowing the output is a directory.
449
+ # The _run_bcftools_command helper won't find a single output file.
450
+ result = _run_bcftools_command(cmd)
451
+
452
+ # Manually list created files
453
+ if result["return_code"] == 0:
454
+ created_files = [str(p) for p in output_dir.glob('*')]
455
+ result["output_files"] = created_files
456
+
457
+ return result
458
+
459
+ @mcp.tool()
460
+ def bcftools_merge(
461
+ input_files: List[Path],
462
+ output: Optional[Path] = None,
463
+ output_type: str = "v",
464
+ info_rules: Optional[str] = None,
465
+ merge_logic: Optional[str] = None,
466
+ threads: int = 1,
467
+ ):
468
+ """
469
+ Merge multiple VCF/BCF files from different samples into a single file.
470
+ """
471
+ if not input_files:
472
+ raise ValueError("At least one input file must be provided.")
473
+ for f in input_files:
474
+ if not f.exists():
475
+ raise FileNotFoundError(f"Input file not found: {f}")
476
+ if output_type not in ["b", "u", "z", "v"]:
477
+ raise ValueError("output_type must be one of 'b', 'u', 'z', 'v'.")
478
+
479
+ cmd = ["bcftools", "merge"]
480
+
481
+ if output:
482
+ cmd.extend(["-o", str(output)])
483
+ if output_type:
484
+ cmd.extend(["-O", output_type])
485
+ if info_rules:
486
+ cmd.extend(["--info-rules", info_rules])
487
+ if merge_logic:
488
+ cmd.extend(["-m", merge_logic])
489
+ if threads > 1:
490
+ cmd.extend(["--threads", str(threads)])
491
+
492
+ cmd.extend([str(f) for f in input_files])
493
+
494
+ return _run_bcftools_command(cmd, output)
495
+
496
+ @mcp.tool()
497
+ def bcftools_mpileup(
498
+ input_bams: List[Path],
499
+ fasta_ref: Path,
500
+ output: Optional[Path] = None,
501
+ output_type: str = "v",
502
+ regions: Optional[str] = None,
503
+ regions_file: Optional[Path] = None,
504
+ annotate: Optional[str] = None,
505
+ max_depth: int = 250,
506
+ min_base_quality: int = 13,
507
+ min_mapping_quality: int = 0,
508
+ adjust_mq: int = 50,
509
+ no_baq: bool = False,
510
+ threads: int = 1,
511
+ ):
512
+ """
513
+ Generate VCF/BCF from alignment files (BAM/CRAM).
514
+ """
515
+ if not input_bams:
516
+ raise ValueError("At least one input BAM/CRAM file must be provided.")
517
+ for f in input_bams:
518
+ if not f.exists():
519
+ raise FileNotFoundError(f"Input alignment file not found: {f}")
520
+ if not fasta_ref.exists():
521
+ raise FileNotFoundError(f"Reference FASTA file not found: {fasta_ref}")
522
+ if output_type not in ["b", "u", "z", "v"]:
523
+ raise ValueError("output_type must be one of 'b', 'u', 'z', 'v'.")
524
+
525
+ cmd = ["bcftools", "mpileup"]
526
+ cmd.extend(["-f", str(fasta_ref)])
527
+
528
+ if output:
529
+ cmd.extend(["-o", str(output)])
530
+ if output_type:
531
+ cmd.extend(["-O", output_type])
532
+ if regions:
533
+ cmd.extend(["-r", regions])
534
+ if regions_file:
535
+ cmd.extend(["-R", str(regions_file)])
536
+ if annotate:
537
+ cmd.extend(["-a", annotate])
538
+ if max_depth != 250:
539
+ cmd.extend(["-d", str(max_depth)])
540
+ if min_base_quality != 13:
541
+ cmd.extend(["-q", str(min_base_quality)])
542
+ if min_mapping_quality != 0:
543
+ cmd.extend(["-Q", str(min_mapping_quality)])
544
+ if adjust_mq != 50:
545
+ cmd.extend(["-C", str(adjust_mq)])
546
+ if no_baq:
547
+ cmd.append("-B")
548
+ if threads > 1:
549
+ cmd.extend(["--threads", str(threads)])
550
+
551
+ cmd.extend([str(f) for f in input_bams])
552
+
553
+ return _run_bcftools_command(cmd, output)
554
+
555
+ @mcp.tool()
556
+ def bcftools_norm(
557
+ input_file: Path,
558
+ fasta_ref: Path,
559
+ output: Optional[Path] = None,
560
+ output_type: str = "v",
561
+ check_ref: str = "w",
562
+ multiallelics: Optional[str] = None,
563
+ atomize: bool = False,
564
+ rm_dup: Optional[str] = None,
565
+ threads: int = 1,
566
+ ):
567
+ """
568
+ Left-align and normalize indels, check REF, split multiallelic sites.
569
+ """
570
+ if not input_file.exists():
571
+ raise FileNotFoundError(f"Input file not found: {input_file}")
572
+ if not fasta_ref.exists():
573
+ raise FileNotFoundError(f"Reference FASTA file not found: {fasta_ref}")
574
+ if output_type not in ["b", "u", "z", "v"]:
575
+ raise ValueError("output_type must be one of 'b', 'u', 'z', 'v'.")
576
+ if check_ref not in ["w", "e", "x", "s"]:
577
+ raise ValueError("check_ref must be one of 'w', 'e', 'x', 's'.")
578
+
579
+ cmd = ["bcftools", "norm", str(input_file)]
580
+ cmd.extend(["-f", str(fasta_ref)])
581
+
582
+ if output:
583
+ cmd.extend(["-o", str(output)])
584
+ if output_type:
585
+ cmd.extend(["-O", output_type])
586
+ if check_ref != "w":
587
+ cmd.extend(["-c", check_ref])
588
+ if multiallelics:
589
+ cmd.extend(["-m", multiallelics])
590
+ if atomize:
591
+ cmd.append("-a")
592
+ if rm_dup:
593
+ cmd.extend(["-d", rm_dup])
594
+ if threads > 1:
595
+ cmd.extend(["--threads", str(threads)])
596
+
597
+ return _run_bcftools_command(cmd, output)
598
+
599
+ @mcp.tool()
600
+ def bcftools_query(
601
+ input_file: Path,
602
+ format_string: str,
603
+ output: Optional[Path] = None,
604
+ include: Optional[str] = None,
605
+ exclude: Optional[str] = None,
606
+ regions: Optional[str] = None,
607
+ regions_file: Optional[Path] = None,
608
+ samples: Optional[str] = None,
609
+ samples_file: Optional[Path] = None,
610
+ list_samples: bool = False,
611
+ ):
612
+ """
613
+ Extracts fields from VCF/BCF files and prints them in a user-defined format.
614
+ """
615
+ if not input_file.exists():
616
+ raise FileNotFoundError(f"Input file not found: {input_file}")
617
+
618
+ cmd = ["bcftools", "query", str(input_file)]
619
+
620
+ if list_samples:
621
+ cmd.append("-l")
622
+ else:
623
+ cmd.extend(["-f", format_string])
624
+
625
+ if output:
626
+ cmd.extend(["-o", str(output)])
627
+ if include:
628
+ cmd.extend(["-i", include])
629
+ if exclude:
630
+ cmd.extend(["-e", exclude])
631
+ if regions:
632
+ cmd.extend(["-r", regions])
633
+ if regions_file:
634
+ cmd.extend(["-R", str(regions_file)])
635
+ if samples:
636
+ cmd.extend(["-s", samples])
637
+ if samples_file:
638
+ cmd.extend(["-S", str(samples_file)])
639
+
640
+ return _run_bcftools_command(cmd, output)
641
+
642
+ @mcp.tool()
643
+ def bcftools_reheader(
644
+ input_file: Path,
645
+ header: Optional[Path] = None,
646
+ samples: Optional[Path] = None,
647
+ output: Optional[Path] = None,
648
+ output_type: str = "v",
649
+ ):
650
+ """
651
+ Modify VCF/BCF header, e.g., rename samples.
652
+ """
653
+ if not input_file.exists():
654
+ raise FileNotFoundError(f"Input file not found: {input_file}")
655
+ if header and not header.exists():
656
+ raise FileNotFoundError(f"Header file not found: {header}")
657
+ if samples and not samples.exists():
658
+ raise FileNotFoundError(f"Samples file not found: {samples}")
659
+ if not header and not samples:
660
+ raise ValueError("Either 'header' or 'samples' file must be provided.")
661
+ if output_type not in ["b", "u", "z", "v"]:
662
+ raise ValueError("output_type must be one of 'b', 'u', 'z', 'v'.")
663
+
664
+ cmd = ["bcftools", "reheader"]
665
+
666
+ if header:
667
+ cmd.extend(["-h", str(header)])
668
+ if samples:
669
+ cmd.extend(["-s", str(samples)])
670
+ if output:
671
+ cmd.extend(["-o", str(output)])
672
+
673
+ cmd.append(str(input_file))
674
+
675
+ # Reheader does not support -O, output type is inferred from extension
676
+ return _run_bcftools_command(cmd, output)
677
+
678
+ @mcp.tool()
679
+ def bcftools_sort(
680
+ input_file: Path,
681
+ output: Optional[Path] = None,
682
+ output_type: str = "v",
683
+ max_mem: str = "768M",
684
+ temp_dir: Optional[Path] = None,
685
+ ):
686
+ """
687
+ Sort VCF/BCF file by chromosome and position.
688
+ """
689
+ if not input_file.exists():
690
+ raise FileNotFoundError(f"Input file not found: {input_file}")
691
+ if output_type not in ["b", "u", "z", "v"]:
692
+ raise ValueError("output_type must be one of 'b', 'u', 'z', 'v'.")
693
+
694
+ cmd = ["bcftools", "sort", str(input_file)]
695
+
696
+ if output:
697
+ cmd.extend(["-o", str(output)])
698
+ if output_type:
699
+ cmd.extend(["-O", output_type])
700
+ if max_mem:
701
+ cmd.extend(["-m", max_mem])
702
+ if temp_dir:
703
+ temp_dir.mkdir(exist_ok=True, parents=True)
704
+ cmd.extend(["-T", str(temp_dir)])
705
+
706
+ return _run_bcftools_command(cmd, output)
707
+
708
+ @mcp.tool()
709
+ def bcftools_stats(
710
+ input_files: List[Path],
711
+ fasta_ref: Optional[Path] = None,
712
+ output_dir: Optional[Path] = None,
713
+ regions: Optional[str] = None,
714
+ regions_file: Optional[Path] = None,
715
+ samples: Optional[str] = None,
716
+ samples_file: Optional[Path] = None,
717
+ threads: int = 1,
718
+ ):
719
+ """
720
+ Produce VCF/BCF stats, create plots with plot-vcfstats.
721
+ """
722
+ if not input_files:
723
+ raise ValueError("At least one input file must be provided.")
724
+ for f in input_files:
725
+ if not f.exists():
726
+ raise FileNotFoundError(f"Input file not found: {f}")
727
+ if fasta_ref and not fasta_ref.exists():
728
+ raise FileNotFoundError(f"Reference FASTA file not found: {fasta_ref}")
729
+
730
+ cmd = ["bcftools", "stats"]
731
+
732
+ if fasta_ref:
733
+ cmd.extend(["-f", str(fasta_ref)])
734
+ if regions:
735
+ cmd.extend(["-r", regions])
736
+ if regions_file:
737
+ cmd.extend(["-R", str(regions_file)])
738
+ if samples:
739
+ cmd.extend(["-s", samples])
740
+ if samples_file:
741
+ cmd.extend(["-S", str(samples_file)])
742
+ if threads > 1:
743
+ cmd.extend(["--threads", str(threads)])
744
+
745
+ cmd.extend([str(f) for f in input_files])
746
+
747
+ # stats command outputs to stdout by default.
748
+ # If output_dir is provided, we redirect stdout to a file.
749
+ output_file = None
750
+ if output_dir:
751
+ output_dir.mkdir(exist_ok=True, parents=True)
752
+ output_file = output_dir / "stats.txt"
753
+ with open(output_file, "w") as f_out:
754
+ command_str = " ".join(cmd)
755
+ try:
756
+ result = subprocess.run(
757
+ cmd,
758
+ stdout=f_out,
759
+ stderr=subprocess.PIPE,
760
+ text=True,
761
+ check=True,
762
+ )
763
+ return {
764
+ "command_executed": command_str,
765
+ "stdout": f"Stats written to {output_file}",
766
+ "stderr": result.stderr,
767
+ "output_files": [str(output_file)],
768
+ "return_code": 0,
769
+ }
770
+ except subprocess.CalledProcessError as e:
771
+ return {
772
+ "command_executed": command_str,
773
+ "stdout": e.stdout or "",
774
+ "stderr": e.stderr,
775
+ "output_files": [],
776
+ "return_code": e.returncode,
777
+ "error": "CalledProcessError"
778
+ }
779
+ else:
780
+ # No output file, capture stdout directly
781
+ return _run_bcftools_command(cmd)
782
+
783
+ @mcp.tool()
784
+ def bcftools_view(
785
+ input_file: Path,
786
+ output: Optional[Path] = None,
787
+ output_type: str = "v",
788
+ header_only: bool = False,
789
+ no_header: bool = False,
790
+ drop_genotypes: bool = False,
791
+ trim_alt_alleles: bool = False,
792
+ min_alleles: Optional[int] = None,
793
+ max_alleles: Optional[int] = None,
794
+ min_ac: Optional[int] = None,
795
+ max_ac: Optional[int] = None,
796
+ min_af: Optional[float] = None,
797
+ max_af: Optional[float] = None,
798
+ types: Optional[str] = None,
799
+ include: Optional[str] = None,
800
+ exclude: Optional[str] = None,
801
+ regions: Optional[str] = None,
802
+ regions_file: Optional[Path] = None,
803
+ samples: Optional[str] = None,
804
+ samples_file: Optional[Path] = None,
805
+ threads: int = 1,
806
+ ):
807
+ """
808
+ Subset, filter, and convert VCF and BCF files.
809
+ """
810
+ if not input_file.exists():
811
+ raise FileNotFoundError(f"Input file not found: {input_file}")
812
+ if output_type not in ["b", "u", "z", "v"]:
813
+ raise ValueError("output_type must be one of 'b', 'u', 'z', 'v'.")
814
+
815
+ cmd = ["bcftools", "view", str(input_file)]
816
+
817
+ if output:
818
+ cmd.extend(["-o", str(output)])
819
+ if output_type:
820
+ cmd.extend(["-O", output_type])
821
+ if header_only:
822
+ cmd.append("-h")
823
+ if no_header:
824
+ cmd.append("-H")
825
+ if drop_genotypes:
826
+ cmd.append("-G")
827
+ if trim_alt_alleles:
828
+ cmd.append("-a")
829
+ if min_alleles is not None:
830
+ cmd.extend(["-m", str(min_alleles)])
831
+ if max_alleles is not None:
832
+ cmd.extend(["-M", str(max_alleles)])
833
+ if min_ac is not None:
834
+ cmd.extend(["-c", str(min_ac)])
835
+ if max_ac is not None:
836
+ cmd.extend(["-C", str(max_ac)])
837
+ if min_af is not None:
838
+ cmd.extend(["-q", str(min_af)])
839
+ if max_af is not None:
840
+ cmd.extend(["-Q", str(max_af)])
841
+ if types:
842
+ cmd.extend(["-v", types])
843
+ if include:
844
+ cmd.extend(["-i", include])
845
+ if exclude:
846
+ cmd.extend(["-e", exclude])
847
+ if regions:
848
+ cmd.extend(["-r", regions])
849
+ if regions_file:
850
+ cmd.extend(["-R", str(regions_file)])
851
+ if samples:
852
+ cmd.extend(["-s", samples])
853
+ if samples_file:
854
+ cmd.extend(["-S", str(samples_file)])
855
+ if threads > 1:
856
+ cmd.extend(["--threads", str(threads)])
857
+
858
+ return _run_bcftools_command(cmd, output)
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bcftools/app/bcftools_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_bcftools/app/bcftools_server.py')
11
+ SERVER_NAME = 'biosci_bcftools'
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_bcftools/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-bcftools:
5
+ build: .
6
+ image: mcp-bcftools:latest
7
+ container_name: mcp-bcftools
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=bcftools
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_bcftools/environment.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ name: mcp-tool
3
+ channels:
4
+ - bioconda
5
+ - conda-forge
6
+ - defaults
7
+ dependencies:
8
+ - bcftools
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bcftools/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/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 bedops via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bedops -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/bedops_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/bedops_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/bedops_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/app/bedops_server.py ADDED
@@ -0,0 +1,819 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import tempfile
3
+ from pathlib import Path
4
+ from typing import List, Optional
5
+
6
+ # MCP decorator is commented out as per instructions
7
+ # import mcp
8
+
9
+ @mcp.tool()
10
+ def bedops_complement(
11
+ files: List[Path],
12
+ chop_to_limits: bool = False,
13
+ chrom: Optional[str] = None,
14
+ ec: bool = False,
15
+ header: bool = False,
16
+ range_str: Optional[str] = None,
17
+ output_file: Optional[Path] = None,
18
+ ) -> dict:
19
+ """
20
+ Computes the complement of one or more BED files.
21
+
22
+ This corresponds to the `bedops -c` or `bedops --complement` operation.
23
+ It finds the regions within chromosome boundaries that are not covered by
24
+ any intervals in the input file(s).
25
+
26
+ Args:
27
+ files: A list of one or more input BED/Starch files. Must be sorted.
28
+ chop_to_limits: If True, chop complementary regions to chromosome limits
29
+ defined by the first input file (-L flag).
30
+ chrom: Process data for the given chromosome only.
31
+ ec: Error check input files (slower).
32
+ header: Accept headers (VCF, GFF, SAM, BED, WIG) in any input file.
33
+ range_str: Pad coordinates. Use 'L:R' format (e.g., '-10:20') or a
34
+ single value 'S' for symmetric padding (e.g., '100').
35
+ output_file: Optional path to save the output. If not provided,
36
+ output is returned as a string in the result dictionary.
37
+
38
+ Returns:
39
+ A dictionary containing the command executed, stdout, stderr, and a
40
+ list of output files generated.
41
+ """
42
+ if not files:
43
+ raise ValueError("At least one input file must be provided for the complement operation.")
44
+ for file_path in files:
45
+ if not file_path.exists():
46
+ raise FileNotFoundError(f"Input file not found: {file_path}")
47
+
48
+ cmd = ["bedops"]
49
+
50
+ if chrom:
51
+ cmd.extend(["--chrom", chrom])
52
+ if ec:
53
+ cmd.append("--ec")
54
+ if header:
55
+ cmd.append("--header")
56
+ if range_str:
57
+ cmd.extend(["--range", range_str])
58
+
59
+ cmd.append("--complement")
60
+ if chop_to_limits:
61
+ cmd.append("-L")
62
+
63
+ cmd.extend([str(p) for p in files])
64
+
65
+ try:
66
+ if output_file:
67
+ with open(output_file, "w") as f:
68
+ result = subprocess.run(
69
+ cmd, check=True, text=True, stdout=f, stderr=subprocess.PIPE
70
+ )
71
+ stdout_capture = ""
72
+ output_files_list = [str(output_file)]
73
+ else:
74
+ result = subprocess.run(
75
+ cmd, check=True, text=True, capture_output=True
76
+ )
77
+ stdout_capture = result.stdout
78
+ output_files_list = []
79
+
80
+ return {
81
+ "command_executed": " ".join(cmd),
82
+ "stdout": stdout_capture,
83
+ "stderr": result.stderr,
84
+ "output_files": output_files_list,
85
+ }
86
+ except subprocess.CalledProcessError as e:
87
+ raise RuntimeError(
88
+ f"bedops complement failed with exit code {e.returncode}\n"
89
+ f"Stderr: {e.stderr}\n"
90
+ f"Stdout: {e.stdout}\n"
91
+ f"Command: {' '.join(cmd)}"
92
+ ) from e
93
+
94
+ @mcp.tool()
95
+ def bedops_difference(
96
+ files: List[Path],
97
+ chrom: Optional[str] = None,
98
+ ec: bool = False,
99
+ header: bool = False,
100
+ range_str: Optional[str] = None,
101
+ output_file: Optional[Path] = None,
102
+ ) -> dict:
103
+ """
104
+ Computes the difference between a reference BED file and one or more other BED files.
105
+
106
+ This corresponds to the `bedops -d` or `bedops --difference` operation.
107
+ It returns regions from the first (reference) file that do not overlap
108
+ with any regions in the subsequent files.
109
+
110
+ Args:
111
+ files: A list of two or more input BED/Starch files. The first file is
112
+ the reference. All files must be sorted.
113
+ chrom: Process data for the given chromosome only.
114
+ ec: Error check input files (slower).
115
+ header: Accept headers (VCF, GFF, SAM, BED, WIG) in any input file.
116
+ range_str: Pad coordinates. Use 'L:R' format (e.g., '-10:20') or a
117
+ single value 'S' for symmetric padding (e.g., '100').
118
+ output_file: Optional path to save the output. If not provided,
119
+ output is returned as a string in the result dictionary.
120
+
121
+ Returns:
122
+ A dictionary containing the command executed, stdout, stderr, and a
123
+ list of output files generated.
124
+ """
125
+ if len(files) < 2:
126
+ raise ValueError("At least two input files (a reference and one other) must be provided for the difference operation.")
127
+ for file_path in files:
128
+ if not file_path.exists():
129
+ raise FileNotFoundError(f"Input file not found: {file_path}")
130
+
131
+ cmd = ["bedops"]
132
+
133
+ if chrom:
134
+ cmd.extend(["--chrom", chrom])
135
+ if ec:
136
+ cmd.append("--ec")
137
+ if header:
138
+ cmd.append("--header")
139
+ if range_str:
140
+ cmd.extend(["--range", range_str])
141
+
142
+ cmd.append("--difference")
143
+ cmd.extend([str(p) for p in files])
144
+
145
+ try:
146
+ if output_file:
147
+ with open(output_file, "w") as f:
148
+ result = subprocess.run(
149
+ cmd, check=True, text=True, stdout=f, stderr=subprocess.PIPE
150
+ )
151
+ stdout_capture = ""
152
+ output_files_list = [str(output_file)]
153
+ else:
154
+ result = subprocess.run(
155
+ cmd, check=True, text=True, capture_output=True
156
+ )
157
+ stdout_capture = result.stdout
158
+ output_files_list = []
159
+
160
+ return {
161
+ "command_executed": " ".join(cmd),
162
+ "stdout": stdout_capture,
163
+ "stderr": result.stderr,
164
+ "output_files": output_files_list,
165
+ }
166
+ except subprocess.CalledProcessError as e:
167
+ raise RuntimeError(
168
+ f"bedops difference failed with exit code {e.returncode}\n"
169
+ f"Stderr: {e.stderr}\n"
170
+ f"Stdout: {e.stdout}\n"
171
+ f"Command: {' '.join(cmd)}"
172
+ ) from e
173
+
174
+ @mcp.tool()
175
+ def bedops_element_of(
176
+ files: List[Path],
177
+ overlap_criterion: str = "100%",
178
+ chrom: Optional[str] = None,
179
+ ec: bool = False,
180
+ header: bool = False,
181
+ range_str: Optional[str] = None,
182
+ output_file: Optional[Path] = None,
183
+ ) -> dict:
184
+ """
185
+ Finds elements in the reference file that overlap other files by a specified amount.
186
+
187
+ This corresponds to the `bedops -e` or `bedops --element-of` operation.
188
+ It returns elements from the first (reference) file that overlap elements
189
+ in any of the other files by at least the specified amount.
190
+
191
+ Args:
192
+ files: A list of two or more input BED/Starch files. The first file is
193
+ the reference. All files must be sorted.
194
+ overlap_criterion: The required overlap, as base pairs (e.g., '1') or
195
+ percentage (e.g., '50%'). Defaults to '100%'.
196
+ chrom: Process data for the given chromosome only.
197
+ ec: Error check input files (slower).
198
+ header: Accept headers (VCF, GFF, SAM, BED, WIG) in any input file.
199
+ range_str: Pad coordinates. Use 'L:R' or 'S' format. The first (reference)
200
+ file is NOT padded with this operation.
201
+ output_file: Optional path to save the output. If not provided,
202
+ output is returned as a string in the result dictionary.
203
+
204
+ Returns:
205
+ A dictionary containing the command executed, stdout, stderr, and a
206
+ list of output files generated.
207
+ """
208
+ if len(files) < 2:
209
+ raise ValueError("At least two input files (a reference and one other) must be provided for the element-of operation.")
210
+ for file_path in files:
211
+ if not file_path.exists():
212
+ raise FileNotFoundError(f"Input file not found: {file_path}")
213
+
214
+ cmd = ["bedops"]
215
+
216
+ if chrom:
217
+ cmd.extend(["--chrom", chrom])
218
+ if ec:
219
+ cmd.append("--ec")
220
+ if header:
221
+ cmd.append("--header")
222
+ if range_str:
223
+ cmd.extend(["--range", range_str])
224
+
225
+ cmd.extend(["--element-of", overlap_criterion])
226
+ cmd.extend([str(p) for p in files])
227
+
228
+ try:
229
+ if output_file:
230
+ with open(output_file, "w") as f:
231
+ result = subprocess.run(
232
+ cmd, check=True, text=True, stdout=f, stderr=subprocess.PIPE
233
+ )
234
+ stdout_capture = ""
235
+ output_files_list = [str(output_file)]
236
+ else:
237
+ result = subprocess.run(
238
+ cmd, check=True, text=True, capture_output=True
239
+ )
240
+ stdout_capture = result.stdout
241
+ output_files_list = []
242
+
243
+ return {
244
+ "command_executed": " ".join(cmd),
245
+ "stdout": stdout_capture,
246
+ "stderr": result.stderr,
247
+ "output_files": output_files_list,
248
+ }
249
+ except subprocess.CalledProcessError as e:
250
+ raise RuntimeError(
251
+ f"bedops element-of failed with exit code {e.returncode}\n"
252
+ f"Stderr: {e.stderr}\n"
253
+ f"Stdout: {e.stdout}\n"
254
+ f"Command: {' '.join(cmd)}"
255
+ ) from e
256
+
257
+ @mcp.tool()
258
+ def bedops_intersect(
259
+ files: List[Path],
260
+ chrom: Optional[str] = None,
261
+ ec: bool = False,
262
+ header: bool = False,
263
+ range_str: Optional[str] = None,
264
+ output_file: Optional[Path] = None,
265
+ ) -> dict:
266
+ """
267
+ Computes the intersection of two or more BED files.
268
+
269
+ This corresponds to the `bedops -i` or `bedops --intersect` operation.
270
+ It returns regions that are common to all input files.
271
+
272
+ Args:
273
+ files: A list of two or more input BED/Starch files. All files must be sorted.
274
+ chrom: Process data for the given chromosome only.
275
+ ec: Error check input files (slower).
276
+ header: Accept headers (VCF, GFF, SAM, BED, WIG) in any input file.
277
+ range_str: Pad coordinates. Use 'L:R' format (e.g., '-10:20') or a
278
+ single value 'S' for symmetric padding (e.g., '100').
279
+ output_file: Optional path to save the output. If not provided,
280
+ output is returned as a string in the result dictionary.
281
+
282
+ Returns:
283
+ A dictionary containing the command executed, stdout, stderr, and a
284
+ list of output files generated.
285
+ """
286
+ if len(files) < 2:
287
+ raise ValueError("At least two input files must be provided for the intersect operation.")
288
+ for file_path in files:
289
+ if not file_path.exists():
290
+ raise FileNotFoundError(f"Input file not found: {file_path}")
291
+
292
+ cmd = ["bedops"]
293
+
294
+ if chrom:
295
+ cmd.extend(["--chrom", chrom])
296
+ if ec:
297
+ cmd.append("--ec")
298
+ if header:
299
+ cmd.append("--header")
300
+ if range_str:
301
+ cmd.extend(["--range", range_str])
302
+
303
+ cmd.append("--intersect")
304
+ cmd.extend([str(p) for p in files])
305
+
306
+ try:
307
+ if output_file:
308
+ with open(output_file, "w") as f:
309
+ result = subprocess.run(
310
+ cmd, check=True, text=True, stdout=f, stderr=subprocess.PIPE
311
+ )
312
+ stdout_capture = ""
313
+ output_files_list = [str(output_file)]
314
+ else:
315
+ result = subprocess.run(
316
+ cmd, check=True, text=True, capture_output=True
317
+ )
318
+ stdout_capture = result.stdout
319
+ output_files_list = []
320
+
321
+ return {
322
+ "command_executed": " ".join(cmd),
323
+ "stdout": stdout_capture,
324
+ "stderr": result.stderr,
325
+ "output_files": output_files_list,
326
+ }
327
+ except subprocess.CalledProcessError as e:
328
+ raise RuntimeError(
329
+ f"bedops intersect failed with exit code {e.returncode}\n"
330
+ f"Stderr: {e.stderr}\n"
331
+ f"Stdout: {e.stdout}\n"
332
+ f"Command: {' '.join(cmd)}"
333
+ ) from e
334
+
335
+ @mcp.tool()
336
+ def bedops_merge(
337
+ files: List[Path],
338
+ chrom: Optional[str] = None,
339
+ ec: bool = False,
340
+ header: bool = False,
341
+ range_str: Optional[str] = None,
342
+ output_file: Optional[Path] = None,
343
+ ) -> dict:
344
+ """
345
+ Merges overlapping regions from one or more BED files.
346
+
347
+ This corresponds to the `bedops -m` or `bedops --merge` operation.
348
+ It combines overlapping or adjacent intervals into a single, larger interval.
349
+
350
+ Args:
351
+ files: A list of one or more input BED/Starch files. Must be sorted.
352
+ chrom: Process data for the given chromosome only.
353
+ ec: Error check input files (slower).
354
+ header: Accept headers (VCF, GFF, SAM, BED, WIG) in any input file.
355
+ range_str: Pad coordinates. Use 'L:R' format (e.g., '-10:20') or a
356
+ single value 'S' for symmetric padding (e.g., '100').
357
+ output_file: Optional path to save the output. If not provided,
358
+ output is returned as a string in the result dictionary.
359
+
360
+ Returns:
361
+ A dictionary containing the command executed, stdout, stderr, and a
362
+ list of output files generated.
363
+ """
364
+ if not files:
365
+ raise ValueError("At least one input file must be provided for the merge operation.")
366
+ for file_path in files:
367
+ if not file_path.exists():
368
+ raise FileNotFoundError(f"Input file not found: {file_path}")
369
+
370
+ cmd = ["bedops"]
371
+
372
+ if chrom:
373
+ cmd.extend(["--chrom", chrom])
374
+ if ec:
375
+ cmd.append("--ec")
376
+ if header:
377
+ cmd.append("--header")
378
+ if range_str:
379
+ cmd.extend(["--range", range_str])
380
+
381
+ cmd.append("--merge")
382
+ cmd.extend([str(p) for p in files])
383
+
384
+ try:
385
+ if output_file:
386
+ with open(output_file, "w") as f:
387
+ result = subprocess.run(
388
+ cmd, check=True, text=True, stdout=f, stderr=subprocess.PIPE
389
+ )
390
+ stdout_capture = ""
391
+ output_files_list = [str(output_file)]
392
+ else:
393
+ result = subprocess.run(
394
+ cmd, check=True, text=True, capture_output=True
395
+ )
396
+ stdout_capture = result.stdout
397
+ output_files_list = []
398
+
399
+ return {
400
+ "command_executed": " ".join(cmd),
401
+ "stdout": stdout_capture,
402
+ "stderr": result.stderr,
403
+ "output_files": output_files_list,
404
+ }
405
+ except subprocess.CalledProcessError as e:
406
+ raise RuntimeError(
407
+ f"bedops merge failed with exit code {e.returncode}\n"
408
+ f"Stderr: {e.stderr}\n"
409
+ f"Stdout: {e.stdout}\n"
410
+ f"Command: {' '.join(cmd)}"
411
+ ) from e
412
+
413
+ @mcp.tool()
414
+ def bedops_not_element_of(
415
+ files: List[Path],
416
+ overlap_criterion: str = "100%",
417
+ chrom: Optional[str] = None,
418
+ ec: bool = False,
419
+ header: bool = False,
420
+ range_str: Optional[str] = None,
421
+ output_file: Optional[Path] = None,
422
+ ) -> dict:
423
+ """
424
+ Finds elements in the reference file that DO NOT overlap other files by a specified amount.
425
+
426
+ This corresponds to the `bedops -n` or `bedops --not-element-of` operation.
427
+ It is the inverse of the `element-of` operation.
428
+
429
+ Args:
430
+ files: A list of two or more input BED/Starch files. The first file is
431
+ the reference. All files must be sorted.
432
+ overlap_criterion: The required overlap, as base pairs (e.g., '1') or
433
+ percentage (e.g., '50%'). Defaults to '100%'.
434
+ chrom: Process data for the given chromosome only.
435
+ ec: Error check input files (slower).
436
+ header: Accept headers (VCF, GFF, SAM, BED, WIG) in any input file.
437
+ range_str: Pad coordinates. Use 'L:R' or 'S' format. The first (reference)
438
+ file is NOT padded with this operation.
439
+ output_file: Optional path to save the output. If not provided,
440
+ output is returned as a string in the result dictionary.
441
+
442
+ Returns:
443
+ A dictionary containing the command executed, stdout, stderr, and a
444
+ list of output files generated.
445
+ """
446
+ if len(files) < 2:
447
+ raise ValueError("At least two input files (a reference and one other) must be provided for the not-element-of operation.")
448
+ for file_path in files:
449
+ if not file_path.exists():
450
+ raise FileNotFoundError(f"Input file not found: {file_path}")
451
+
452
+ cmd = ["bedops"]
453
+
454
+ if chrom:
455
+ cmd.extend(["--chrom", chrom])
456
+ if ec:
457
+ cmd.append("--ec")
458
+ if header:
459
+ cmd.append("--header")
460
+ if range_str:
461
+ cmd.extend(["--range", range_str])
462
+
463
+ cmd.extend(["--not-element-of", overlap_criterion])
464
+ cmd.extend([str(p) for p in files])
465
+
466
+ try:
467
+ if output_file:
468
+ with open(output_file, "w") as f:
469
+ result = subprocess.run(
470
+ cmd, check=True, text=True, stdout=f, stderr=subprocess.PIPE
471
+ )
472
+ stdout_capture = ""
473
+ output_files_list = [str(output_file)]
474
+ else:
475
+ result = subprocess.run(
476
+ cmd, check=True, text=True, capture_output=True
477
+ )
478
+ stdout_capture = result.stdout
479
+ output_files_list = []
480
+
481
+ return {
482
+ "command_executed": " ".join(cmd),
483
+ "stdout": stdout_capture,
484
+ "stderr": result.stderr,
485
+ "output_files": output_files_list,
486
+ }
487
+ except subprocess.CalledProcessError as e:
488
+ raise RuntimeError(
489
+ f"bedops not-element-of failed with exit code {e.returncode}\n"
490
+ f"Stderr: {e.stderr}\n"
491
+ f"Stdout: {e.stdout}\n"
492
+ f"Command: {' '.join(cmd)}"
493
+ ) from e
494
+
495
+ @mcp.tool()
496
+ def bedops_partition(
497
+ files: List[Path],
498
+ chrom: Optional[str] = None,
499
+ ec: bool = False,
500
+ header: bool = False,
501
+ range_str: Optional[str] = None,
502
+ output_file: Optional[Path] = None,
503
+ ) -> dict:
504
+ """
505
+ Partitions the input BED file(s) into disjoint segments.
506
+
507
+ This corresponds to the `bedops -p` or `bedops --partition` operation.
508
+ It breaks the input regions into non-overlapping segments, reporting each
509
+ new segment and which input files it came from.
510
+
511
+ Args:
512
+ files: A list of one or more input BED/Starch files. Must be sorted.
513
+ chrom: Process data for the given chromosome only.
514
+ ec: Error check input files (slower).
515
+ header: Accept headers (VCF, GFF, SAM, BED, WIG) in any input file.
516
+ range_str: Pad coordinates. Use 'L:R' format (e.g., '-10:20') or a
517
+ single value 'S' for symmetric padding (e.g., '100').
518
+ output_file: Optional path to save the output. If not provided,
519
+ output is returned as a string in the result dictionary.
520
+
521
+ Returns:
522
+ A dictionary containing the command executed, stdout, stderr, and a
523
+ list of output files generated.
524
+ """
525
+ if not files:
526
+ raise ValueError("At least one input file must be provided for the partition operation.")
527
+ for file_path in files:
528
+ if not file_path.exists():
529
+ raise FileNotFoundError(f"Input file not found: {file_path}")
530
+
531
+ cmd = ["bedops"]
532
+
533
+ if chrom:
534
+ cmd.extend(["--chrom", chrom])
535
+ if ec:
536
+ cmd.append("--ec")
537
+ if header:
538
+ cmd.append("--header")
539
+ if range_str:
540
+ cmd.extend(["--range", range_str])
541
+
542
+ cmd.append("--partition")
543
+ cmd.extend([str(p) for p in files])
544
+
545
+ try:
546
+ if output_file:
547
+ with open(output_file, "w") as f:
548
+ result = subprocess.run(
549
+ cmd, check=True, text=True, stdout=f, stderr=subprocess.PIPE
550
+ )
551
+ stdout_capture = ""
552
+ output_files_list = [str(output_file)]
553
+ else:
554
+ result = subprocess.run(
555
+ cmd, check=True, text=True, capture_output=True
556
+ )
557
+ stdout_capture = result.stdout
558
+ output_files_list = []
559
+
560
+ return {
561
+ "command_executed": " ".join(cmd),
562
+ "stdout": stdout_capture,
563
+ "stderr": result.stderr,
564
+ "output_files": output_files_list,
565
+ }
566
+ except subprocess.CalledProcessError as e:
567
+ raise RuntimeError(
568
+ f"bedops partition failed with exit code {e.returncode}\n"
569
+ f"Stderr: {e.stderr}\n"
570
+ f"Stdout: {e.stdout}\n"
571
+ f"Command: {' '.join(cmd)}"
572
+ ) from e
573
+
574
+ @mcp.tool()
575
+ def bedops_symmdiff(
576
+ files: List[Path],
577
+ chrom: Optional[str] = None,
578
+ ec: bool = False,
579
+ header: bool = False,
580
+ range_str: Optional[str] = None,
581
+ output_file: Optional[Path] = None,
582
+ ) -> dict:
583
+ """
584
+ Computes the symmetric difference of two or more BED files.
585
+
586
+ This corresponds to the `bedops -s` or `bedops --symmdiff` operation.
587
+ It returns regions that are unique to any of the input files (i.e., not
588
+ present in their intersection).
589
+
590
+ Args:
591
+ files: A list of two or more input BED/Starch files. All files must be sorted.
592
+ chrom: Process data for the given chromosome only.
593
+ ec: Error check input files (slower).
594
+ header: Accept headers (VCF, GFF, SAM, BED, WIG) in any input file.
595
+ range_str: Pad coordinates. Use 'L:R' format (e.g., '-10:20') or a
596
+ single value 'S' for symmetric padding (e.g., '100').
597
+ output_file: Optional path to save the output. If not provided,
598
+ output is returned as a string in the result dictionary.
599
+
600
+ Returns:
601
+ A dictionary containing the command executed, stdout, stderr, and a
602
+ list of output files generated.
603
+ """
604
+ if len(files) < 2:
605
+ raise ValueError("At least two input files must be provided for the symmetric difference operation.")
606
+ for file_path in files:
607
+ if not file_path.exists():
608
+ raise FileNotFoundError(f"Input file not found: {file_path}")
609
+
610
+ cmd = ["bedops"]
611
+
612
+ if chrom:
613
+ cmd.extend(["--chrom", chrom])
614
+ if ec:
615
+ cmd.append("--ec")
616
+ if header:
617
+ cmd.append("--header")
618
+ if range_str:
619
+ cmd.extend(["--range", range_str])
620
+
621
+ cmd.append("--symmdiff")
622
+ cmd.extend([str(p) for p in files])
623
+
624
+ try:
625
+ if output_file:
626
+ with open(output_file, "w") as f:
627
+ result = subprocess.run(
628
+ cmd, check=True, text=True, stdout=f, stderr=subprocess.PIPE
629
+ )
630
+ stdout_capture = ""
631
+ output_files_list = [str(output_file)]
632
+ else:
633
+ result = subprocess.run(
634
+ cmd, check=True, text=True, capture_output=True
635
+ )
636
+ stdout_capture = result.stdout
637
+ output_files_list = []
638
+
639
+ return {
640
+ "command_executed": " ".join(cmd),
641
+ "stdout": stdout_capture,
642
+ "stderr": result.stderr,
643
+ "output_files": output_files_list,
644
+ }
645
+ except subprocess.CalledProcessError as e:
646
+ raise RuntimeError(
647
+ f"bedops symmdiff failed with exit code {e.returncode}\n"
648
+ f"Stderr: {e.stderr}\n"
649
+ f"Stdout: {e.stdout}\n"
650
+ f"Command: {' '.join(cmd)}"
651
+ ) from e
652
+
653
+ @mcp.tool()
654
+ def bedops_everything(
655
+ files: List[Path],
656
+ chrom: Optional[str] = None,
657
+ ec: bool = False,
658
+ header: bool = False,
659
+ range_str: Optional[str] = None,
660
+ output_file: Optional[Path] = None,
661
+ ) -> dict:
662
+ """
663
+ Returns the union of all elements from input files without merging.
664
+
665
+ This corresponds to the `bedops -u` or `bedops --everything` operation.
666
+ It effectively concatenates the input files while maintaining sort order
667
+ and preserving all original columns.
668
+
669
+ Args:
670
+ files: A list of one or more input BED/Starch files. Must be sorted.
671
+ chrom: Process data for the given chromosome only.
672
+ ec: Error check input files (slower).
673
+ header: Accept headers (VCF, GFF, SAM, BED, WIG) in any input file.
674
+ range_str: Pad coordinates. Use 'L:R' format (e.g., '-10:20') or a
675
+ single value 'S' for symmetric padding (e.g., '100').
676
+ output_file: Optional path to save the output. If not provided,
677
+ output is returned as a string in the result dictionary.
678
+
679
+ Returns:
680
+ A dictionary containing the command executed, stdout, stderr, and a
681
+ list of output files generated.
682
+ """
683
+ if not files:
684
+ raise ValueError("At least one input file must be provided for the everything operation.")
685
+ for file_path in files:
686
+ if not file_path.exists():
687
+ raise FileNotFoundError(f"Input file not found: {file_path}")
688
+
689
+ cmd = ["bedops"]
690
+
691
+ if chrom:
692
+ cmd.extend(["--chrom", chrom])
693
+ if ec:
694
+ cmd.append("--ec")
695
+ if header:
696
+ cmd.append("--header")
697
+ if range_str:
698
+ cmd.extend(["--range", range_str])
699
+
700
+ cmd.append("--everything")
701
+ cmd.extend([str(p) for p in files])
702
+
703
+ try:
704
+ if output_file:
705
+ with open(output_file, "w") as f:
706
+ result = subprocess.run(
707
+ cmd, check=True, text=True, stdout=f, stderr=subprocess.PIPE
708
+ )
709
+ stdout_capture = ""
710
+ output_files_list = [str(output_file)]
711
+ else:
712
+ result = subprocess.run(
713
+ cmd, check=True, text=True, capture_output=True
714
+ )
715
+ stdout_capture = result.stdout
716
+ output_files_list = []
717
+
718
+ return {
719
+ "command_executed": " ".join(cmd),
720
+ "stdout": stdout_capture,
721
+ "stderr": result.stderr,
722
+ "output_files": output_files_list,
723
+ }
724
+ except subprocess.CalledProcessError as e:
725
+ raise RuntimeError(
726
+ f"bedops everything failed with exit code {e.returncode}\n"
727
+ f"Stderr: {e.stderr}\n"
728
+ f"Stdout: {e.stdout}\n"
729
+ f"Command: {' '.join(cmd)}"
730
+ ) from e
731
+
732
+ @mcp.tool()
733
+ def bedops_chop(
734
+ files: List[Path],
735
+ bp: int = 1,
736
+ stagger: Optional[int] = None,
737
+ exclusive_chop: bool = False,
738
+ chrom: Optional[str] = None,
739
+ ec: bool = False,
740
+ header: bool = False,
741
+ range_str: Optional[str] = None,
742
+ output_file: Optional[Path] = None,
743
+ ) -> dict:
744
+ """
745
+ Chops elements into fixed-size, potentially staggered sub-elements.
746
+
747
+ This corresponds to the `bedops -w` or `bedops --chop` operation.
748
+
749
+ Args:
750
+ files: A list of one or more input BED/Starch files. Must be sorted.
751
+ bp: The size in base pairs of each chopped element. Defaults to 1.
752
+ stagger: The stagger distance in nucleotides. If not set, no staggering is done.
753
+ exclusive_chop: If True, removes single-base elements that can result
754
+ from chopping (-x flag).
755
+ chrom: Process data for the given chromosome only.
756
+ ec: Error check input files (slower).
757
+ header: Accept headers (VCF, GFF, SAM, BED, WIG) in any input file.
758
+ range_str: Pad coordinates. Use 'L:R' format (e.g., '-10:20') or a
759
+ single value 'S' for symmetric padding (e.g., '100').
760
+ output_file: Optional path to save the output. If not provided,
761
+ output is returned as a string in the result dictionary.
762
+
763
+ Returns:
764
+ A dictionary containing the command executed, stdout, stderr, and a
765
+ list of output files generated.
766
+ """
767
+ if not files:
768
+ raise ValueError("At least one input file must be provided for the chop operation.")
769
+ for file_path in files:
770
+ if not file_path.exists():
771
+ raise FileNotFoundError(f"Input file not found: {file_path}")
772
+
773
+ cmd = ["bedops"]
774
+
775
+ if chrom:
776
+ cmd.extend(["--chrom", chrom])
777
+ if ec:
778
+ cmd.append("--ec")
779
+ if header:
780
+ cmd.append("--header")
781
+ if range_str:
782
+ cmd.extend(["--range", range_str])
783
+
784
+ cmd.extend(["--chop", str(bp)])
785
+ if stagger is not None:
786
+ cmd.extend(["--stagger", str(stagger)])
787
+ if exclusive_chop:
788
+ cmd.append("-x")
789
+
790
+ cmd.extend([str(p) for p in files])
791
+
792
+ try:
793
+ if output_file:
794
+ with open(output_file, "w") as f:
795
+ result = subprocess.run(
796
+ cmd, check=True, text=True, stdout=f, stderr=subprocess.PIPE
797
+ )
798
+ stdout_capture = ""
799
+ output_files_list = [str(output_file)]
800
+ else:
801
+ result = subprocess.run(
802
+ cmd, check=True, text=True, capture_output=True
803
+ )
804
+ stdout_capture = result.stdout
805
+ output_files_list = []
806
+
807
+ return {
808
+ "command_executed": " ".join(cmd),
809
+ "stdout": stdout_capture,
810
+ "stderr": result.stderr,
811
+ "output_files": output_files_list,
812
+ }
813
+ except subprocess.CalledProcessError as e:
814
+ raise RuntimeError(
815
+ f"bedops chop failed with exit code {e.returncode}\n"
816
+ f"Stderr: {e.stderr}\n"
817
+ f"Stdout: {e.stdout}\n"
818
+ f"Command: {' '.join(cmd)}"
819
+ ) from e
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/app/bedops_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_bedops/app/bedops_server.py')
11
+ SERVER_NAME = 'biosci_bedops'
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_bedops/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-bedops:
5
+ build: .
6
+ image: mcp-bedops:latest
7
+ container_name: mcp-bedops
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=bedops
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_bedops/environment.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ name: mcp-tool
3
+ channels:
4
+ - bioconda
5
+ - conda-forge
6
+ - defaults
7
+ dependencies:
8
+ - bedops
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedops/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedtools/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 bedtools via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bedtools -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 bedtools_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/bedtools_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/bedtools_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedtools/app/bedtools_server.py ADDED
@@ -0,0 +1,700 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import tempfile
3
+ from pathlib import Path
4
+ from typing import List, Optional
5
+
6
+ # This is a placeholder for the MCP decorator.
7
+ # In a real MCP environment, this would be provided by the MCP framework.
8
+ def tool(func):
9
+ """A dummy decorator to stand in for @mcp.tool()."""
10
+ return func
11
+
12
+ mcp = type("mcp", (), {"tool": tool})
13
+
14
+
15
+ @mcp.tool()
16
+ def intersect(
17
+ a: Path,
18
+ b: List[Path],
19
+ output: Optional[Path] = None,
20
+ wa: bool = False,
21
+ wb: bool = False,
22
+ loj: bool = False,
23
+ wo: bool = False,
24
+ wao: bool = False,
25
+ u: bool = False,
26
+ c: bool = False,
27
+ v: bool = False,
28
+ ubam: bool = False,
29
+ s: bool = False,
30
+ S: bool = False,
31
+ f: float = 1e-9,
32
+ F: float = 1e-9,
33
+ r: bool = False,
34
+ e: bool = False,
35
+ split: bool = False,
36
+ g: Optional[Path] = None,
37
+ header: bool = False,
38
+ bed: bool = False,
39
+ sorted: bool = False,
40
+ names: Optional[str] = None,
41
+ filenames: bool = False,
42
+ nonamecheck: bool = False,
43
+ ):
44
+ """
45
+ Find overlapping intervals in two or more BED/GFF/VCF/BAM files.
46
+
47
+ This tool allows one to screen for overlaps between two sets of genomic features.
48
+ """
49
+ # Input validation
50
+ if not a.exists():
51
+ raise FileNotFoundError(f"Input file -a does not exist: {a}")
52
+ for b_file in b:
53
+ if not b_file.exists():
54
+ raise FileNotFoundError(f"Input file in -b list does not exist: {b_file}")
55
+ if g and not g.exists():
56
+ raise FileNotFoundError(f"Genome file -g does not exist: {g}")
57
+
58
+ exclusive_flags = [u, c, v, wo, wao]
59
+ if sum(exclusive_flags) > 1:
60
+ raise ValueError("Options -u, -c, -v, -wo, -wao are mutually exclusive.")
61
+ if s and S:
62
+ raise ValueError("Options -s and -S are mutually exclusive.")
63
+ if f < 0.0 or f > 1.0:
64
+ raise ValueError("-f (fraction) must be between 0.0 and 1.0.")
65
+ if F < 0.0 or F > 1.0:
66
+ raise ValueError("-F (fraction) must be between 0.0 and 1.0.")
67
+ if sorted and not g:
68
+ raise ValueError("The -sorted option requires a genome file (-g).")
69
+
70
+ # Command construction
71
+ cmd = ["bedtools", "intersect", "-a", str(a), "-b"]
72
+ cmd.extend([str(p) for p in b])
73
+
74
+ if wa: cmd.append("-wa")
75
+ if wb: cmd.append("-wb")
76
+ if loj: cmd.append("-loj")
77
+ if wo: cmd.append("-wo")
78
+ if wao: cmd.append("-wao")
79
+ if u: cmd.append("-u")
80
+ if c: cmd.append("-c")
81
+ if v: cmd.append("-v")
82
+ if ubam: cmd.append("-ubam")
83
+ if s: cmd.append("-s")
84
+ if S: cmd.append("-S")
85
+ if f != 1e-9: cmd.extend(["-f", str(f)])
86
+ if F != 1e-9: cmd.extend(["-F", str(F)])
87
+ if r: cmd.append("-r")
88
+ if e: cmd.append("-e")
89
+ if split: cmd.append("-split")
90
+ if g: cmd.extend(["-g", str(g)])
91
+ if header: cmd.append("-header")
92
+ if bed: cmd.append("-bed")
93
+ if sorted: cmd.append("-sorted")
94
+ if names: cmd.extend(["-names", names])
95
+ if filenames: cmd.append("-filenames")
96
+ if nonamecheck: cmd.append("-nonamecheck")
97
+
98
+ # Subprocess execution
99
+ command_executed = " ".join(cmd)
100
+ output_files = []
101
+ stdout_capture, stderr_capture = "", ""
102
+
103
+ try:
104
+ if output:
105
+ output_files.append(str(output))
106
+ with open(output, "w") as f_out:
107
+ result = subprocess.run(
108
+ cmd, check=True, text=True, stdout=f_out, stderr=subprocess.PIPE
109
+ )
110
+ stderr_capture = result.stderr
111
+ else:
112
+ result = subprocess.run(
113
+ cmd, check=True, text=True, capture_output=True
114
+ )
115
+ stdout_capture = result.stdout
116
+ stderr_capture = result.stderr
117
+ except subprocess.CalledProcessError as e:
118
+ return {
119
+ "command_executed": command_executed,
120
+ "stdout": e.stdout or "",
121
+ "stderr": e.stderr or "CalledProcessError with no stderr.",
122
+ "output_files": [],
123
+ "return_code": e.returncode,
124
+ }
125
+
126
+ return {
127
+ "command_executed": command_executed,
128
+ "stdout": stdout_capture,
129
+ "stderr": stderr_capture,
130
+ "output_files": output_files,
131
+ }
132
+
133
+
134
+ @mcp.tool()
135
+ def merge(
136
+ i: Path,
137
+ output: Optional[Path] = None,
138
+ s: bool = False,
139
+ S: Optional[str] = None,
140
+ d: int = 0,
141
+ c: Optional[str] = None,
142
+ o: Optional[str] = None,
143
+ header: bool = False,
144
+ delim: str = ";",
145
+ n: bool = False,
146
+ nms: bool = False,
147
+ scores: Optional[str] = None,
148
+ bed: bool = False,
149
+ prec: int = 5,
150
+ ):
151
+ """
152
+ Merge overlapping features in a BED/GFF/VCF file.
153
+
154
+ This tool combines overlapping or "book-ended" features into a single feature.
155
+ """
156
+ # Input validation
157
+ if not i.exists():
158
+ raise FileNotFoundError(f"Input file -i does not exist: {i}")
159
+ if S and S not in ["+", "-"]:
160
+ raise ValueError("Option -S must be either '+' or '-'.")
161
+ if s and S:
162
+ raise ValueError("Options -s and -S are mutually exclusive.")
163
+ if d < 0:
164
+ raise ValueError("Option -d (distance) must be a non-negative integer.")
165
+ if (c and not o) or (o and not c):
166
+ raise ValueError("Options -c and -o must be used together.")
167
+ if c and o:
168
+ if len(c.split(',')) != len(o.split(',')):
169
+ raise ValueError("The number of columns in -c must match the number of operations in -o.")
170
+
171
+ # Command construction
172
+ cmd = ["bedtools", "merge", "-i", str(i)]
173
+
174
+ if s: cmd.append("-s")
175
+ if S: cmd.extend(["-S", S])
176
+ if d > 0: cmd.extend(["-d", str(d)])
177
+ if c: cmd.extend(["-c", c])
178
+ if o: cmd.extend(["-o", o])
179
+ if header: cmd.append("-header")
180
+ if delim != ";": cmd.extend(["-delim", delim])
181
+ if n: cmd.append("-n")
182
+ if nms: cmd.append("-nms")
183
+ if scores: cmd.extend(["-scores", scores])
184
+ if bed: cmd.append("-bed")
185
+ if prec != 5: cmd.extend(["-prec", str(prec)])
186
+
187
+ # Subprocess execution
188
+ command_executed = " ".join(cmd)
189
+ output_files = []
190
+ stdout_capture, stderr_capture = "", ""
191
+
192
+ try:
193
+ if output:
194
+ output_files.append(str(output))
195
+ with open(output, "w") as f_out:
196
+ result = subprocess.run(
197
+ cmd, check=True, text=True, stdout=f_out, stderr=subprocess.PIPE
198
+ )
199
+ stderr_capture = result.stderr
200
+ else:
201
+ result = subprocess.run(
202
+ cmd, check=True, text=True, capture_output=True
203
+ )
204
+ stdout_capture = result.stdout
205
+ stderr_capture = result.stderr
206
+ except subprocess.CalledProcessError as e:
207
+ return {
208
+ "command_executed": command_executed,
209
+ "stdout": e.stdout or "",
210
+ "stderr": e.stderr or "CalledProcessError with no stderr.",
211
+ "output_files": [],
212
+ "return_code": e.returncode,
213
+ }
214
+
215
+ return {
216
+ "command_executed": command_executed,
217
+ "stdout": stdout_capture,
218
+ "stderr": stderr_capture,
219
+ "output_files": output_files,
220
+ }
221
+
222
+
223
+ @mcp.tool()
224
+ def subtract(
225
+ a: Path,
226
+ b: List[Path],
227
+ output: Optional[Path] = None,
228
+ f: float = 1e-9,
229
+ F: float = 1e-9,
230
+ r: bool = False,
231
+ e: bool = False,
232
+ s: bool = False,
233
+ S: bool = False,
234
+ A: bool = False,
235
+ B: bool = False,
236
+ N: bool = False,
237
+ header: bool = False,
238
+ g: Optional[Path] = None,
239
+ ):
240
+ """
241
+ Remove overlapping intervals from a BED/GFF/VCF file.
242
+
243
+ This tool removes portions of features in file A that are overlapped by features in file(s) B.
244
+ """
245
+ # Input validation
246
+ if not a.exists():
247
+ raise FileNotFoundError(f"Input file -a does not exist: {a}")
248
+ for b_file in b:
249
+ if not b_file.exists():
250
+ raise FileNotFoundError(f"Input file in -b list does not exist: {b_file}")
251
+ if g and not g.exists():
252
+ raise FileNotFoundError(f"Genome file -g does not exist: {g}")
253
+ if A and B:
254
+ raise ValueError("Options -A and -B are mutually exclusive.")
255
+ if s and S:
256
+ raise ValueError("Options -s and -S are mutually exclusive.")
257
+
258
+ # Command construction
259
+ cmd = ["bedtools", "subtract", "-a", str(a), "-b"]
260
+ cmd.extend([str(p) for p in b])
261
+
262
+ if f != 1e-9: cmd.extend(["-f", str(f)])
263
+ if F != 1e-9: cmd.extend(["-F", str(F)])
264
+ if r: cmd.append("-r")
265
+ if e: cmd.append("-e")
266
+ if s: cmd.append("-s")
267
+ if S: cmd.append("-S")
268
+ if A: cmd.append("-A")
269
+ if B: cmd.append("-B")
270
+ if N: cmd.append("-N")
271
+ if header: cmd.append("-header")
272
+ if g: cmd.extend(["-g", str(g)])
273
+
274
+ # Subprocess execution
275
+ command_executed = " ".join(cmd)
276
+ output_files = []
277
+ stdout_capture, stderr_capture = "", ""
278
+
279
+ try:
280
+ if output:
281
+ output_files.append(str(output))
282
+ with open(output, "w") as f_out:
283
+ result = subprocess.run(
284
+ cmd, check=True, text=True, stdout=f_out, stderr=subprocess.PIPE
285
+ )
286
+ stderr_capture = result.stderr
287
+ else:
288
+ result = subprocess.run(
289
+ cmd, check=True, text=True, capture_output=True
290
+ )
291
+ stdout_capture = result.stdout
292
+ stderr_capture = result.stderr
293
+ except subprocess.CalledProcessError as e:
294
+ return {
295
+ "command_executed": command_executed,
296
+ "stdout": e.stdout or "",
297
+ "stderr": e.stderr or "CalledProcessError with no stderr.",
298
+ "output_files": [],
299
+ "return_code": e.returncode,
300
+ }
301
+
302
+ return {
303
+ "command_executed": command_executed,
304
+ "stdout": stdout_capture,
305
+ "stderr": stderr_capture,
306
+ "output_files": output_files,
307
+ }
308
+
309
+
310
+ @mcp.tool()
311
+ def slop(
312
+ i: Path,
313
+ g: Path,
314
+ output: Optional[Path] = None,
315
+ b: int = 0,
316
+ l: int = 0,
317
+ r: int = 0,
318
+ s: bool = False,
319
+ pct: bool = False,
320
+ header: bool = False,
321
+ ):
322
+ """
323
+ Increase the size of features in a BED/GFF/VCF file.
324
+
325
+ This tool will increase the size of each feature in a feature file by a user-defined number of bases.
326
+ """
327
+ # Input validation
328
+ if not i.exists():
329
+ raise FileNotFoundError(f"Input file -i does not exist: {i}")
330
+ if not g.exists():
331
+ raise FileNotFoundError(f"Genome file -g does not exist: {g}")
332
+ if b != 0 and (l != 0 or r != 0):
333
+ raise ValueError("Option -b cannot be used with -l or -r.")
334
+
335
+ # Command construction
336
+ cmd = ["bedtools", "slop", "-i", str(i), "-g", str(g)]
337
+
338
+ if b != 0: cmd.extend(["-b", str(b)])
339
+ if l != 0: cmd.extend(["-l", str(l)])
340
+ if r != 0: cmd.extend(["-r", str(r)])
341
+ if s: cmd.append("-s")
342
+ if pct: cmd.append("-pct")
343
+ if header: cmd.append("-header")
344
+
345
+ # Subprocess execution
346
+ command_executed = " ".join(cmd)
347
+ output_files = []
348
+ stdout_capture, stderr_capture = "", ""
349
+
350
+ try:
351
+ if output:
352
+ output_files.append(str(output))
353
+ with open(output, "w") as f_out:
354
+ result = subprocess.run(
355
+ cmd, check=True, text=True, stdout=f_out, stderr=subprocess.PIPE
356
+ )
357
+ stderr_capture = result.stderr
358
+ else:
359
+ result = subprocess.run(
360
+ cmd, check=True, text=True, capture_output=True
361
+ )
362
+ stdout_capture = result.stdout
363
+ stderr_capture = result.stderr
364
+ except subprocess.CalledProcessError as e:
365
+ return {
366
+ "command_executed": command_executed,
367
+ "stdout": e.stdout or "",
368
+ "stderr": e.stderr or "CalledProcessError with no stderr.",
369
+ "output_files": [],
370
+ "return_code": e.returncode,
371
+ }
372
+
373
+ return {
374
+ "command_executed": command_executed,
375
+ "stdout": stdout_capture,
376
+ "stderr": stderr_capture,
377
+ "output_files": output_files,
378
+ }
379
+
380
+
381
+ @mcp.tool()
382
+ def getfasta(
383
+ fi: Path,
384
+ bed: Path,
385
+ fo: Optional[Path] = None,
386
+ s: bool = False,
387
+ split: bool = False,
388
+ name: bool = False,
389
+ name_plus: bool = False,
390
+ tab: bool = False,
391
+ full_header: bool = False,
392
+ ):
393
+ """
394
+ Extract DNA sequences from a FASTA file based on BED/GFF/VCF coordinates.
395
+ """
396
+ # Input validation
397
+ if not fi.exists():
398
+ raise FileNotFoundError(f"FASTA input file -fi does not exist: {fi}")
399
+ if not bed.exists():
400
+ raise FileNotFoundError(f"BED/GFF/VCF file -bed does not exist: {bed}")
401
+ if name and name_plus:
402
+ raise ValueError("Options -name and -name+ are mutually exclusive.")
403
+
404
+ # Command construction
405
+ cmd = ["bedtools", "getfasta", "-fi", str(fi), "-bed", str(bed)]
406
+
407
+ if s: cmd.append("-s")
408
+ if split: cmd.append("-split")
409
+ if name: cmd.append("-name")
410
+ if name_plus: cmd.append("-name+")
411
+ if tab: cmd.append("-tab")
412
+ if full_header: cmd.append("-fullHeader")
413
+ if fo: cmd.extend(["-fo", str(fo)])
414
+
415
+ # Subprocess execution
416
+ command_executed = " ".join(cmd)
417
+ output_files = []
418
+ stdout_capture, stderr_capture = "", ""
419
+
420
+ try:
421
+ # getfasta is unique in that it has a dedicated -fo parameter
422
+ # and doesn't typically write to stdout if -fo is used.
423
+ result = subprocess.run(
424
+ cmd, check=True, text=True, capture_output=True
425
+ )
426
+ stdout_capture = result.stdout
427
+ stderr_capture = result.stderr
428
+ if fo:
429
+ output_files.append(str(fo))
430
+
431
+ except subprocess.CalledProcessError as e:
432
+ return {
433
+ "command_executed": command_executed,
434
+ "stdout": e.stdout or "",
435
+ "stderr": e.stderr or "CalledProcessError with no stderr.",
436
+ "output_files": [],
437
+ "return_code": e.returncode,
438
+ }
439
+
440
+ return {
441
+ "command_executed": command_executed,
442
+ "stdout": stdout_capture,
443
+ "stderr": stderr_capture,
444
+ "output_files": output_files,
445
+ }
446
+
447
+
448
+ @mcp.tool()
449
+ def sort(
450
+ i: Path,
451
+ output: Optional[Path] = None,
452
+ header: bool = False,
453
+ g: Optional[Path] = None,
454
+ faidx: Optional[Path] = None,
455
+ sizeA: bool = False,
456
+ sizeD: bool = False,
457
+ chrThenSizeA: bool = False,
458
+ chrThenSizeD: bool = False,
459
+ chrThenScoreA: bool = False,
460
+ chrThenScoreD: bool = False,
461
+ ):
462
+ """
463
+ Sort a BED/GFF/VCF file by chromosome and then by start position.
464
+ """
465
+ # Input validation
466
+ if not i.exists():
467
+ raise FileNotFoundError(f"Input file -i does not exist: {i}")
468
+ if g and not g.exists():
469
+ raise FileNotFoundError(f"Genome file -g does not exist: {g}")
470
+ if faidx and not faidx.exists():
471
+ raise FileNotFoundError(f"FASTA index file -faidx does not exist: {faidx}")
472
+
473
+ sort_flags = [sizeA, sizeD, chrThenSizeA, chrThenSizeD, chrThenScoreA, chrThenScoreD]
474
+ if sum(sort_flags) > 1:
475
+ raise ValueError("Multiple sorting order flags were provided, but only one is allowed.")
476
+
477
+ # Command construction
478
+ cmd = ["bedtools", "sort", "-i", str(i)]
479
+
480
+ if header: cmd.append("-header")
481
+ if g: cmd.extend(["-g", str(g)])
482
+ if faidx: cmd.extend(["-faidx", str(faidx)])
483
+ if sizeA: cmd.append("-sizeA")
484
+ if sizeD: cmd.append("-sizeD")
485
+ if chrThenSizeA: cmd.append("-chrThenSizeA")
486
+ if chrThenSizeD: cmd.append("-chrThenSizeD")
487
+ if chrThenScoreA: cmd.append("-chrThenScoreA")
488
+ if chrThenScoreD: cmd.append("-chrThenScoreD")
489
+
490
+ # Subprocess execution
491
+ command_executed = " ".join(cmd)
492
+ output_files = []
493
+ stdout_capture, stderr_capture = "", ""
494
+
495
+ try:
496
+ if output:
497
+ output_files.append(str(output))
498
+ with open(output, "w") as f_out:
499
+ result = subprocess.run(
500
+ cmd, check=True, text=True, stdout=f_out, stderr=subprocess.PIPE
501
+ )
502
+ stderr_capture = result.stderr
503
+ else:
504
+ result = subprocess.run(
505
+ cmd, check=True, text=True, capture_output=True
506
+ )
507
+ stdout_capture = result.stdout
508
+ stderr_capture = result.stderr
509
+ except subprocess.CalledProcessError as e:
510
+ return {
511
+ "command_executed": command_executed,
512
+ "stdout": e.stdout or "",
513
+ "stderr": e.stderr or "CalledProcessError with no stderr.",
514
+ "output_files": [],
515
+ "return_code": e.returncode,
516
+ }
517
+
518
+ return {
519
+ "command_executed": command_executed,
520
+ "stdout": stdout_capture,
521
+ "stderr": stderr_capture,
522
+ "output_files": output_files,
523
+ }
524
+
525
+
526
+ @mcp.tool()
527
+ def coverage(
528
+ a: Path,
529
+ b: List[Path],
530
+ output: Optional[Path] = None,
531
+ s: bool = False,
532
+ S: bool = False,
533
+ f: float = 1e-9,
534
+ F: float = 1e-9,
535
+ r: bool = False,
536
+ e: bool = False,
537
+ split: bool = False,
538
+ d: bool = False,
539
+ counts: bool = False,
540
+ hist: bool = False,
541
+ mean: bool = False,
542
+ g: Optional[Path] = None,
543
+ header: bool = False,
544
+ sorted: bool = False,
545
+ ):
546
+ """
547
+ Compute the coverage of features in file A on features in file(s) B.
548
+ """
549
+ # Input validation
550
+ if not a.exists():
551
+ raise FileNotFoundError(f"Input file -a does not exist: {a}")
552
+ for b_file in b:
553
+ if not b_file.exists():
554
+ raise FileNotFoundError(f"Input file in -b list does not exist: {b_file}")
555
+ if g and not g.exists():
556
+ raise FileNotFoundError(f"Genome file -g does not exist: {g}")
557
+ if s and S:
558
+ raise ValueError("Options -s and -S are mutually exclusive.")
559
+ if sorted and not g:
560
+ raise ValueError("The -sorted option requires a genome file (-g).")
561
+
562
+ # Command construction
563
+ cmd = ["bedtools", "coverage", "-a", str(a), "-b"]
564
+ cmd.extend([str(p) for p in b])
565
+
566
+ if s: cmd.append("-s")
567
+ if S: cmd.append("-S")
568
+ if f != 1e-9: cmd.extend(["-f", str(f)])
569
+ if F != 1e-9: cmd.extend(["-F", str(F)])
570
+ if r: cmd.append("-r")
571
+ if e: cmd.append("-e")
572
+ if split: cmd.append("-split")
573
+ if d: cmd.append("-d")
574
+ if counts: cmd.append("-counts")
575
+ if hist: cmd.append("-hist")
576
+ if mean: cmd.append("-mean")
577
+ if g: cmd.extend(["-g", str(g)])
578
+ if header: cmd.append("-header")
579
+ if sorted: cmd.append("-sorted")
580
+
581
+ # Subprocess execution
582
+ command_executed = " ".join(cmd)
583
+ output_files = []
584
+ stdout_capture, stderr_capture = "", ""
585
+
586
+ try:
587
+ if output:
588
+ output_files.append(str(output))
589
+ with open(output, "w") as f_out:
590
+ result = subprocess.run(
591
+ cmd, check=True, text=True, stdout=f_out, stderr=subprocess.PIPE
592
+ )
593
+ stderr_capture = result.stderr
594
+ else:
595
+ result = subprocess.run(
596
+ cmd, check=True, text=True, capture_output=True
597
+ )
598
+ stdout_capture = result.stdout
599
+ stderr_capture = result.stderr
600
+ except subprocess.CalledProcessError as e:
601
+ return {
602
+ "command_executed": command_executed,
603
+ "stdout": e.stdout or "",
604
+ "stderr": e.stderr or "CalledProcessError with no stderr.",
605
+ "output_files": [],
606
+ "return_code": e.returncode,
607
+ }
608
+
609
+ return {
610
+ "command_executed": command_executed,
611
+ "stdout": stdout_capture,
612
+ "stderr": stderr_capture,
613
+ "output_files": output_files,
614
+ }
615
+
616
+
617
+ @mcp.tool()
618
+ def genomecov(
619
+ i: Path,
620
+ g: Path,
621
+ output: Optional[Path] = None,
622
+ d: bool = False,
623
+ dz: bool = False,
624
+ bga: bool = False,
625
+ bg: bool = False,
626
+ scale: float = 1.0,
627
+ pc: bool = False,
628
+ fs: bool = False,
629
+ split: bool = False,
630
+ strand: Optional[str] = None,
631
+ max: int = 0,
632
+ trackline: bool = False,
633
+ trackopts: Optional[str] = None,
634
+ ):
635
+ """
636
+ Compute genome-wide coverage of a feature file.
637
+ """
638
+ # Input validation
639
+ if not i.exists():
640
+ raise FileNotFoundError(f"Input file -i does not exist: {i}")
641
+ if not g.exists():
642
+ raise FileNotFoundError(f"Genome file -g does not exist: {g}")
643
+ if strand and strand not in ["+", "-"]:
644
+ raise ValueError("Option -strand must be either '+' or '-'.")
645
+ if max < 0:
646
+ raise ValueError("Option -max must be a non-negative integer.")
647
+ output_modes = [d, dz, bga, bg]
648
+ if sum(output_modes) > 1:
649
+ raise ValueError("Output format flags (-d, -dz, -bga, -bg) are mutually exclusive.")
650
+
651
+ # Command construction
652
+ cmd = ["bedtools", "genomecov", "-i", str(i), "-g", str(g)]
653
+
654
+ if d: cmd.append("-d")
655
+ if dz: cmd.append("-dz")
656
+ if bga: cmd.append("-bga")
657
+ if bg: cmd.append("-bg")
658
+ if scale != 1.0: cmd.extend(["-scale", str(scale)])
659
+ if pc: cmd.append("-pc")
660
+ if fs: cmd.append("-fs")
661
+ if split: cmd.append("-split")
662
+ if strand: cmd.extend(["-strand", strand])
663
+ if max > 0: cmd.extend(["-max", str(max)])
664
+ if trackline: cmd.append("-trackline")
665
+ if trackopts: cmd.extend(["-trackopts", trackopts])
666
+
667
+ # Subprocess execution
668
+ command_executed = " ".join(cmd)
669
+ output_files = []
670
+ stdout_capture, stderr_capture = "", ""
671
+
672
+ try:
673
+ if output:
674
+ output_files.append(str(output))
675
+ with open(output, "w") as f_out:
676
+ result = subprocess.run(
677
+ cmd, check=True, text=True, stdout=f_out, stderr=subprocess.PIPE
678
+ )
679
+ stderr_capture = result.stderr
680
+ else:
681
+ result = subprocess.run(
682
+ cmd, check=True, text=True, capture_output=True
683
+ )
684
+ stdout_capture = result.stdout
685
+ stderr_capture = result.stderr
686
+ except subprocess.CalledProcessError as e:
687
+ return {
688
+ "command_executed": command_executed,
689
+ "stdout": e.stdout or "",
690
+ "stderr": e.stderr or "CalledProcessError with no stderr.",
691
+ "output_files": [],
692
+ "return_code": e.returncode,
693
+ }
694
+
695
+ return {
696
+ "command_executed": command_executed,
697
+ "stdout": stdout_capture,
698
+ "stderr": stderr_capture,
699
+ "output_files": output_files,
700
+ }
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedtools/app/bedtools_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_bedtools/app/bedtools_server.py')
11
+ SERVER_NAME = 'biosci_bedtools'
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_bedtools/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-bedtools:
5
+ build: .
6
+ image: mcp-bedtools:latest
7
+ container_name: mcp-bedtools
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=bedtools
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_bedtools/environment.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ name: mcp-tool
3
+ channels:
4
+ - bioconda
5
+ - conda-forge
6
+ - defaults
7
+ dependencies:
8
+ - bedtools
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bedtools/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/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 bioawk via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bioawk -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/bioawk_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/bioawk_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/bioawk_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/app/bioawk_server.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ from pathlib import Path
3
+ from typing import List, Optional, Dict, Any
4
+
5
+ # Assume 'mcp' is a globally available module in the execution environment.
6
+ # from some_mcp_library import mcp
7
+
8
+ @mcp.tool
9
+ def bioawk(
10
+ program: Optional[str] = None,
11
+ program_file: Optional[Path] = None,
12
+ input_files: Optional[List[Path]] = None,
13
+ output_file: Optional[Path] = None,
14
+ format: Optional[str] = None,
15
+ tab_separator: bool = False,
16
+ include_header: bool = False,
17
+ variables: Optional[List[str]] = None,
18
+ field_separator: Optional[str] = None,
19
+ ) -> Dict[str, Any]:
20
+ """
21
+ Executes the bioawk command, a powerful stream editor for biological data formats.
22
+
23
+ bioawk is an extension of awk that understands common biological data formats
24
+ like FASTA, FASTQ, SAM, VCF, BED, and GFF. At least one of 'program' or
25
+ 'program_file' must be provided.
26
+
27
+ Args:
28
+ program: The AWK program string to execute. Mutually exclusive with 'program_file'.
29
+ program_file: Path to a file containing the AWK program. Mutually exclusive with 'program'.
30
+ input_files: A list of input files to process. If not provided, bioawk reads from standard input.
31
+ output_file: Path to a file where the output (stdout) will be saved. If not provided, stdout is captured and returned.
32
+ format: Input format (-c). Supported formats include 'fasta', 'fastq', 'sam', 'vcf', 'bed', 'gff'.
33
+ tab_separator: Use tab as the input and output field separator (-t flag).
34
+ include_header: Include header in the output for formats like VCF/SAM (-H flag).
35
+ variables: A list of 'var=value' strings to define AWK variables (-v flag).
36
+ field_separator: The input field separator string (-F flag).
37
+
38
+ Returns:
39
+ A dictionary containing the executed command, stdout, stderr, and a list of output files.
40
+ """
41
+ # --- Input Validation ---
42
+ if not program and not program_file:
43
+ raise ValueError("Either 'program' or 'program_file' must be provided.")
44
+ if program and program_file:
45
+ raise ValueError("'program' and 'program_file' are mutually exclusive and cannot be used together.")
46
+
47
+ if program_file:
48
+ if not program_file.is_file():
49
+ raise FileNotFoundError(f"Program file not found: {program_file}")
50
+
51
+ if input_files:
52
+ for file_path in input_files:
53
+ if not file_path.is_file():
54
+ raise FileNotFoundError(f"Input file not found: {file_path}")
55
+
56
+ VALID_FORMATS = {"fasta", "fastq", "sam", "vcf", "bed", "gff"}
57
+ if format and format.lower() not in VALID_FORMATS:
58
+ raise ValueError(f"Invalid format '{format}'. Must be one of {VALID_FORMATS}.")
59
+
60
+ if variables:
61
+ for var in variables:
62
+ if "=" not in var:
63
+ raise ValueError(f"Invalid variable assignment '{var}'. Must be in 'var=value' format.")
64
+
65
+ # --- Command Construction ---
66
+ cmd = ["bioawk"]
67
+
68
+ if format:
69
+ cmd.extend(["-c", format.lower()])
70
+ if tab_separator:
71
+ cmd.append("-t")
72
+ if include_header:
73
+ cmd.append("-H")
74
+ if field_separator:
75
+ cmd.extend(["-F", field_separator])
76
+ if variables:
77
+ for var in variables:
78
+ cmd.extend(["-v", var])
79
+
80
+ # The program or program_file argument must come after options but before input files.
81
+ if program_file:
82
+ cmd.extend(["-f", str(program_file)])
83
+ elif program:
84
+ cmd.append(program)
85
+
86
+ if input_files:
87
+ cmd.extend([str(p) for p in input_files])
88
+
89
+ command_executed = " ".join(cmd)
90
+
91
+ # --- Subprocess Execution ---
92
+ try:
93
+ if output_file:
94
+ # Create parent directories if they don't exist
95
+ output_file.parent.mkdir(parents=True, exist_ok=True)
96
+ with open(output_file, "w") as f_out:
97
+ result = subprocess.run(
98
+ cmd,
99
+ check=True,
100
+ stdout=f_out,
101
+ stderr=subprocess.PIPE,
102
+ text=True,
103
+ )
104
+ stdout_content = f"Output successfully written to {output_file}"
105
+ output_files_list = [str(output_file)]
106
+ else:
107
+ result = subprocess.run(
108
+ cmd,
109
+ check=True,
110
+ capture_output=True,
111
+ text=True,
112
+ )
113
+ stdout_content = result.stdout
114
+ output_files_list = []
115
+
116
+ return {
117
+ "command_executed": command_executed,
118
+ "stdout": stdout_content,
119
+ "stderr": result.stderr,
120
+ "output_files": output_files_list,
121
+ }
122
+ except FileNotFoundError:
123
+ raise RuntimeError("bioawk command not found. Please ensure it is installed and in your system's PATH.")
124
+ except subprocess.CalledProcessError as e:
125
+ # Return a structured error response if the command fails
126
+ return {
127
+ "command_executed": command_executed,
128
+ "stdout": e.stdout or "",
129
+ "stderr": e.stderr or f"bioawk exited with error code {e.returncode}",
130
+ "output_files": [],
131
+ "error": f"Command failed with exit code {e.returncode}"
132
+ }
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/app/bioawk_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_bioawk/app/bioawk_server.py')
11
+ SERVER_NAME = 'biosci_bioawk'
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_bioawk/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-bioawk:
5
+ build: .
6
+ image: mcp-bioawk:latest
7
+ container_name: mcp-bioawk
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=bioawk
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_bioawk/environment.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ name: mcp-tool
3
+ channels:
4
+ - bioconda
5
+ - conda-forge
6
+ - defaults
7
+ dependencies:
8
+ - bioawk
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioawk/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/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 bioconductor-affyio via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bioconductor-affyio -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/bioconductor-affyio_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/bioconductor-affyio_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/bioconductor-affyio_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/app/bioconductor-affyio_server.py ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import json
3
+ import os
4
+ from pathlib import Path
5
+ from typing import Optional, List, Dict, Any
6
+
7
+ @mcp.tool()
8
+ def affyio_read_celfile_header(
9
+ filename: str,
10
+ info: str = "full"
11
+ ) -> Dict[str, Any]:
12
+ """
13
+ Read the header information from an Affymetrix CEL file.
14
+
15
+ Args:
16
+ filename: Path to the CEL file.
17
+ info: Level of information to extract ('full' or 'minimal').
18
+ """
19
+ file_path = Path(filename)
20
+ if not file_path.exists():
21
+ return {"error": f"File not found: {filename}"}
22
+
23
+ if info not in ["full", "minimal"]:
24
+ info = "full"
25
+
26
+ # R script to extract header and convert to JSON
27
+ r_command = f"""
28
+ library(affyio)
29
+ library(jsonlite)
30
+ header <- read.celfile.header("{str(file_path)}", info="{info}")
31
+ cat(toJSON(header, auto_unbox = TRUE))
32
+ """
33
+
34
+ try:
35
+ result = subprocess.run(
36
+ ["Rscript", "-e", r_command],
37
+ capture_output=True,
38
+ text=True,
39
+ check=True
40
+ )
41
+ return {
42
+ "command_executed": f"read.celfile.header('{filename}')",
43
+ "header_data": json.loads(result.stdout),
44
+ "stderr": result.stderr
45
+ }
46
+ except subprocess.CalledProcessError as e:
47
+ return {
48
+ "error": "R execution failed",
49
+ "stdout": e.stdout,
50
+ "stderr": e.stderr,
51
+ "command_executed": e.cmd
52
+ }
53
+ except json.JSONDecodeError:
54
+ return {"error": "Failed to parse R output", "raw_stdout": result.stdout}
55
+
56
+ @mcp.tool()
57
+ def affyio_read_celfile(
58
+ filename: str,
59
+ output_csv: str,
60
+ intensity_only: bool = True
61
+ ) -> Dict[str, Any]:
62
+ """
63
+ Read an Affymetrix CEL file and export the intensity data to a CSV file.
64
+
65
+ Args:
66
+ filename: Path to the CEL file.
67
+ output_csv: Path where the intensity data should be saved.
68
+ intensity_only: If True, only the intensity values are extracted.
69
+ """
70
+ input_path = Path(filename)
71
+ output_path = Path(output_csv)
72
+
73
+ if not input_path.exists():
74
+ return {"error": f"Input file not found: {filename}"}
75
+
76
+ intensity_val = "TRUE" if intensity_only else "FALSE"
77
+
78
+ r_command = f"""
79
+ library(affyio)
80
+ data <- read.celfile("{str(input_path)}", intensity.only={intensity_val})
81
+ # If intensity.only is TRUE, it returns a list with INTENSITY
82
+ # If FALSE, it returns a list with INTENSITY, MASKS, OUTLIERS
83
+ write.csv(data$INTENSITY, "{str(output_path)}")
84
+ """
85
+
86
+ try:
87
+ subprocess.run(
88
+ ["Rscript", "-e", r_command],
89
+ capture_output=True,
90
+ text=True,
91
+ check=True
92
+ )
93
+ return {
94
+ "command_executed": f"read.celfile('{filename}')",
95
+ "status": "Success",
96
+ "output_file": str(output_path)
97
+ }
98
+ except subprocess.CalledProcessError as e:
99
+ return {
100
+ "error": "R execution failed",
101
+ "stderr": e.stderr,
102
+ "stdout": e.stdout
103
+ }
104
+
105
+ @mcp.tool()
106
+ def affyio_check_cdf_type(
107
+ filename: str
108
+ ) -> Dict[str, Any]:
109
+ """
110
+ Identify the type of an Affymetrix CDF file (e.g., text, binary, gzipped).
111
+
112
+ Args:
113
+ filename: Path to the CDF file.
114
+ """
115
+ file_path = Path(filename)
116
+ if not file_path.exists():
117
+ return {"error": f"File not found: {filename}"}
118
+
119
+ r_command = f"""
120
+ library(affyio)
121
+ type <- check.cdf.type("{str(file_path)}")
122
+ cat(type)
123
+ """
124
+
125
+ try:
126
+ result = subprocess.run(
127
+ ["Rscript", "-e", r_command],
128
+ capture_output=True,
129
+ text=True,
130
+ check=True
131
+ )
132
+ return {
133
+ "command_executed": f"check.cdf.type('{filename}')",
134
+ "cdf_type": result.stdout.strip(),
135
+ "stderr": result.stderr
136
+ }
137
+ except subprocess.CalledProcessError as e:
138
+ return {"error": "R execution failed", "stderr": e.stderr}
139
+
140
+ @mcp.tool()
141
+ def affyio_read_cdffile_summary(
142
+ filename: str
143
+ ) -> Dict[str, Any]:
144
+ """
145
+ Read an Affymetrix CDF file and return a summary of its contents.
146
+ Note: Full CDF lists are extremely large; this tool returns structural metadata.
147
+
148
+ Args:
149
+ filename: Path to the CDF file.
150
+ """
151
+ file_path = Path(filename)
152
+ if not file_path.exists():
153
+ return {"error": f"File not found: {filename}"}
154
+
155
+ r_command = f"""
156
+ library(affyio)
157
+ library(jsonlite)
158
+ cdf_data <- read.cdffile.list("{str(file_path)}")
159
+ summary_info <- list(
160
+ filename = "{filename}",
161
+ num_probesets = length(cdf_data),
162
+ probeset_names = head(names(cdf_data), 10)
163
+ )
164
+ cat(toJSON(summary_info, auto_unbox = TRUE))
165
+ """
166
+
167
+ try:
168
+ result = subprocess.run(
169
+ ["Rscript", "-e", r_command],
170
+ capture_output=True,
171
+ text=True,
172
+ check=True
173
+ )
174
+ return {
175
+ "command_executed": f"read.cdffile.list('{filename}')",
176
+ "summary": json.loads(result.stdout),
177
+ "stderr": result.stderr
178
+ }
179
+ except subprocess.CalledProcessError as e:
180
+ return {"error": "R execution failed", "stderr": e.stderr}
181
+
182
+ @mcp.tool()
183
+ def affyio_get_package_version() -> Dict[str, Any]:
184
+ """
185
+ Check the installed version of the affyio package and its dependencies.
186
+ """
187
+ r_command = """
188
+ library(affyio)
189
+ v <- as.character(packageVersion("affyio"))
190
+ cat(v)
191
+ """
192
+ try:
193
+ result = subprocess.run(
194
+ ["Rscript", "-e", r_command],
195
+ capture_output=True,
196
+ text=True,
197
+ check=True
198
+ )
199
+ return {
200
+ "package": "affyio",
201
+ "version": result.stdout.strip(),
202
+ "r_version": subprocess.run(["Rscript", "--version"], capture_output=True, text=True).stderr.strip()
203
+ }
204
+ except subprocess.CalledProcessError as e:
205
+ return {
206
+ "error": "Could not determine package version. Ensure bioconductor-affyio is installed.",
207
+ "stderr": e.stderr
208
+ }
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/app/bioconductor-affyio_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_bioconductor-affyio/app/bioconductor-affyio_server.py')
11
+ SERVER_NAME = 'biosci_bioconductor_affyio'
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_bioconductor-affyio/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-bioconductor-affyio:
5
+ build: .
6
+ image: mcp-bioconductor-affyio:latest
7
+ container_name: mcp-bioconductor-affyio
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=bioconductor-affyio
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_bioconductor-affyio/environment.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ name: mcp-tool
3
+ channels:
4
+ - bioconda
5
+ - conda-forge
6
+ - defaults
7
+ dependencies:
8
+ - bioconductor-affyio
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-affyio/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotate/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 bioconductor-annotate via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bioconductor-annotate -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 bioconductor-annotate_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/bioconductor-annotate_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/bioconductor-annotate_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotate/app/bioconductor-annotate_server.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import logging
3
+ from pathlib import Path
4
+ from typing import Optional, List, Dict, Any
5
+
6
+ # The mcp.tool decorator is supplied by the MCP framework.
7
+ # It is aliased here for clarity and to allow for standalone code analysis.
8
+ class mcp:
9
+ """A dummy class to represent the MCP decorator for static analysis."""
10
+ @staticmethod
11
+ def tool(func):
12
+ """A dummy decorator that returns the function unchanged."""
13
+ return func
14
+
15
+ @mcp.tool
16
+ def rscript(
17
+ script_file: Optional[Path] = None,
18
+ expressions: Optional[List[str]] = None,
19
+ script_args: Optional[List[str]] = None,
20
+ verbose: bool = False,
21
+ default_packages: Optional[str] = None,
22
+ vanilla: bool = False,
23
+ save: bool = False,
24
+ no_environ: bool = False,
25
+ no_site_file: bool = False,
26
+ no_init_file: bool = False,
27
+ restore: bool = False,
28
+ ) -> Dict[str, Any]:
29
+ """
30
+ Executes an R script or R expressions using the Rscript command-line tool.
31
+
32
+ This tool serves as a wrapper for the Rscript interpreter, which is commonly
33
+ used to run bioinformatics scripts that rely on R packages from repositories
34
+ like CRAN or Bioconductor (e.g., for using bioconductor-annotate).
35
+ You must provide either a path to an R script file or a list of R expressions
36
+ to execute.
37
+
38
+ Args:
39
+ script_file: Path to the R script file to be executed.
40
+ expressions: A list of R expressions to execute directly. Use this instead of script_file.
41
+ script_args: A list of arguments to be passed to the R script itself.
42
+ verbose: If True, enables verbose output, printing information on progress.
43
+ default_packages: A comma-separated string of package names to be loaded by default.
44
+ vanilla: If True, combines --no-save, --no-restore, --no-site-file,
45
+ --no-init-file, and --no-environ. This provides a clean session.
46
+ If True, the individual flags (save, restore, etc.) are ignored.
47
+ save: If True, the workspace will be saved at the end of the session. Ignored if vanilla is True.
48
+ no_environ: If True, site and user environment files will not be read. Ignored if vanilla is True.
49
+ no_site_file: If True, the site-wide Rprofile will not be read. Ignored if vanilla is True.
50
+ no_init_file: If True, the user's R profile will not be read. Ignored if vanilla is True.
51
+ restore: If True, previously saved objects will be restored at startup. Ignored if vanilla is True.
52
+
53
+ Returns:
54
+ A dictionary containing the executed command, stdout, stderr, and a list of output files.
55
+ """
56
+ # 1. Input Validation
57
+ if not script_file and not expressions:
58
+ raise ValueError("Either 'script_file' or 'expressions' must be provided.")
59
+ if script_file and expressions:
60
+ raise ValueError("Cannot provide both 'script_file' and 'expressions' simultaneously.")
61
+
62
+ if script_file:
63
+ if not script_file.is_file():
64
+ raise FileNotFoundError(f"The specified script file does not exist: {script_file}")
65
+
66
+ # 2. Command Construction
67
+ cmd = ["Rscript"]
68
+
69
+ if verbose:
70
+ cmd.append("--verbose")
71
+
72
+ if default_packages:
73
+ cmd.append(f"--default-packages={default_packages}")
74
+
75
+ if vanilla:
76
+ cmd.append("--vanilla")
77
+ else:
78
+ # These options are processed only if --vanilla is not used
79
+ if save:
80
+ cmd.append("--save")
81
+ if no_environ:
82
+ cmd.append("--no-environ")
83
+ if no_site_file:
84
+ cmd.append("--no-site-file")
85
+ if no_init_file:
86
+ cmd.append("--no-init-file")
87
+ if restore:
88
+ cmd.append("--restore")
89
+
90
+ # Add script file or expressions to execute
91
+ if script_file:
92
+ cmd.append(str(script_file))
93
+ elif expressions:
94
+ for expr in expressions:
95
+ cmd.extend(["-e", expr])
96
+
97
+ # Add trailing arguments for the R script
98
+ if script_args:
99
+ cmd.extend(script_args)
100
+
101
+ command_executed = " ".join(cmd)
102
+ logging.info(f"Executing command: {command_executed}")
103
+
104
+ # 3. Subprocess Execution and Error Handling
105
+ try:
106
+ result = subprocess.run(
107
+ cmd,
108
+ capture_output=True,
109
+ text=True,
110
+ check=True,
111
+ )
112
+ except FileNotFoundError:
113
+ # This error occurs if 'Rscript' is not in the system's PATH
114
+ logging.error("Rscript executable not found.")
115
+ return {
116
+ "error": "Rscript not found. Please ensure R is installed and in your PATH.",
117
+ "command_executed": command_executed,
118
+ "stdout": "",
119
+ "stderr": "Rscript executable not found.",
120
+ "output_files": []
121
+ }
122
+ except subprocess.CalledProcessError as e:
123
+ # This error occurs if the R script exits with a non-zero status code
124
+ logging.error(f"Rscript execution failed with exit code {e.returncode}")
125
+ return {
126
+ "error": f"Rscript execution failed with exit code {e.returncode}.",
127
+ "command_executed": command_executed,
128
+ "stdout": e.stdout,
129
+ "stderr": e.stderr,
130
+ "output_files": []
131
+ }
132
+
133
+ # 4. Structured Result Return
134
+ # This wrapper cannot reliably determine output files generated by the user's script.
135
+ # The user is responsible for knowing and handling the script's output.
136
+ return {
137
+ "command_executed": command_executed,
138
+ "stdout": result.stdout,
139
+ "stderr": result.stderr,
140
+ "output_files": []
141
+ }
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotate/app/bioconductor-annotate_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_bioconductor-annotate/app/bioconductor-annotate_server.py')
11
+ SERVER_NAME = 'biosci_bioconductor_annotate'
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_bioconductor-annotate/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-bioconductor-annotate:
5
+ build: .
6
+ image: mcp-bioconductor-annotate:latest
7
+ container_name: mcp-bioconductor-annotate
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=bioconductor-annotate
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_bioconductor-annotate/environment.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ name: mcp-tool
3
+ channels:
4
+ - bioconda
5
+ - conda-forge
6
+ - defaults
7
+ dependencies:
8
+ - bioconductor-annotate
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotate/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotationdbi/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 bioconductor-annotationdbi via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bioconductor-annotationdbi -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 bioconductor-annotationdbi_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/bioconductor-annotationdbi_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/bioconductor-annotationdbi_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotationdbi/app/bioconductor-annotationdbi_server.py ADDED
@@ -0,0 +1,456 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import tempfile
3
+ from pathlib import Path
4
+ from typing import Optional, List
5
+
6
+ # MCP decorator is assumed to be defined in the execution environment.
7
+ # No import is needed as per the instructions.
8
+
9
+ @mcp.tool()
10
+ def annotationdbi_columns(db_package: str) -> dict:
11
+ """
12
+ Lists all available columns for a given Bioconductor annotation package.
13
+
14
+ This tool requires R, Rscript, and the Bioconductor packages 'AnnotationDbi'
15
+ and the specified 'db_package' to be installed in the R environment.
16
+
17
+ Args:
18
+ db_package: The name of the Bioconductor annotation package (e.g., "org.Hs.eg.db").
19
+
20
+ Returns:
21
+ A dictionary containing the command executed and the standard output with the column names.
22
+ """
23
+ if not db_package:
24
+ raise ValueError("db_package must be a non-empty string.")
25
+
26
+ r_script_content = f"""
27
+ suppressPackageStartupMessages(library(AnnotationDbi))
28
+
29
+ db_package_name <- "{db_package}"
30
+
31
+ if (!requireNamespace(db_package_name, quietly = TRUE)) {{
32
+ stop(paste("Annotation package '", db_package_name, "' is not installed. Please install it from Bioconductor."), call. = FALSE)
33
+ }}
34
+ db <- get(db_package_name)
35
+
36
+ tryCatch({{
37
+ result_data <- AnnotationDbi::columns(db)
38
+ cat(result_data, sep = "\\n")
39
+ }}, error = function(e) {{
40
+ stop(paste("AnnotationDbi::columns failed:", e$message), call. = FALSE)
41
+ }})
42
+ """
43
+
44
+ with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, encoding='utf-8') as tmp_script:
45
+ tmp_script.write(r_script_content)
46
+ script_path = tmp_script.name
47
+
48
+ cmd = ["Rscript", script_path]
49
+ command_executed = f"Rscript {script_path}"
50
+
51
+ try:
52
+ result = subprocess.run(
53
+ cmd,
54
+ capture_output=True,
55
+ text=True,
56
+ check=True,
57
+ encoding='utf-8'
58
+ )
59
+ return {
60
+ "command_executed": command_executed,
61
+ "stdout": result.stdout,
62
+ "stderr": result.stderr,
63
+ }
64
+ except subprocess.CalledProcessError as e:
65
+ return {
66
+ "command_executed": command_executed,
67
+ "stdout": e.stdout,
68
+ "stderr": e.stderr,
69
+ "error": f"R script execution failed with exit code {e.returncode}"
70
+ }
71
+ except FileNotFoundError:
72
+ return {
73
+ "command_executed": command_executed,
74
+ "stdout": "",
75
+ "stderr": "Error: 'Rscript' command not found. Please ensure R is installed and 'Rscript' is in your system's PATH.",
76
+ "error": "Dependency not found"
77
+ }
78
+ finally:
79
+ Path(script_path).unlink()
80
+
81
+ @mcp.tool()
82
+ def annotationdbi_keytypes(db_package: str) -> dict:
83
+ """
84
+ Lists all available keytypes for a given Bioconductor annotation package.
85
+
86
+ This tool requires R, Rscript, and the Bioconductor packages 'AnnotationDbi'
87
+ and the specified 'db_package' to be installed in the R environment.
88
+
89
+ Args:
90
+ db_package: The name of the Bioconductor annotation package (e.g., "org.Hs.eg.db").
91
+
92
+ Returns:
93
+ A dictionary containing the command executed and the standard output with the keytype names.
94
+ """
95
+ if not db_package:
96
+ raise ValueError("db_package must be a non-empty string.")
97
+
98
+ r_script_content = f"""
99
+ suppressPackageStartupMessages(library(AnnotationDbi))
100
+
101
+ db_package_name <- "{db_package}"
102
+
103
+ if (!requireNamespace(db_package_name, quietly = TRUE)) {{
104
+ stop(paste("Annotation package '", db_package_name, "' is not installed. Please install it from Bioconductor."), call. = FALSE)
105
+ }}
106
+ db <- get(db_package_name)
107
+
108
+ tryCatch({{
109
+ result_data <- AnnotationDbi::keytypes(db)
110
+ cat(result_data, sep = "\\n")
111
+ }}, error = function(e) {{
112
+ stop(paste("AnnotationDbi::keytypes failed:", e$message), call. = FALSE)
113
+ }})
114
+ """
115
+
116
+ with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, encoding='utf-8') as tmp_script:
117
+ tmp_script.write(r_script_content)
118
+ script_path = tmp_script.name
119
+
120
+ cmd = ["Rscript", script_path]
121
+ command_executed = f"Rscript {script_path}"
122
+
123
+ try:
124
+ result = subprocess.run(
125
+ cmd,
126
+ capture_output=True,
127
+ text=True,
128
+ check=True,
129
+ encoding='utf-8'
130
+ )
131
+ return {
132
+ "command_executed": command_executed,
133
+ "stdout": result.stdout,
134
+ "stderr": result.stderr,
135
+ }
136
+ except subprocess.CalledProcessError as e:
137
+ return {
138
+ "command_executed": command_executed,
139
+ "stdout": e.stdout,
140
+ "stderr": e.stderr,
141
+ "error": f"R script execution failed with exit code {e.returncode}"
142
+ }
143
+ except FileNotFoundError:
144
+ return {
145
+ "command_executed": command_executed,
146
+ "stdout": "",
147
+ "stderr": "Error: 'Rscript' command not found. Please ensure R is installed and 'Rscript' is in your system's PATH.",
148
+ "error": "Dependency not found"
149
+ }
150
+ finally:
151
+ Path(script_path).unlink()
152
+
153
+ @mcp.tool()
154
+ def annotationdbi_keys(db_package: str, keytype: str) -> dict:
155
+ """
156
+ Lists all available keys for a given keytype in a Bioconductor annotation package.
157
+
158
+ This tool requires R, Rscript, and the Bioconductor packages 'AnnotationDbi'
159
+ and the specified 'db_package' to be installed in the R environment.
160
+
161
+ Args:
162
+ db_package: The name of the Bioconductor annotation package (e.g., "org.Hs.eg.db").
163
+ keytype: The keytype for which to retrieve all available keys (e.g., "ENTREZID").
164
+
165
+ Returns:
166
+ A dictionary containing the command executed and the standard output with the keys.
167
+ """
168
+ if not db_package:
169
+ raise ValueError("db_package must be a non-empty string.")
170
+ if not keytype:
171
+ raise ValueError("keytype must be a non-empty string.")
172
+
173
+ r_script_content = f"""
174
+ suppressPackageStartupMessages(library(AnnotationDbi))
175
+
176
+ db_package_name <- "{db_package}"
177
+ keytype_str <- "{keytype}"
178
+
179
+ if (!requireNamespace(db_package_name, quietly = TRUE)) {{
180
+ stop(paste("Annotation package '", db_package_name, "' is not installed. Please install it from Bioconductor."), call. = FALSE)
181
+ }}
182
+ db <- get(db_package_name)
183
+
184
+ tryCatch({{
185
+ result_data <- AnnotationDbi::keys(db, keytype = keytype_str)
186
+ cat(result_data, sep = "\\n")
187
+ }}, error = function(e) {{
188
+ stop(paste("AnnotationDbi::keys failed:", e$message), call. = FALSE)
189
+ }})
190
+ """
191
+
192
+ with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, encoding='utf-8') as tmp_script:
193
+ tmp_script.write(r_script_content)
194
+ script_path = tmp_script.name
195
+
196
+ cmd = ["Rscript", script_path]
197
+ command_executed = f"Rscript {script_path}"
198
+
199
+ try:
200
+ result = subprocess.run(
201
+ cmd,
202
+ capture_output=True,
203
+ text=True,
204
+ check=True,
205
+ encoding='utf-8'
206
+ )
207
+ return {
208
+ "command_executed": command_executed,
209
+ "stdout": result.stdout,
210
+ "stderr": result.stderr,
211
+ }
212
+ except subprocess.CalledProcessError as e:
213
+ return {
214
+ "command_executed": command_executed,
215
+ "stdout": e.stdout,
216
+ "stderr": e.stderr,
217
+ "error": f"R script execution failed with exit code {e.returncode}"
218
+ }
219
+ except FileNotFoundError:
220
+ return {
221
+ "command_executed": command_executed,
222
+ "stdout": "",
223
+ "stderr": "Error: 'Rscript' command not found. Please ensure R is installed and 'Rscript' is in your system's PATH.",
224
+ "error": "Dependency not found"
225
+ }
226
+ finally:
227
+ Path(script_path).unlink()
228
+
229
+ @mcp.tool()
230
+ def annotationdbi_select(
231
+ db_package: str,
232
+ keys: str,
233
+ columns: str,
234
+ keytype: str,
235
+ output_file: Path,
236
+ ) -> dict:
237
+ """
238
+ Retrieves data from a Bioconductor annotation package using AnnotationDbi::select.
239
+
240
+ This tool requires R, Rscript, and the Bioconductor packages 'AnnotationDbi'
241
+ and the specified 'db_package' to be installed in the R environment.
242
+
243
+ Args:
244
+ db_package: The name of the Bioconductor annotation package (e.g., "org.Hs.eg.db").
245
+ keys: A comma-separated string of keys to query (e.g., "BRCA1,TP53").
246
+ columns: A comma-separated string of columns to retrieve (e.g., "SYMBOL,GENENAME,ENTREZID").
247
+ keytype: The type of the provided keys (e.g., "SYMBOL").
248
+ output_file: The path to save the results as a TSV file.
249
+
250
+ Returns:
251
+ A dictionary containing the command executed, logs, and the path to the output file.
252
+ """
253
+ if not db_package:
254
+ raise ValueError("db_package must be a non-empty string.")
255
+ if not keys:
256
+ raise ValueError("keys must be a non-empty, comma-separated string.")
257
+ if not columns:
258
+ raise ValueError("columns must be a non-empty, comma-separated string.")
259
+ if not keytype:
260
+ raise ValueError("keytype must be a non-empty string.")
261
+
262
+ output_file.parent.mkdir(parents=True, exist_ok=True)
263
+
264
+ r_script_content = f"""
265
+ suppressPackageStartupMessages(library(AnnotationDbi))
266
+
267
+ db_package_name <- "{db_package}"
268
+ keys_vec <- unlist(strsplit("{keys}", ","))
269
+ columns_vec <- unlist(strsplit("{columns}", ","))
270
+ keytype_str <- "{keytype}"
271
+ output_file_path <- "{output_file.resolve()}"
272
+
273
+ if (!requireNamespace(db_package_name, quietly = TRUE)) {{
274
+ stop(paste("Annotation package '", db_package_name, "' is not installed. Please install it from Bioconductor."), call. = FALSE)
275
+ }}
276
+ db <- get(db_package_name)
277
+
278
+ tryCatch({{
279
+ results <- AnnotationDbi::select(db,
280
+ keys = keys_vec,
281
+ columns = columns_vec,
282
+ keytype = keytype_str)
283
+
284
+ write.table(results,
285
+ file = output_file_path,
286
+ sep = "\\t",
287
+ row.names = FALSE,
288
+ col.names = TRUE,
289
+ quote = FALSE)
290
+
291
+ cat(paste("Successfully wrote", nrow(results), "rows to", basename(output_file_path), "\\n"))
292
+
293
+ }}, error = function(e) {{
294
+ stop(paste("AnnotationDbi::select failed:", e$message), call. = FALSE)
295
+ }})
296
+ """
297
+
298
+ with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, encoding='utf-8') as tmp_script:
299
+ tmp_script.write(r_script_content)
300
+ script_path = tmp_script.name
301
+
302
+ cmd = ["Rscript", script_path]
303
+ command_executed = f"Rscript {script_path}"
304
+
305
+ try:
306
+ result = subprocess.run(
307
+ cmd,
308
+ capture_output=True,
309
+ text=True,
310
+ check=True,
311
+ encoding='utf-8'
312
+ )
313
+ return {
314
+ "command_executed": command_executed,
315
+ "stdout": result.stdout,
316
+ "stderr": result.stderr,
317
+ "output_files": [str(output_file.resolve())]
318
+ }
319
+ except subprocess.CalledProcessError as e:
320
+ return {
321
+ "command_executed": command_executed,
322
+ "stdout": e.stdout,
323
+ "stderr": e.stderr,
324
+ "error": f"R script execution failed with exit code {e.returncode}",
325
+ "output_files": []
326
+ }
327
+ except FileNotFoundError:
328
+ return {
329
+ "command_executed": command_executed,
330
+ "stdout": "",
331
+ "stderr": "Error: 'Rscript' command not found. Please ensure R is installed and 'Rscript' is in your system's PATH.",
332
+ "error": "Dependency not found",
333
+ "output_files": []
334
+ }
335
+ finally:
336
+ Path(script_path).unlink()
337
+
338
+ @mcp.tool()
339
+ def annotationdbi_mapids(
340
+ db_package: str,
341
+ keys: str,
342
+ column: str,
343
+ keytype: str,
344
+ output_file: Path,
345
+ multi_vals: str = "first",
346
+ ) -> dict:
347
+ """
348
+ Maps identifiers from one type to another using AnnotationDbi::mapIds.
349
+
350
+ This tool requires R, Rscript, and the Bioconductor packages 'AnnotationDbi'
351
+ and the specified 'db_package' to be installed in the R environment.
352
+
353
+ Args:
354
+ db_package: The name of the Bioconductor annotation package (e.g., "org.Hs.eg.db").
355
+ keys: A comma-separated string of keys to query (e.g., "BRCA1,TP53").
356
+ column: The single column (identifier type) to map to (e.g., "ENTREZID").
357
+ keytype: The type of the provided keys (e.g., "SYMBOL").
358
+ output_file: The path to save the mapping results as a TSV file.
359
+ multi_vals: How to handle multiple matches. One of "first", "list", "filter", "asNA".
360
+
361
+ Returns:
362
+ A dictionary containing the command executed, logs, and the path to the output file.
363
+ """
364
+ if not db_package:
365
+ raise ValueError("db_package must be a non-empty string.")
366
+ if not keys:
367
+ raise ValueError("keys must be a non-empty, comma-separated string.")
368
+ if not column:
369
+ raise ValueError("column must be a non-empty string.")
370
+ if not keytype:
371
+ raise ValueError("keytype must be a non-empty string.")
372
+
373
+ valid_multi_vals = ["first", "list", "filter", "asNA", "character"]
374
+ if multi_vals not in valid_multi_vals:
375
+ raise ValueError(f"multi_vals must be one of {valid_multi_vals}")
376
+
377
+ output_file.parent.mkdir(parents=True, exist_ok=True)
378
+
379
+ r_script_content = f"""
380
+ suppressPackageStartupMessages(library(AnnotationDbi))
381
+
382
+ db_package_name <- "{db_package}"
383
+ keys_vec <- unlist(strsplit("{keys}", ","))
384
+ column_str <- "{column}"
385
+ keytype_str <- "{keytype}"
386
+ multi_vals_str <- "{multi_vals}"
387
+ output_file_path <- "{output_file.resolve()}"
388
+
389
+ if (!requireNamespace(db_package_name, quietly = TRUE)) {{
390
+ stop(paste("Annotation package '", db_package_name, "' is not installed. Please install it from Bioconductor."), call. = FALSE)
391
+ }}
392
+ db <- get(db_package_name)
393
+
394
+ tryCatch({{
395
+ results_vec <- AnnotationDbi::mapIds(db,
396
+ keys = keys_vec,
397
+ column = column_str,
398
+ keytype = keytype_str,
399
+ multiVals = multi_vals_str)
400
+
401
+ # Convert named vector to a data frame for saving
402
+ results_df <- data.frame(FROM = names(results_vec), TO = I(results_vec), stringsAsFactors = FALSE)
403
+
404
+ write.table(results_df,
405
+ file = output_file_path,
406
+ sep = "\\t",
407
+ row.names = FALSE,
408
+ col.names = TRUE,
409
+ quote = FALSE)
410
+
411
+ cat(paste("Successfully wrote", nrow(results_df), "rows to", basename(output_file_path), "\\n"))
412
+
413
+ }}, error = function(e) {{
414
+ stop(paste("AnnotationDbi::mapIds failed:", e$message), call. = FALSE)
415
+ }})
416
+ """
417
+
418
+ with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, encoding='utf-8') as tmp_script:
419
+ tmp_script.write(r_script_content)
420
+ script_path = tmp_script.name
421
+
422
+ cmd = ["Rscript", script_path]
423
+ command_executed = f"Rscript {script_path}"
424
+
425
+ try:
426
+ result = subprocess.run(
427
+ cmd,
428
+ capture_output=True,
429
+ text=True,
430
+ check=True,
431
+ encoding='utf-8'
432
+ )
433
+ return {
434
+ "command_executed": command_executed,
435
+ "stdout": result.stdout,
436
+ "stderr": result.stderr,
437
+ "output_files": [str(output_file.resolve())]
438
+ }
439
+ except subprocess.CalledProcessError as e:
440
+ return {
441
+ "command_executed": command_executed,
442
+ "stdout": e.stdout,
443
+ "stderr": e.stderr,
444
+ "error": f"R script execution failed with exit code {e.returncode}",
445
+ "output_files": []
446
+ }
447
+ except FileNotFoundError:
448
+ return {
449
+ "command_executed": command_executed,
450
+ "stdout": "",
451
+ "stderr": "Error: 'Rscript' command not found. Please ensure R is installed and 'Rscript' is in your system's PATH.",
452
+ "error": "Dependency not found",
453
+ "output_files": []
454
+ }
455
+ finally:
456
+ Path(script_path).unlink()
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotationdbi/app/bioconductor-annotationdbi_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_bioconductor-annotationdbi/app/bioconductor-annotationdbi_server.py')
11
+ SERVER_NAME = 'biosci_bioconductor_annotationdbi'
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_bioconductor-annotationdbi/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-bioconductor-annotationdbi:
5
+ build: .
6
+ image: mcp-bioconductor-annotationdbi:latest
7
+ container_name: mcp-bioconductor-annotationdbi
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=bioconductor-annotationdbi
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_bioconductor-annotationdbi/environment.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ name: mcp-tool
3
+ channels:
4
+ - bioconda
5
+ - conda-forge
6
+ - defaults
7
+ dependencies:
8
+ - bioconductor-annotationdbi
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-annotationdbi/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-apeglm/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 bioconductor-apeglm via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bioconductor-apeglm -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 bioconductor-apeglm_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/bioconductor-apeglm_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/bioconductor-apeglm_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-apeglm/app/bioconductor-apeglm_server.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ from pathlib import Path
3
+ from typing import List, Optional, Dict, Any
4
+
5
+ @mcp.tool()
6
+ def run_r_script(
7
+ r_script_file: Optional[Path] = None,
8
+ r_expressions: Optional[List[str]] = None,
9
+ script_args: Optional[List[str]] = None,
10
+ verbose: bool = False,
11
+ default_packages: Optional[str] = None,
12
+ save_workspace: bool = False,
13
+ no_environ: bool = False,
14
+ no_site_file: bool = False,
15
+ no_init_file: bool = False,
16
+ restore_workspace: bool = False,
17
+ vanilla: bool = False,
18
+ ) -> Dict[str, Any]:
19
+ """
20
+ Executes an R script file or R expressions using the Rscript command.
21
+
22
+ This tool provides a wrapper for the Rscript command, allowing users to run
23
+ R code with various configuration options. It supports executing a specified
24
+ R script file or a list of R expressions directly. It also allows passing
25
+ arguments to the R script itself and configuring R's startup behavior.
26
+
27
+ Args:
28
+ r_script_file: Path to an R script file to execute. Mutually exclusive with `r_expressions`.
29
+ r_expressions: A list of R expressions (strings) to execute. Mutually exclusive with `r_script_file`.
30
+ script_args: A list of arguments to be passed to the R script or expressions.
31
+ verbose: If True, print information on progress (corresponds to Rscript's --verbose).
32
+ default_packages: A comma-separated list of package names, or 'NULL',
33
+ to set the default packages loaded (corresponds to --default-packages).
34
+ save_workspace: If True, save the workspace at the end of the session (corresponds to R's --save).
35
+ Ignored if `vanilla` is True.
36
+ no_environ: If True, don't read the site and user environment files (corresponds to R's --no-environ).
37
+ Ignored if `vanilla` is True.
38
+ no_site_file: If True, don't read the site-wide Rprofile (corresponds to R's --no-site-file).
39
+ Ignored if `vanilla` is True.
40
+ no_init_file: If True, don't read the user R profile (corresponds to R's --no-init-file).
41
+ Ignored if `vanilla` is True.
42
+ restore_workspace: If True, restore previously saved objects at startup (corresponds to R's --restore).
43
+ Ignored if `vanilla` is True.
44
+ vanilla: If True, combine --no-save, --no-restore, --no-site-file, --no-init-file, and --no-environ.
45
+ This option overrides individual settings for these flags.
46
+
47
+ Returns:
48
+ A dictionary containing the command executed, stdout, stderr, and any output files.
49
+ In case of an error, it includes error details and the return code.
50
+
51
+ Raises:
52
+ ValueError: If neither `r_script_file` nor `r_expressions` is provided, or if both are provided.
53
+ FileNotFoundError: If `r_script_file` is provided but does not exist.
54
+ """
55
+ command: List[str] = ["Rscript"]
56
+ output_files: List[Path] = []
57
+
58
+ # Input validation for script source
59
+ if r_script_file is None and r_expressions is None:
60
+ raise ValueError("Either 'r_script_file' or 'r_expressions' must be provided.")
61
+ if r_script_file is not None and r_expressions is not None:
62
+ raise ValueError("Cannot provide both 'r_script_file' and 'r_expressions'. Choose one.")
63
+
64
+ if r_script_file:
65
+ if not r_script_file.is_file():
66
+ raise FileNotFoundError(f"R script file not found: {r_script_file}")
67
+
68
+ # Add Rscript specific options
69
+ if verbose:
70
+ command.append("--verbose")
71
+ if default_packages is not None:
72
+ command.append(f"--default-packages={default_packages}")
73
+
74
+ # Add R options (passed to R, in addition to --no-echo --no-restore by Rscript)
75
+ if vanilla:
76
+ command.append("--vanilla")
77
+ else:
78
+ # Only add these if --vanilla is not set, as --vanilla implies them
79
+ if save_workspace:
80
+ command.append("--save")
81
+ if no_environ:
82
+ command.append("--no-environ")
83
+ if no_site_file:
84
+ command.append("--no-site-file")
85
+ if no_init_file:
86
+ command.append("--no-init-file")
87
+ if restore_workspace:
88
+ command.append("--restore")
89
+
90
+ # Add the script source (file or expressions)
91
+ if r_script_file:
92
+ command.append(str(r_script_file))
93
+ elif r_expressions:
94
+ for expr in r_expressions:
95
+ command.extend(["-e", expr])
96
+
97
+ # Add arguments to the R script
98
+ if script_args:
99
+ command.extend(script_args)
100
+
101
+ try:
102
+ process = subprocess.run(
103
+ command,
104
+ capture_output=True,
105
+ text=True,
106
+ check=True
107
+ )
108
+ stdout = process.stdout
109
+ stderr = process.stderr
110
+ except subprocess.CalledProcessError as e:
111
+ return {
112
+ "command_executed": " ".join(command),
113
+ "stdout": e.stdout,
114
+ "stderr": e.stderr,
115
+ "error": str(e),
116
+ "returncode": e.returncode,
117
+ "output_files": output_files,
118
+ }
119
+
120
+ return {
121
+ "command_executed": " ".join(command),
122
+ "stdout": stdout,
123
+ "stderr": stderr,
124
+ "output_files": output_files,
125
+ }