czty commited on
Commit
0a9507b
·
verified ·
1 Parent(s): 6f77ded

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. Biomanus/biomni_web/backend/data/mcp_generated/mcp_adapterremoval/Dockerfile +40 -0
  2. Biomanus/biomni_web/backend/data/mcp_generated/mcp_adapterremoval/app/__pycache__/adapterremoval_shim_server.cpython-311.pyc +0 -0
  3. Biomanus/biomni_web/backend/data/mcp_generated/mcp_adapterremoval/app/adapterremoval_server.py +291 -0
  4. Biomanus/biomni_web/backend/data/mcp_generated/mcp_adapterremoval/app/adapterremoval_shim_server.py +55 -0
  5. Biomanus/biomni_web/backend/data/mcp_generated/mcp_adapterremoval/app/requirements.txt +1 -0
  6. Biomanus/biomni_web/backend/data/mcp_generated/mcp_adapterremoval/docker-compose.yml +22 -0
  7. Biomanus/biomni_web/backend/data/mcp_generated/mcp_adapterremoval/environment.yaml +10 -0
  8. Biomanus/biomni_web/backend/data/mcp_generated/mcp_adapterremoval/requirements.txt +2 -0
  9. Biomanus/biomni_web/backend/data/mcp_generated/mcp_alfred/Dockerfile +40 -0
  10. Biomanus/biomni_web/backend/data/mcp_generated/mcp_alfred/app/__pycache__/alfred_shim_server.cpython-311.pyc +0 -0
  11. Biomanus/biomni_web/backend/data/mcp_generated/mcp_alfred/app/alfred_server.py +638 -0
  12. Biomanus/biomni_web/backend/data/mcp_generated/mcp_alfred/app/alfred_shim_server.py +55 -0
  13. Biomanus/biomni_web/backend/data/mcp_generated/mcp_alfred/app/requirements.txt +1 -0
  14. Biomanus/biomni_web/backend/data/mcp_generated/mcp_alfred/docker-compose.yml +22 -0
  15. Biomanus/biomni_web/backend/data/mcp_generated/mcp_alfred/environment.yaml +10 -0
  16. Biomanus/biomni_web/backend/data/mcp_generated/mcp_alfred/requirements.txt +2 -0
  17. Biomanus/biomni_web/backend/data/mcp_generated/mcp_anansescanpy/Dockerfile +40 -0
  18. Biomanus/biomni_web/backend/data/mcp_generated/mcp_anansescanpy/app/__pycache__/anansescanpy_shim_server.cpython-311.pyc +0 -0
  19. Biomanus/biomni_web/backend/data/mcp_generated/mcp_anansescanpy/app/anansescanpy_server.py +278 -0
  20. Biomanus/biomni_web/backend/data/mcp_generated/mcp_anansescanpy/app/anansescanpy_shim_server.py +55 -0
  21. Biomanus/biomni_web/backend/data/mcp_generated/mcp_anansescanpy/docker-compose.yml +22 -0
  22. Biomanus/biomni_web/backend/data/mcp_generated/mcp_anansescanpy/environment.yaml +10 -0
  23. Biomanus/biomni_web/backend/data/mcp_generated/mcp_anansescanpy/requirements.txt +2 -0
  24. Biomanus/biomni_web/backend/data/mcp_generated/mcp_aria2/Dockerfile +40 -0
  25. Biomanus/biomni_web/backend/data/mcp_generated/mcp_aria2/app/__pycache__/aria2_shim_server.cpython-311.pyc +0 -0
  26. Biomanus/biomni_web/backend/data/mcp_generated/mcp_aria2/app/aria2_server.py +315 -0
  27. Biomanus/biomni_web/backend/data/mcp_generated/mcp_aria2/app/aria2_shim_server.py +55 -0
  28. Biomanus/biomni_web/backend/data/mcp_generated/mcp_aria2/docker-compose.yml +22 -0
  29. Biomanus/biomni_web/backend/data/mcp_generated/mcp_aria2/environment.yaml +10 -0
  30. Biomanus/biomni_web/backend/data/mcp_generated/mcp_aria2/requirements.txt +2 -0
  31. Biomanus/biomni_web/backend/data/mcp_generated/mcp_augur/requirements.txt +2 -0
  32. Biomanus/biomni_web/backend/data/mcp_generated/mcp_bbmap/Dockerfile +40 -0
  33. Biomanus/biomni_web/backend/data/mcp_generated/mcp_bbmap/app/__pycache__/bbmap_shim_server.cpython-311.pyc +0 -0
  34. Biomanus/biomni_web/backend/data/mcp_generated/mcp_bbmap/app/bbmap_server.py +234 -0
  35. Biomanus/biomni_web/backend/data/mcp_generated/mcp_bbmap/app/bbmap_shim_server.py +55 -0
  36. Biomanus/biomni_web/backend/data/mcp_generated/mcp_bbmap/docker-compose.yml +22 -0
  37. Biomanus/biomni_web/backend/data/mcp_generated/mcp_bbmap/environment.yaml +10 -0
  38. Biomanus/biomni_web/backend/data/mcp_generated/mcp_bbmap/requirements.txt +2 -0
  39. Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affy/Dockerfile +40 -0
  40. Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affy/app/__pycache__/bioconductor-affy_shim_server.cpython-311.pyc +0 -0
  41. Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affy/app/bioconductor-affy_server.py +196 -0
  42. Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affy/app/bioconductor-affy_shim_server.py +55 -0
  43. Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affy/app/requirements.txt +1 -0
  44. Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affy/docker-compose.yml +22 -0
  45. Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affy/environment.yaml +10 -0
  46. Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affy/requirements.txt +2 -0
  47. Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-annotationdbi/environment.yaml +10 -0
  48. Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-biocfilecache/Dockerfile +40 -0
  49. Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-biocfilecache/app/__pycache__/bioconductor-biocfilecache_shim_server.cpython-311.pyc +0 -0
  50. Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-biocfilecache/app/bioconductor-biocfilecache_server.py +314 -0
Biomanus/biomni_web/backend/data/mcp_generated/mcp_adapterremoval/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 adapterremoval via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda adapterremoval -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/adapterremoval_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/adapterremoval_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/adapterremoval_server.py"]
40
+
Biomanus/biomni_web/backend/data/mcp_generated/mcp_adapterremoval/app/__pycache__/adapterremoval_shim_server.cpython-311.pyc ADDED
Binary file (3.6 kB). View file
 
Biomanus/biomni_web/backend/data/mcp_generated/mcp_adapterremoval/app/adapterremoval_server.py ADDED
@@ -0,0 +1,291 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ from pathlib import Path
3
+ from typing import Optional, List, Dict, Any
4
+
5
+ from mcp.server.fastmcp import FastMCP
6
+
7
+ SERVER_NAME = 'local_adapterremoval'
8
+ mcp = FastMCP(SERVER_NAME)
9
+
10
+ @mcp.tool()
11
+ def adapter_removal(
12
+ file1: str,
13
+ file2: Optional[str] = None,
14
+ adapter1: str = "AGATCGGAAGAGCACACGTCTGAACTCCAGTCAC",
15
+ adapter2: str = "AGATCGGAAGAGCGTCGTGTAGGGAAAGAGTGTAGATCTCGGTGGTCGCCGTATCATT",
16
+ adapter_list: Optional[str] = None,
17
+ basename: str = "adapterremoval_output",
18
+ trimns: bool = False,
19
+ trimqualities: bool = False,
20
+ minquality: int = 2,
21
+ minlength: int = 15,
22
+ maxlength: int = 0,
23
+ collapse: bool = False,
24
+ collapse_deterministic: bool = False,
25
+ mismatchrate: float = 0.333,
26
+ minadapteroverlap: int = 0,
27
+ gzip: bool = False,
28
+ bzip2: bool = False,
29
+ threads: int = 1,
30
+ interleaved: bool = False,
31
+ interleaved_output: bool = False,
32
+ qualitybase: int = 33,
33
+ qualitymax: int = 41,
34
+ mate_separator: str = "/",
35
+ trim_low_complexity: bool = False,
36
+ ):
37
+ """
38
+ Perform adapter trimming, quality trimming, and optional merging of paired-end reads using AdapterRemoval v2.
39
+
40
+ Args:
41
+ file1: Path to the first input FASTQ file (or interleaved file).
42
+ file2: Path to the second input FASTQ file (optional).
43
+ adapter1: Sequence of the first adapter.
44
+ adapter2: Sequence of the second adapter.
45
+ adapter_list: Path to a file containing a list of adapters (one per line).
46
+ basename: Prefix for all output files.
47
+ trimns: If True, trim ambiguous bases (N) from the 5' and 3' ends.
48
+ trimqualities: If True, trim low-quality bases from the 5' and 3' ends.
49
+ minquality: Minimum quality score for trimming (default 2).
50
+ minlength: Minimum read length after trimming (default 15).
51
+ maxlength: Maximum read length; reads longer than this are discarded (0 = disabled).
52
+ collapse: If True, merge overlapping paired-end reads into a single consensus sequence.
53
+ collapse_deterministic: If True, use deterministic merging for overlapping reads.
54
+ mismatchrate: Maximum allowed fraction of mismatches in the overlapping region (default 0.333).
55
+ minadapteroverlap: Minimum overlap between read and adapter (default 0).
56
+ gzip: If True, compress output files using gzip.
57
+ bzip2: If True, compress output files using bzip2.
58
+ threads: Number of threads to use.
59
+ interleaved: If True, input file1 is treated as an interleaved paired-end file.
60
+ interleaved_output: If True, output paired-end reads in a single interleaved file.
61
+ qualitybase: Phred quality score offset (33 or 64).
62
+ qualitymax: Maximum Phred quality score (default 41).
63
+ mate_separator: Character separating mate number in read names (default '/').
64
+ trim_low_complexity: If True, trim low complexity (e.g. poly-A) sequences.
65
+ """
66
+ # Input validation
67
+ f1_path = Path(file1)
68
+ if not f1_path.exists():
69
+ raise FileNotFoundError(f"Input file1 not found: {file1}")
70
+
71
+ cmd = ["AdapterRemoval", "--file1", str(f1_path)]
72
+
73
+ if file2:
74
+ f2_path = Path(file2)
75
+ if not f2_path.exists():
76
+ raise FileNotFoundError(f"Input file2 not found: {file2}")
77
+ cmd.extend(["--file2", str(f2_path)])
78
+
79
+ if adapter_list:
80
+ alist_path = Path(adapter_list)
81
+ if not alist_path.exists():
82
+ raise FileNotFoundError(f"Adapter list file not found: {adapter_list}")
83
+ cmd.extend(["--adapter-list", str(alist_path)])
84
+ else:
85
+ cmd.extend(["--adapter1", adapter1, "--adapter2", adapter2])
86
+
87
+ # Parameters
88
+ cmd.extend(["--basename", basename])
89
+ cmd.extend(["--minquality", str(minquality)])
90
+ cmd.extend(["--minlength", str(minlength)])
91
+ cmd.extend(["--mismatchrate", str(mismatchrate)])
92
+ cmd.extend(["--minadapteroverlap", str(minadapteroverlap)])
93
+ cmd.extend(["--threads", str(threads)])
94
+ cmd.extend(["--qualitybase", str(qualitybase)])
95
+ cmd.extend(["--qualitymax", str(qualitymax)])
96
+ cmd.extend(["--mate-separator", mate_separator])
97
+
98
+ if trimns: cmd.append("--trimns")
99
+ if trimqualities: cmd.append("--trimqualities")
100
+ if collapse: cmd.append("--collapse")
101
+ if collapse_deterministic: cmd.append("--collapse-deterministic")
102
+ if gzip: cmd.append("--gzip")
103
+ if bzip2: cmd.append("--bzip2")
104
+ if interleaved: cmd.append("--interleaved")
105
+ if interleaved_output: cmd.append("--interleaved-output")
106
+ if trim_low_complexity: cmd.append("--trim-low-complexity")
107
+ if maxlength > 0:
108
+ cmd.extend(["--maxlength", str(maxlength)])
109
+
110
+ try:
111
+ result = subprocess.run(cmd, capture_output=True, text=True, check=True)
112
+
113
+ # Identify potential output files based on basename and flags
114
+ ext = ".gz" if gzip else (".bz2" if bzip2 else "")
115
+ output_files = [f"{basename}.settings"]
116
+
117
+ # Standard outputs
118
+ if file2 or interleaved:
119
+ output_files.extend([
120
+ f"{basename}.pair1.truncated{ext}",
121
+ f"{basename}.pair2.truncated{ext}",
122
+ f"{basename}.singleton.truncated{ext}"
123
+ ])
124
+ if collapse or collapse_deterministic:
125
+ output_files.extend([
126
+ f"{basename}.collapsed{ext}",
127
+ f"{basename}.collapsed.truncated{ext}"
128
+ ])
129
+ else:
130
+ output_files.append(f"{basename}.truncated{ext}")
131
+
132
+ # Filter for files that actually exist
133
+ existing_outputs = [f for f in output_files if Path(f).exists()]
134
+
135
+ return {
136
+ "command_executed": " ".join(cmd),
137
+ "stdout": result.stdout,
138
+ "stderr": result.stderr,
139
+ "output_files": existing_outputs
140
+ }
141
+ except subprocess.CalledProcessError as e:
142
+ return {
143
+ "command_executed": " ".join(cmd),
144
+ "error": str(e),
145
+ "stdout": e.stdout,
146
+ "stderr": e.stderr
147
+ }
148
+
149
+ @mcp.tool()
150
+ def adapter_removal_identify_adapters(
151
+ file1: str,
152
+ file2: str,
153
+ threads: int = 1,
154
+ interleaved: bool = False,
155
+ qualitybase: int = 33,
156
+ ):
157
+ """
158
+ Attempt to identify adapter sequences by looking for consensus overlaps in paired-end reads.
159
+
160
+ Args:
161
+ file1: Path to the first input FASTQ file.
162
+ file2: Path to the second input FASTQ file.
163
+ threads: Number of threads to use.
164
+ interleaved: If True, input file1 is treated as an interleaved paired-end file.
165
+ qualitybase: Phred quality score offset (33 or 64).
166
+ """
167
+ f1_path = Path(file1)
168
+ f2_path = Path(file2)
169
+
170
+ if not f1_path.exists():
171
+ raise FileNotFoundError(f"Input file1 not found: {file1}")
172
+ if not f2_path.exists() and not interleaved:
173
+ raise FileNotFoundError(f"Input file2 not found: {file2}")
174
+
175
+ cmd = [
176
+ "AdapterRemoval",
177
+ "--identify-adapters",
178
+ "--file1", str(f1_path),
179
+ "--threads", str(threads),
180
+ "--qualitybase", str(qualitybase)
181
+ ]
182
+
183
+ if not interleaved:
184
+ cmd.extend(["--file2", str(f2_path)])
185
+ else:
186
+ cmd.append("--interleaved")
187
+
188
+ try:
189
+ result = subprocess.run(cmd, capture_output=True, text=True, check=True)
190
+ return {
191
+ "command_executed": " ".join(cmd),
192
+ "stdout": result.stdout,
193
+ "stderr": result.stderr,
194
+ "identified_adapters": result.stdout # Usually printed to stdout
195
+ }
196
+ except subprocess.CalledProcessError as e:
197
+ return {
198
+ "command_executed": " ".join(cmd),
199
+ "error": str(e),
200
+ "stdout": e.stdout,
201
+ "stderr": e.stderr
202
+ }
203
+
204
+ @mcp.tool()
205
+ def adapter_removal_demultiplex(
206
+ barcode_list: str,
207
+ file1: str,
208
+ file2: Optional[str] = None,
209
+ basename: str = "demux_output",
210
+ barcode_mm: int = 1,
211
+ barcode_mm_r1: Optional[int] = None,
212
+ barcode_mm_r2: Optional[int] = None,
213
+ gzip: bool = False,
214
+ threads: int = 1,
215
+ interleaved: bool = False,
216
+ ):
217
+ """
218
+ Demultiplex reads based on a list of barcodes using AdapterRemoval v2.
219
+
220
+ Args:
221
+ barcode_list: Path to a file containing barcodes (Format: Name Barcode1 Barcode2).
222
+ file1: Path to the first input FASTQ file.
223
+ file2: Path to the second input FASTQ file (optional).
224
+ basename: Prefix for all output files.
225
+ barcode_mm: Max number of mismatches allowed in barcodes (default 1).
226
+ barcode_mm_r1: Max mismatches for barcode 1 (overrides barcode_mm).
227
+ barcode_mm_r2: Max mismatches for barcode 2 (overrides barcode_mm).
228
+ gzip: If True, compress output files using gzip.
229
+ threads: Number of threads to use.
230
+ interleaved: If True, input file1 is treated as an interleaved paired-end file.
231
+ """
232
+ blist_path = Path(barcode_list)
233
+ f1_path = Path(file1)
234
+
235
+ if not blist_path.exists():
236
+ raise FileNotFoundError(f"Barcode list file not found: {barcode_list}")
237
+ if not f1_path.exists():
238
+ raise FileNotFoundError(f"Input file1 not found: {file1}")
239
+
240
+ cmd = [
241
+ "AdapterRemoval",
242
+ "--barcode-list", str(blist_path),
243
+ "--file1", str(f1_path),
244
+ "--basename", basename,
245
+ "--threads", str(threads)
246
+ ]
247
+
248
+ if file2:
249
+ f2_path = Path(file2)
250
+ if not f2_path.exists():
251
+ raise FileNotFoundError(f"Input file2 not found: {file2}")
252
+ cmd.extend(["--file2", str(f2_path)])
253
+
254
+ if interleaved:
255
+ cmd.append("--interleaved")
256
+
257
+ if gzip:
258
+ cmd.append("--gzip")
259
+
260
+ if barcode_mm_r1 is not None:
261
+ cmd.extend(["--barcode-mm-r1", str(barcode_mm_r1)])
262
+ if barcode_mm_r2 is not None:
263
+ cmd.extend(["--barcode-mm-r2", str(barcode_mm_r2)])
264
+ if barcode_mm_r1 is None and barcode_mm_r2 is None:
265
+ cmd.extend(["--barcode-mm", str(barcode_mm)])
266
+
267
+ try:
268
+ result = subprocess.run(cmd, capture_output=True, text=True, check=True)
269
+
270
+ # Demultiplexing creates many files based on the barcode names in the list
271
+ # We'll return the settings file and a note about the outputs
272
+ ext = ".gz" if gzip else ""
273
+ settings_file = f"{basename}.settings"
274
+
275
+ return {
276
+ "command_executed": " ".join(cmd),
277
+ "stdout": result.stdout,
278
+ "stderr": result.stderr,
279
+ "settings_file": settings_file if Path(settings_file).exists() else "Not found",
280
+ "info": "Demultiplexed files are created with the prefix specified in the barcode list."
281
+ }
282
+ except subprocess.CalledProcessError as e:
283
+ return {
284
+ "command_executed": " ".join(cmd),
285
+ "error": str(e),
286
+ "stdout": e.stdout,
287
+ "stderr": e.stderr
288
+ }
289
+
290
+ if __name__ == "__main__":
291
+ mcp.run(transport="stdio")
Biomanus/biomni_web/backend/data/mcp_generated/mcp_adapterremoval/app/adapterremoval_shim_server.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_adapterremoval/app/adapterremoval_server.py')
11
+ LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name)
12
+ SERVER_NAME = 'biosci_adapterremoval'
13
+
14
+
15
+ class _ShimMCP:
16
+ @staticmethod
17
+ def tool(*args, **kwargs):
18
+ if args and callable(args[0]) and len(args) == 1 and not kwargs:
19
+ return args[0]
20
+ def _decorator(fn):
21
+ return fn
22
+ return _decorator
23
+
24
+
25
+ def _resolve_source_server():
26
+ if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name:
27
+ return LOCAL_SERVER
28
+ return SOURCE_SERVER
29
+
30
+
31
+ def _load_functions():
32
+ source_server = _resolve_source_server()
33
+ code = source_server.read_text(encoding="utf-8")
34
+ tree = ast.parse(code, filename=str(source_server))
35
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
36
+ namespace = {
37
+ "__name__": "__mcp_source__",
38
+ "mcp": _ShimMCP(),
39
+ }
40
+ exec(compile(code, str(source_server), "exec"), namespace, namespace)
41
+ loaded = []
42
+ for name in function_names:
43
+ fn = namespace.get(name)
44
+ if callable(fn):
45
+ loaded.append(fn)
46
+ return loaded
47
+
48
+
49
+ mcp = FastMCP(SERVER_NAME)
50
+ for _fn in _load_functions():
51
+ mcp.tool()(_fn)
52
+
53
+
54
+ if __name__ == "__main__":
55
+ mcp.run(transport="stdio")
Biomanus/biomni_web/backend/data/mcp_generated/mcp_adapterremoval/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
Biomanus/biomni_web/backend/data/mcp_generated/mcp_adapterremoval/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-adapterremoval:
5
+ build: .
6
+ image: mcp-adapterremoval:latest
7
+ container_name: mcp-adapterremoval
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=adapterremoval
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
+
Biomanus/biomni_web/backend/data/mcp_generated/mcp_adapterremoval/environment.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ name: mcp-tool
3
+ channels:
4
+ - bioconda
5
+ - conda-forge
6
+ - defaults
7
+ dependencies:
8
+ - adapterremoval
9
+ - python=3.10
10
+
Biomanus/biomni_web/backend/data/mcp_generated/mcp_adapterremoval/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
Biomanus/biomni_web/backend/data/mcp_generated/mcp_alfred/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 alfred via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda alfred -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/alfred_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/alfred_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/alfred_server.py"]
40
+
Biomanus/biomni_web/backend/data/mcp_generated/mcp_alfred/app/__pycache__/alfred_shim_server.cpython-311.pyc ADDED
Binary file (3.56 kB). View file
 
Biomanus/biomni_web/backend/data/mcp_generated/mcp_alfred/app/alfred_server.py ADDED
@@ -0,0 +1,638 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import tempfile
3
+ from pathlib import Path
4
+ from typing import List, Literal, Optional
5
+
6
+ # MCP-related decorators are assumed to be available in the environment.
7
+ #
8
+ # For local testing, you can create a dummy decorator:
9
+ #
10
+ # def mcp_tool_dummy(*args, **kwargs):
11
+ # def decorator(func):
12
+ # return func
13
+ # return decorator
14
+ #
15
+ # mcp = type("mcp", (), {"tool": mcp_tool_dummy})
16
+
17
+
18
+ from mcp.server.fastmcp import FastMCP
19
+
20
+ SERVER_NAME = 'local_alfred'
21
+ mcp = FastMCP(SERVER_NAME)
22
+
23
+ @mcp.tool()
24
+ def alfred_stats(
25
+ in_bam: Path,
26
+ ref: Path,
27
+ outfile: Optional[Path] = None,
28
+ bed: Optional[Path] = None,
29
+ threads: int = 1,
30
+ minmapq: int = 0,
31
+ flag: int = 0,
32
+ fflag: int = 1540,
33
+ coverage: Optional[Path] = None,
34
+ dist: Optional[Path] = None,
35
+ sampleid: Optional[str] = None,
36
+ libid: Optional[str] = None,
37
+ readgroup: Optional[str] = None,
38
+ uncompressed: bool = False,
39
+ ):
40
+ """
41
+ Compute alignment summary statistics for a BAM file.
42
+
43
+ Args:
44
+ in_bam: Input BAM file.
45
+ ref: Reference FASTA file.
46
+ outfile: Output file for alignment metrics (e.g., metrics.tsv.gz). Defaults to stdout.
47
+ bed: BED file with regions of interest.
48
+ threads: Number of threads to use.
49
+ minmapq: Minimum mapping quality for reads to be considered.
50
+ flag: Required SAM flag.
51
+ fflag: Filtering SAM flag (reads with these flags will be ignored).
52
+ coverage: Output file for coverage statistics (e.g., cov.txt.gz).
53
+ dist: Output file for insert size distribution (e.g., dist.txt.gz).
54
+ sampleid: Sample ID to be used in the output.
55
+ libid: Library ID to be used in the output.
56
+ readgroup: Read-group ID to be used in the output.
57
+ uncompressed: Write uncompressed output files.
58
+ """
59
+ if not in_bam.exists():
60
+ raise FileNotFoundError(f"Input BAM file not found: {in_bam}")
61
+ if not ref.exists():
62
+ raise FileNotFoundError(f"Reference FASTA file not found: {ref}")
63
+ if bed and not bed.exists():
64
+ raise FileNotFoundError(f"BED file not found: {bed}")
65
+ if threads < 1:
66
+ raise ValueError("Number of threads must be at least 1.")
67
+
68
+ cmd = ["alfred", "stats", "-r", str(ref)]
69
+ output_files = []
70
+
71
+ if outfile:
72
+ cmd.extend(["-o", str(outfile)])
73
+ output_files.append(str(outfile))
74
+ if bed:
75
+ cmd.extend(["-b", str(bed)])
76
+ if threads > 1:
77
+ cmd.extend(["-p", str(threads)])
78
+ if minmapq != 0:
79
+ cmd.extend(["-m", str(minmapq)])
80
+ if flag != 0:
81
+ cmd.extend(["-f", str(flag)])
82
+ if fflag != 1540:
83
+ cmd.extend(["-F", str(fflag)])
84
+ if coverage:
85
+ cmd.extend(["-c", str(coverage)])
86
+ output_files.append(str(coverage))
87
+ if dist:
88
+ cmd.extend(["-d", str(dist)])
89
+ output_files.append(str(dist))
90
+ if sampleid:
91
+ cmd.extend(["-s", sampleid])
92
+ if libid:
93
+ cmd.extend(["-l", libid])
94
+ if readgroup:
95
+ cmd.extend(["-g", readgroup])
96
+ if uncompressed:
97
+ cmd.append("-u")
98
+
99
+ cmd.append(str(in_bam))
100
+
101
+ try:
102
+ result = subprocess.run(
103
+ cmd, check=True, capture_output=True, text=True, encoding="utf-8"
104
+ )
105
+ return {
106
+ "command_executed": " ".join(cmd),
107
+ "stdout": result.stdout,
108
+ "stderr": result.stderr,
109
+ "output_files": output_files,
110
+ }
111
+ except subprocess.CalledProcessError as e:
112
+ return {
113
+ "command_executed": " ".join(cmd),
114
+ "stdout": e.stdout,
115
+ "stderr": e.stderr,
116
+ "error": "Alfred stats failed",
117
+ "return_code": e.returncode,
118
+ }
119
+
120
+
121
+ @mcp.tool()
122
+ def alfred_count(
123
+ in_bam: Path,
124
+ ref: Path,
125
+ bed: Optional[Path] = None,
126
+ gtf: Optional[Path] = None,
127
+ outfile: Optional[Path] = None,
128
+ threads: int = 1,
129
+ minmapq: int = 0,
130
+ flag: int = 0,
131
+ fflag: int = 1540,
132
+ sampleid: Optional[str] = None,
133
+ libid: Optional[str] = None,
134
+ readgroup: Optional[str] = None,
135
+ uncompressed: bool = False,
136
+ feature: str = "exon",
137
+ id_attribute: str = "gene_id",
138
+ stranded: Literal[0, 1, 2] = 0,
139
+ antisense: bool = False,
140
+ ):
141
+ """
142
+ Count reads in genomic features from a BAM file.
143
+
144
+ Args:
145
+ in_bam: Input BAM file.
146
+ ref: Reference FASTA file.
147
+ bed: BED file with features. Provide either 'bed' or 'gtf'.
148
+ gtf: GTF file with features. Provide either 'bed' or 'gtf'.
149
+ outfile: Output file for feature counts (e.g., counts.tsv.gz). Defaults to stdout.
150
+ threads: Number of threads to use.
151
+ minmapq: Minimum mapping quality.
152
+ flag: Required SAM flag.
153
+ fflag: Filtering SAM flag.
154
+ sampleid: Sample ID.
155
+ libid: Library ID.
156
+ readgroup: Read-group ID.
157
+ uncompressed: Write uncompressed output.
158
+ feature: GTF feature to count (e.g., 'exon').
159
+ id_attribute: GTF identifier to aggregate by (e.g., 'gene_id').
160
+ stranded: Strandedness (0: unstranded, 1: forward, 2: reverse).
161
+ antisense: Count antisense reads.
162
+ """
163
+ if not in_bam.exists():
164
+ raise FileNotFoundError(f"Input BAM file not found: {in_bam}")
165
+ if not ref.exists():
166
+ raise FileNotFoundError(f"Reference FASTA file not found: {ref}")
167
+ if bed and gtf:
168
+ raise ValueError("Parameters 'bed' and 'gtf' are mutually exclusive.")
169
+ if not bed and not gtf:
170
+ raise ValueError("Either 'bed' or 'gtf' must be provided.")
171
+ if bed and not bed.exists():
172
+ raise FileNotFoundError(f"BED file not found: {bed}")
173
+ if gtf and not gtf.exists():
174
+ raise FileNotFoundError(f"GTF file not found: {gtf}")
175
+ if threads < 1:
176
+ raise ValueError("Number of threads must be at least 1.")
177
+
178
+ cmd = ["alfred", "count", "-r", str(ref)]
179
+ output_files = []
180
+
181
+ if bed:
182
+ cmd.extend(["-b", str(bed)])
183
+ if gtf:
184
+ cmd.extend(["-j", str(gtf)])
185
+ if outfile:
186
+ cmd.extend(["-o", str(outfile)])
187
+ output_files.append(str(outfile))
188
+ if threads > 1:
189
+ cmd.extend(["-p", str(threads)])
190
+ if minmapq != 0:
191
+ cmd.extend(["-m", str(minmapq)])
192
+ if flag != 0:
193
+ cmd.extend(["-f", str(flag)])
194
+ if fflag != 1540:
195
+ cmd.extend(["-F", str(fflag)])
196
+ if sampleid:
197
+ cmd.extend(["-s", sampleid])
198
+ if libid:
199
+ cmd.extend(["-l", libid])
200
+ if readgroup:
201
+ cmd.extend(["-g", readgroup])
202
+ if uncompressed:
203
+ cmd.append("-u")
204
+ if feature != "exon":
205
+ cmd.extend(["-e", feature])
206
+ if id_attribute != "gene_id":
207
+ cmd.extend(["-i", id_attribute])
208
+ if stranded != 0:
209
+ cmd.extend(["-a", str(stranded)])
210
+ if antisense:
211
+ cmd.append("-z")
212
+
213
+ cmd.append(str(in_bam))
214
+
215
+ try:
216
+ result = subprocess.run(
217
+ cmd, check=True, capture_output=True, text=True, encoding="utf-8"
218
+ )
219
+ return {
220
+ "command_executed": " ".join(cmd),
221
+ "stdout": result.stdout,
222
+ "stderr": result.stderr,
223
+ "output_files": output_files,
224
+ }
225
+ except subprocess.CalledProcessError as e:
226
+ return {
227
+ "command_executed": " ".join(cmd),
228
+ "stdout": e.stdout,
229
+ "stderr": e.stderr,
230
+ "error": "Alfred count failed",
231
+ "return_code": e.returncode,
232
+ }
233
+
234
+
235
+ @mcp.tool()
236
+ def alfred_annotate(
237
+ in_vcf: Path,
238
+ in_bam: Path,
239
+ outfile: Path,
240
+ ref: Path,
241
+ bed: Optional[Path] = None,
242
+ gtf: Optional[Path] = None,
243
+ threads: int = 1,
244
+ minmapq: int = 0,
245
+ flag: int = 0,
246
+ fflag: int = 1540,
247
+ feature: str = "exon",
248
+ id_attribute: str = "gene_id",
249
+ annotation_type: Literal["INFO", "FORMAT"] = "FORMAT",
250
+ field: str = "FE",
251
+ ):
252
+ """
253
+ Annotate variants in a VCF/BCF file with feature overlaps from a BAM file.
254
+
255
+ Args:
256
+ in_vcf: Input VCF/BCF file.
257
+ in_bam: Input BAM file.
258
+ outfile: Output VCF/BCF file.
259
+ ref: Reference FASTA file.
260
+ bed: BED file with features. Provide either 'bed' or 'gtf'.
261
+ gtf: GTF file with features. Provide either 'bed' or 'gtf'.
262
+ threads: Number of threads to use.
263
+ minmapq: Minimum mapping quality.
264
+ flag: Required SAM flag.
265
+ fflag: Filtering SAM flag.
266
+ feature: GTF feature to count (e.g., 'exon').
267
+ id_attribute: GTF identifier to aggregate by (e.g., 'gene_id').
268
+ annotation_type: Annotation type ('INFO' or 'FORMAT').
269
+ field: Annotation field name.
270
+ """
271
+ if not in_vcf.exists():
272
+ raise FileNotFoundError(f"Input VCF/BCF file not found: {in_vcf}")
273
+ if not in_bam.exists():
274
+ raise FileNotFoundError(f"Input BAM file not found: {in_bam}")
275
+ if not ref.exists():
276
+ raise FileNotFoundError(f"Reference FASTA file not found: {ref}")
277
+ if bed and gtf:
278
+ raise ValueError("Parameters 'bed' and 'gtf' are mutually exclusive.")
279
+ if not bed and not gtf:
280
+ raise ValueError("Either 'bed' or 'gtf' must be provided.")
281
+ if bed and not bed.exists():
282
+ raise FileNotFoundError(f"BED file not found: {bed}")
283
+ if gtf and not gtf.exists():
284
+ raise FileNotFoundError(f"GTF file not found: {gtf}")
285
+ if threads < 1:
286
+ raise ValueError("Number of threads must be at least 1.")
287
+
288
+ cmd = ["alfred", "annotate", "-o", str(outfile), "-r", str(ref)]
289
+ output_files = [str(outfile)]
290
+
291
+ if bed:
292
+ cmd.extend(["-b", str(bed)])
293
+ if gtf:
294
+ cmd.extend(["-j", str(gtf)])
295
+ if threads > 1:
296
+ cmd.extend(["-p", str(threads)])
297
+ if minmapq != 0:
298
+ cmd.extend(["-m", str(minmapq)])
299
+ if flag != 0:
300
+ cmd.extend(["-f", str(flag)])
301
+ if fflag != 1540:
302
+ cmd.extend(["-F", str(fflag)])
303
+ if feature != "exon":
304
+ cmd.extend(["-e", feature])
305
+ if id_attribute != "gene_id":
306
+ cmd.extend(["-i", id_attribute])
307
+ if annotation_type != "FORMAT":
308
+ cmd.extend(["-t", annotation_type])
309
+ if field != "FE":
310
+ cmd.extend(["-a", field])
311
+
312
+ cmd.extend([str(in_vcf), str(in_bam)])
313
+
314
+ try:
315
+ result = subprocess.run(
316
+ cmd, check=True, capture_output=True, text=True, encoding="utf-8"
317
+ )
318
+ return {
319
+ "command_executed": " ".join(cmd),
320
+ "stdout": result.stdout,
321
+ "stderr": result.stderr,
322
+ "output_files": output_files,
323
+ }
324
+ except subprocess.CalledProcessError as e:
325
+ return {
326
+ "command_executed": " ".join(cmd),
327
+ "stdout": e.stdout,
328
+ "stderr": e.stderr,
329
+ "error": "Alfred annotate failed",
330
+ "return_code": e.returncode,
331
+ }
332
+
333
+
334
+ @mcp.tool()
335
+ def alfred_qc(
336
+ input_bams: List[Path],
337
+ outfile: Path,
338
+ ref: Path,
339
+ bed: Optional[Path] = None,
340
+ gtf: Optional[Path] = None,
341
+ threads: int = 1,
342
+ minmapq: int = 0,
343
+ flag: int = 0,
344
+ fflag: int = 1540,
345
+ contigs: Optional[str] = None,
346
+ feature: str = "exon",
347
+ id_attribute: str = "gene_id",
348
+ stranded: Literal[0, 1, 2] = 0,
349
+ antisense: bool = False,
350
+ uncompressed: bool = False,
351
+ sites: Optional[Path] = None,
352
+ genome: Optional[Path] = None,
353
+ ):
354
+ """
355
+ Generate a multi-sample QC report from one or more BAM files.
356
+
357
+ Args:
358
+ input_bams: List of input BAM files.
359
+ outfile: Output file for QC metrics (e.g., out.qc.json.gz).
360
+ ref: Reference FASTA file.
361
+ bed: BED file with regions of interest.
362
+ gtf: GTF file with features.
363
+ threads: Number of threads to use.
364
+ minmapq: Minimum mapping quality.
365
+ flag: Required SAM flag.
366
+ fflag: Filtering SAM flag.
367
+ contigs: Comma-separated list of contigs to include.
368
+ feature: GTF feature to count (e.g., 'exon').
369
+ id_attribute: GTF identifier to aggregate by (e.g., 'gene_id').
370
+ stranded: Strandedness (0: unstranded, 1: forward, 2: reverse).
371
+ antisense: Count antisense reads.
372
+ uncompressed: Write uncompressed output.
373
+ sites: VCF/BCF file with sites of interest.
374
+ genome: Genome accessibility file.
375
+ """
376
+ if not input_bams:
377
+ raise ValueError("At least one input BAM file is required.")
378
+ for bam in input_bams:
379
+ if not bam.exists():
380
+ raise FileNotFoundError(f"Input BAM file not found: {bam}")
381
+ if not ref.exists():
382
+ raise FileNotFoundError(f"Reference FASTA file not found: {ref}")
383
+ if bed and not bed.exists():
384
+ raise FileNotFoundError(f"BED file not found: {bed}")
385
+ if gtf and not gtf.exists():
386
+ raise FileNotFoundError(f"GTF file not found: {gtf}")
387
+ if sites and not sites.exists():
388
+ raise FileNotFoundError(f"Sites VCF/BCF file not found: {sites}")
389
+ if genome and not genome.exists():
390
+ raise FileNotFoundError(f"Genome accessibility file not found: {genome}")
391
+ if threads < 1:
392
+ raise ValueError("Number of threads must be at least 1.")
393
+
394
+ cmd = ["alfred", "qc", "-o", str(outfile), "-r", str(ref)]
395
+ output_files = [str(outfile)]
396
+
397
+ if bed:
398
+ cmd.extend(["-b", str(bed)])
399
+ if gtf:
400
+ cmd.extend(["-j", str(gtf)])
401
+ if threads > 1:
402
+ cmd.extend(["-p", str(threads)])
403
+ if minmapq != 0:
404
+ cmd.extend(["-m", str(minmapq)])
405
+ if flag != 0:
406
+ cmd.extend(["-f", str(flag)])
407
+ if fflag != 1540:
408
+ cmd.extend(["-F", str(fflag)])
409
+ if contigs:
410
+ cmd.extend(["-c", contigs])
411
+ if feature != "exon":
412
+ cmd.extend(["-e", feature])
413
+ if id_attribute != "gene_id":
414
+ cmd.extend(["-i", id_attribute])
415
+ if stranded != 0:
416
+ cmd.extend(["-a", str(stranded)])
417
+ if antisense:
418
+ cmd.append("-z")
419
+ if uncompressed:
420
+ cmd.append("-u")
421
+ if sites:
422
+ cmd.extend(["-s", str(sites)])
423
+ if genome:
424
+ cmd.extend(["-g", str(genome)])
425
+
426
+ cmd.extend([str(bam) for bam in input_bams])
427
+
428
+ try:
429
+ result = subprocess.run(
430
+ cmd, check=True, capture_output=True, text=True, encoding="utf-8"
431
+ )
432
+ return {
433
+ "command_executed": " ".join(cmd),
434
+ "stdout": result.stdout,
435
+ "stderr": result.stderr,
436
+ "output_files": output_files,
437
+ }
438
+ except subprocess.CalledProcessError as e:
439
+ return {
440
+ "command_executed": " ".join(cmd),
441
+ "stdout": e.stdout,
442
+ "stderr": e.stderr,
443
+ "error": "Alfred qc failed",
444
+ "return_code": e.returncode,
445
+ }
446
+
447
+
448
+ @mcp.tool()
449
+ def alfred_merge(
450
+ input_qc_files: List[Path], outfile: Path, uncompressed: bool = False
451
+ ):
452
+ """
453
+ Merge multiple alfred QC files.
454
+
455
+ Args:
456
+ input_qc_files: List of input QC JSON files (e.g., *.qc.json.gz).
457
+ outfile: Output file for merged QC metrics (e.g., out.qc.json.gz).
458
+ uncompressed: Write uncompressed output.
459
+ """
460
+ if not input_qc_files:
461
+ raise ValueError("At least one input QC file is required.")
462
+ for qc_file in input_qc_files:
463
+ if not qc_file.exists():
464
+ raise FileNotFoundError(f"Input QC file not found: {qc_file}")
465
+
466
+ cmd = ["alfred", "merge", "-o", str(outfile)]
467
+ output_files = [str(outfile)]
468
+
469
+ if uncompressed:
470
+ cmd.append("-u")
471
+
472
+ cmd.extend([str(f) for f in input_qc_files])
473
+
474
+ try:
475
+ result = subprocess.run(
476
+ cmd, check=True, capture_output=True, text=True, encoding="utf-8"
477
+ )
478
+ return {
479
+ "command_executed": " ".join(cmd),
480
+ "stdout": result.stdout,
481
+ "stderr": result.stderr,
482
+ "output_files": output_files,
483
+ }
484
+ except subprocess.CalledProcessError as e:
485
+ return {
486
+ "command_executed": " ".join(cmd),
487
+ "stdout": e.stdout,
488
+ "stderr": e.stderr,
489
+ "error": "Alfred merge failed",
490
+ "return_code": e.returncode,
491
+ }
492
+
493
+
494
+ @mcp.tool()
495
+ def alfred_track(
496
+ in_bam: Path,
497
+ ref: Path,
498
+ outfile: Optional[Path] = None,
499
+ bed: Optional[Path] = None,
500
+ threads: int = 1,
501
+ minmapq: int = 0,
502
+ flag: int = 0,
503
+ fflag: int = 1540,
504
+ step: int = 1000,
505
+ window: int = 1000,
506
+ uncompressed: bool = False,
507
+ ):
508
+ """
509
+ Create a bedGraph track from a BAM file.
510
+
511
+ Args:
512
+ in_bam: Input BAM file.
513
+ ref: Reference FASTA file.
514
+ outfile: Output bedGraph file (e.g., track.bedGraph.gz). Defaults to stdout.
515
+ bed: BED file with regions of interest.
516
+ threads: Number of threads to use.
517
+ minmapq: Minimum mapping quality.
518
+ flag: Required SAM flag.
519
+ fflag: Filtering SAM flag.
520
+ step: Step size for coverage computation.
521
+ window: Window size for coverage computation.
522
+ uncompressed: Write uncompressed output.
523
+ """
524
+ if not in_bam.exists():
525
+ raise FileNotFoundError(f"Input BAM file not found: {in_bam}")
526
+ if not ref.exists():
527
+ raise FileNotFoundError(f"Reference FASTA file not found: {ref}")
528
+ if bed and not bed.exists():
529
+ raise FileNotFoundError(f"BED file not found: {bed}")
530
+ if threads < 1:
531
+ raise ValueError("Number of threads must be at least 1.")
532
+ if step <= 0 or window <= 0:
533
+ raise ValueError("Step and window sizes must be positive.")
534
+
535
+ cmd = ["alfred", "track", "-r", str(ref)]
536
+ output_files = []
537
+
538
+ if outfile:
539
+ cmd.extend(["-o", str(outfile)])
540
+ output_files.append(str(outfile))
541
+ if bed:
542
+ cmd.extend(["-b", str(bed)])
543
+ if threads > 1:
544
+ cmd.extend(["-p", str(threads)])
545
+ if minmapq != 0:
546
+ cmd.extend(["-m", str(minmapq)])
547
+ if flag != 0:
548
+ cmd.extend(["-f", str(flag)])
549
+ if fflag != 1540:
550
+ cmd.extend(["-F", str(fflag)])
551
+ if step != 1000:
552
+ cmd.extend(["-s", str(step)])
553
+ if window != 1000:
554
+ cmd.extend(["-w", str(window)])
555
+ if uncompressed:
556
+ cmd.append("-u")
557
+
558
+ cmd.append(str(in_bam))
559
+
560
+ try:
561
+ result = subprocess.run(
562
+ cmd, check=True, capture_output=True, text=True, encoding="utf-8"
563
+ )
564
+ return {
565
+ "command_executed": " ".join(cmd),
566
+ "stdout": result.stdout,
567
+ "stderr": result.stderr,
568
+ "output_files": output_files,
569
+ }
570
+ except subprocess.CalledProcessError as e:
571
+ return {
572
+ "command_executed": " ".join(cmd),
573
+ "stdout": e.stdout,
574
+ "stderr": e.stderr,
575
+ "error": "Alfred track failed",
576
+ "return_code": e.returncode,
577
+ }
578
+
579
+
580
+ @mcp.tool()
581
+ def alfred_motif(
582
+ ref_fa: Path,
583
+ motif: str,
584
+ outfile: Optional[Path] = None,
585
+ mincount: int = 1,
586
+ uncompressed: bool = False,
587
+ ):
588
+ """
589
+ Search for motifs in a FASTA file.
590
+
591
+ Args:
592
+ ref_fa: Reference FASTA file.
593
+ motif: Motif to search for.
594
+ outfile: Output BED file (e.g., motif.bed.gz). Defaults to stdout.
595
+ mincount: Minimum number of motif repeats.
596
+ uncompressed: Write uncompressed output.
597
+ """
598
+ if not ref_fa.exists():
599
+ raise FileNotFoundError(f"Reference FASTA file not found: {ref_fa}")
600
+ if not motif:
601
+ raise ValueError("Motif string cannot be empty.")
602
+ if mincount < 1:
603
+ raise ValueError("Minimum count must be at least 1.")
604
+
605
+ cmd = ["alfred", "motif", "-m", motif]
606
+ output_files = []
607
+
608
+ if outfile:
609
+ cmd.extend(["-o", str(outfile)])
610
+ output_files.append(str(outfile))
611
+ if mincount != 1:
612
+ cmd.extend(["-c", str(mincount)])
613
+ if uncompressed:
614
+ cmd.append("-u")
615
+
616
+ cmd.append(str(ref_fa))
617
+
618
+ try:
619
+ result = subprocess.run(
620
+ cmd, check=True, capture_output=True, text=True, encoding="utf-8"
621
+ )
622
+ return {
623
+ "command_executed": " ".join(cmd),
624
+ "stdout": result.stdout,
625
+ "stderr": result.stderr,
626
+ "output_files": output_files,
627
+ }
628
+ except subprocess.CalledProcessError as e:
629
+ return {
630
+ "command_executed": " ".join(cmd),
631
+ "stdout": e.stdout,
632
+ "stderr": e.stderr,
633
+ "error": "Alfred motif failed",
634
+ "return_code": e.returncode,
635
+ }
636
+
637
+ if __name__ == "__main__":
638
+ mcp.run(transport="stdio")
Biomanus/biomni_web/backend/data/mcp_generated/mcp_alfred/app/alfred_shim_server.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_alfred/app/alfred_server.py')
11
+ LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name)
12
+ SERVER_NAME = 'biosci_alfred'
13
+
14
+
15
+ class _ShimMCP:
16
+ @staticmethod
17
+ def tool(*args, **kwargs):
18
+ if args and callable(args[0]) and len(args) == 1 and not kwargs:
19
+ return args[0]
20
+ def _decorator(fn):
21
+ return fn
22
+ return _decorator
23
+
24
+
25
+ def _resolve_source_server():
26
+ if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name:
27
+ return LOCAL_SERVER
28
+ return SOURCE_SERVER
29
+
30
+
31
+ def _load_functions():
32
+ source_server = _resolve_source_server()
33
+ code = source_server.read_text(encoding="utf-8")
34
+ tree = ast.parse(code, filename=str(source_server))
35
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
36
+ namespace = {
37
+ "__name__": "__mcp_source__",
38
+ "mcp": _ShimMCP(),
39
+ }
40
+ exec(compile(code, str(source_server), "exec"), namespace, namespace)
41
+ loaded = []
42
+ for name in function_names:
43
+ fn = namespace.get(name)
44
+ if callable(fn):
45
+ loaded.append(fn)
46
+ return loaded
47
+
48
+
49
+ mcp = FastMCP(SERVER_NAME)
50
+ for _fn in _load_functions():
51
+ mcp.tool()(_fn)
52
+
53
+
54
+ if __name__ == "__main__":
55
+ mcp.run(transport="stdio")
Biomanus/biomni_web/backend/data/mcp_generated/mcp_alfred/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
Biomanus/biomni_web/backend/data/mcp_generated/mcp_alfred/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-alfred:
5
+ build: .
6
+ image: mcp-alfred:latest
7
+ container_name: mcp-alfred
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=alfred
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
+
Biomanus/biomni_web/backend/data/mcp_generated/mcp_alfred/environment.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ name: mcp-tool
3
+ channels:
4
+ - bioconda
5
+ - conda-forge
6
+ - defaults
7
+ dependencies:
8
+ - alfred
9
+ - python=3.10
10
+
Biomanus/biomni_web/backend/data/mcp_generated/mcp_alfred/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
Biomanus/biomni_web/backend/data/mcp_generated/mcp_anansescanpy/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 anansescanpy via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda anansescanpy -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 anansescanpy_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/anansescanpy_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/anansescanpy_server.py"]
40
+
Biomanus/biomni_web/backend/data/mcp_generated/mcp_anansescanpy/app/__pycache__/anansescanpy_shim_server.cpython-311.pyc ADDED
Binary file (3.59 kB). View file
 
Biomanus/biomni_web/backend/data/mcp_generated/mcp_anansescanpy/app/anansescanpy_server.py ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ from pathlib import Path
3
+ from typing import Optional
4
+ import shlex
5
+ import textwrap
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+ SERVER_NAME = 'local_anansescanpy'
10
+ mcp = FastMCP(SERVER_NAME)
11
+
12
+ @mcp.tool()
13
+ def export_scanpy(
14
+ adata_path: str,
15
+ cluster_id: str,
16
+ output_dir: str = "scANANSE",
17
+ rna_type: str = "raw",
18
+ min_cells: int = 50,
19
+ is_multiome: bool = False,
20
+ ):
21
+ """
22
+ Export Scanpy AnnData object to files compatible with ANANSE.
23
+ This function prepares the gene expression and (optionally) accessibility data
24
+ for each cluster defined in the AnnData object.
25
+
26
+ Args:
27
+ adata_path: Path to the input AnnData file (.h5ad).
28
+ cluster_id: The column in adata.obs containing cluster/cell-type labels.
29
+ output_dir: Directory where the exported files will be saved.
30
+ rna_type: Type of RNA data ('raw' or 'recount').
31
+ min_cells: Minimum number of cells per cluster to be included in the export.
32
+ is_multiome: Set to True if the AnnData object contains both RNA and ATAC data.
33
+ """
34
+ # Input validation
35
+ p_adata = Path(adata_path)
36
+ if not p_adata.exists():
37
+ return {"error": f"Input file {adata_path} not found."}
38
+
39
+ if rna_type not in ["raw", "recount"]:
40
+ return {"error": "rna_type must be either 'raw' or 'recount'."}
41
+
42
+ if min_cells < 0:
43
+ return {"error": "min_cells must be a non-negative integer."}
44
+
45
+ # Construct Python script to execute the library function
46
+ # We use a subprocess to ensure we can capture output and handle the environment
47
+ py_script = textwrap.dedent(f"""
48
+ import scanpy as sc
49
+ import anansescanpy as aspy
50
+ import os
51
+
52
+ try:
53
+ adata = sc.read_h5ad('{adata_path}')
54
+ aspy.export_scanpy(
55
+ adata,
56
+ cluster_id='{cluster_id}',
57
+ rna_type='{rna_type}',
58
+ min_cells={min_cells},
59
+ output_dir='{output_dir}',
60
+ is_multiome={is_multiome}
61
+ )
62
+ print("Export successful")
63
+ except Exception as e:
64
+ print(f"Error: {{str(e)}}")
65
+ exit(1)
66
+ """)
67
+
68
+ try:
69
+ result = subprocess.run(
70
+ ["python3", "-c", py_script],
71
+ capture_output=True,
72
+ text=True,
73
+ check=True
74
+ )
75
+ return {
76
+ "command_executed": f"anansescanpy.export_scanpy on {adata_path}",
77
+ "stdout": result.stdout,
78
+ "stderr": result.stderr,
79
+ "output_dir": output_dir
80
+ }
81
+ except subprocess.CalledProcessError as e:
82
+ return {
83
+ "error": "Failed to export Scanpy object",
84
+ "stdout": e.stdout,
85
+ "stderr": e.stderr
86
+ }
87
+
88
+ @mcp.tool()
89
+ def import_scanpy(
90
+ adata_path: str,
91
+ ananse_dir: str,
92
+ cluster_id: str,
93
+ output_path: str,
94
+ ):
95
+ """
96
+ Import ANANSE results (influence scores, GRN) back into a Scanpy AnnData object.
97
+
98
+ Args:
99
+ adata_path: Path to the original AnnData file (.h5ad).
100
+ ananse_dir: Directory containing the ANANSE output files.
101
+ cluster_id: The column in adata.obs that was used for the ANANSE analysis.
102
+ output_path: Path where the updated AnnData file will be saved.
103
+ """
104
+ p_adata = Path(adata_path)
105
+ p_ananse = Path(ananse_dir)
106
+
107
+ if not p_adata.exists():
108
+ return {"error": f"Input AnnData file {adata_path} not found."}
109
+ if not p_ananse.is_dir():
110
+ return {"error": f"ANANSE directory {ananse_dir} not found."}
111
+
112
+ py_script = textwrap.dedent(f"""
113
+ import scanpy as sc
114
+ import anansescanpy as aspy
115
+
116
+ try:
117
+ adata = sc.read_h5ad('{adata_path}')
118
+ adata = aspy.import_scanpy(
119
+ adata,
120
+ cluster_id='{cluster_id}',
121
+ ananse_dir='{ananse_dir}'
122
+ )
123
+ adata.write_h5ad('{output_path}')
124
+ print("Import successful")
125
+ except Exception as e:
126
+ print(f"Error: {{str(e)}}")
127
+ exit(1)
128
+ """)
129
+
130
+ try:
131
+ result = subprocess.run(
132
+ ["python3", "-c", py_script],
133
+ capture_output=True,
134
+ text=True,
135
+ check=True
136
+ )
137
+ return {
138
+ "command_executed": f"anansescanpy.import_scanpy from {ananse_dir}",
139
+ "stdout": result.stdout,
140
+ "stderr": result.stderr,
141
+ "output_file": output_path
142
+ }
143
+ except subprocess.CalledProcessError as e:
144
+ return {
145
+ "error": "Failed to import ANANSE results",
146
+ "stdout": e.stdout,
147
+ "stderr": e.stderr
148
+ }
149
+
150
+ @mcp.tool()
151
+ def anansnake_config(
152
+ adata_path: str,
153
+ cluster_id: str,
154
+ genome: str,
155
+ output_dir: str,
156
+ sample_col: Optional[str] = None,
157
+ atac_column: Optional[str] = None,
158
+ ):
159
+ """
160
+ Generate a configuration file for the anansnake pipeline based on a Scanpy object.
161
+
162
+ Args:
163
+ adata_path: Path to the AnnData file (.h5ad).
164
+ cluster_id: The column in adata.obs containing cluster labels.
165
+ genome: Genome assembly name (e.g., 'hg38', 'mm10').
166
+ output_dir: Directory where the config.yaml and analysis files will be created.
167
+ sample_col: Optional column in adata.obs containing sample identifiers.
168
+ atac_column: Optional column in adata.obs containing ATAC-seq peak data.
169
+ """
170
+ p_adata = Path(adata_path)
171
+ if not p_adata.exists():
172
+ return {"error": f"Input file {adata_path} not found."}
173
+
174
+ sample_arg = f"'{sample_col}'" if sample_col else "None"
175
+ atac_arg = f"'{atac_column}'" if atac_column else "None"
176
+
177
+ py_script = textwrap.dedent(f"""
178
+ import scanpy as sc
179
+ import anansescanpy as aspy
180
+
181
+ try:
182
+ adata = sc.read_h5ad('{adata_path}')
183
+ aspy.anansnake_config(
184
+ adata,
185
+ cluster_id='{cluster_id}',
186
+ genome='{genome}',
187
+ output_dir='{output_dir}',
188
+ sample_col={sample_arg},
189
+ atac_column={atac_arg}
190
+ )
191
+ print("Config generation successful")
192
+ except Exception as e:
193
+ print(f"Error: {{str(e)}}")
194
+ exit(1)
195
+ """)
196
+
197
+ try:
198
+ result = subprocess.run(
199
+ ["python3", "-c", py_script],
200
+ capture_output=True,
201
+ text=True,
202
+ check=True
203
+ )
204
+ return {
205
+ "command_executed": "anansescanpy.anansnake_config",
206
+ "stdout": result.stdout,
207
+ "stderr": result.stderr,
208
+ "output_dir": output_dir
209
+ }
210
+ except subprocess.CalledProcessError as e:
211
+ return {
212
+ "error": "Failed to generate anansnake config",
213
+ "stdout": e.stdout,
214
+ "stderr": e.stderr
215
+ }
216
+
217
+ @mcp.tool()
218
+ def run_anansnake(
219
+ config_file: str,
220
+ snakefile: str,
221
+ cores: int = 12,
222
+ memory_mb: int = 48000,
223
+ use_conda: bool = True,
224
+ conda_frontend: str = "mamba",
225
+ ):
226
+ """
227
+ Execute the anansnake GRN analysis pipeline using Snakemake.
228
+
229
+ Args:
230
+ config_file: Path to the config.yaml file (generated by anansnake_config).
231
+ snakefile: Path to the anansnake Snakefile.
232
+ cores: Number of CPU cores to use.
233
+ memory_mb: Memory resource limit in MB.
234
+ use_conda: Whether to use conda environments for the pipeline steps.
235
+ conda_frontend: The conda frontend to use ('mamba' or 'conda').
236
+ """
237
+ p_config = Path(config_file)
238
+ p_snake = Path(snakefile)
239
+
240
+ if not p_config.exists():
241
+ return {"error": f"Config file {config_file} not found."}
242
+ if not p_snake.exists():
243
+ return {"error": f"Snakefile {snakefile} not found."}
244
+
245
+ cmd = [
246
+ "snakemake",
247
+ "--configfile", str(p_config),
248
+ "--snakefile", str(p_snake),
249
+ "--cores", str(cores),
250
+ "--resources", f"mem_mb={memory_mb}"
251
+ ]
252
+
253
+ if use_conda:
254
+ cmd.append("--use-conda")
255
+ cmd.extend(["--conda-frontend", conda_frontend])
256
+
257
+ try:
258
+ result = subprocess.run(
259
+ cmd,
260
+ capture_output=True,
261
+ text=True,
262
+ check=True
263
+ )
264
+ return {
265
+ "command_executed": " ".join(cmd),
266
+ "stdout": result.stdout,
267
+ "stderr": result.stderr
268
+ }
269
+ except subprocess.CalledProcessError as e:
270
+ return {
271
+ "error": "Snakemake pipeline execution failed",
272
+ "command_executed": " ".join(cmd),
273
+ "stdout": e.stdout,
274
+ "stderr": e.stderr
275
+ }
276
+
277
+ if __name__ == "__main__":
278
+ mcp.run(transport="stdio")
Biomanus/biomni_web/backend/data/mcp_generated/mcp_anansescanpy/app/anansescanpy_shim_server.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_anansescanpy/app/anansescanpy_server.py')
11
+ LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name)
12
+ SERVER_NAME = 'biosci_anansescanpy'
13
+
14
+
15
+ class _ShimMCP:
16
+ @staticmethod
17
+ def tool(*args, **kwargs):
18
+ if args and callable(args[0]) and len(args) == 1 and not kwargs:
19
+ return args[0]
20
+ def _decorator(fn):
21
+ return fn
22
+ return _decorator
23
+
24
+
25
+ def _resolve_source_server():
26
+ if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name:
27
+ return LOCAL_SERVER
28
+ return SOURCE_SERVER
29
+
30
+
31
+ def _load_functions():
32
+ source_server = _resolve_source_server()
33
+ code = source_server.read_text(encoding="utf-8")
34
+ tree = ast.parse(code, filename=str(source_server))
35
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
36
+ namespace = {
37
+ "__name__": "__mcp_source__",
38
+ "mcp": _ShimMCP(),
39
+ }
40
+ exec(compile(code, str(source_server), "exec"), namespace, namespace)
41
+ loaded = []
42
+ for name in function_names:
43
+ fn = namespace.get(name)
44
+ if callable(fn):
45
+ loaded.append(fn)
46
+ return loaded
47
+
48
+
49
+ mcp = FastMCP(SERVER_NAME)
50
+ for _fn in _load_functions():
51
+ mcp.tool()(_fn)
52
+
53
+
54
+ if __name__ == "__main__":
55
+ mcp.run(transport="stdio")
Biomanus/biomni_web/backend/data/mcp_generated/mcp_anansescanpy/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-anansescanpy:
5
+ build: .
6
+ image: mcp-anansescanpy:latest
7
+ container_name: mcp-anansescanpy
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=anansescanpy
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
+
Biomanus/biomni_web/backend/data/mcp_generated/mcp_anansescanpy/environment.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ name: mcp-tool
3
+ channels:
4
+ - bioconda
5
+ - conda-forge
6
+ - defaults
7
+ dependencies:
8
+ - anansescanpy
9
+ - python=3.10
10
+
Biomanus/biomni_web/backend/data/mcp_generated/mcp_anansescanpy/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
Biomanus/biomni_web/backend/data/mcp_generated/mcp_aria2/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 aria2 via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda aria2 -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 aria2_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/aria2_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/aria2_server.py"]
40
+
Biomanus/biomni_web/backend/data/mcp_generated/mcp_aria2/app/__pycache__/aria2_shim_server.cpython-311.pyc ADDED
Binary file (3.56 kB). View file
 
Biomanus/biomni_web/backend/data/mcp_generated/mcp_aria2/app/aria2_server.py ADDED
@@ -0,0 +1,315 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ from pathlib import Path
3
+ from typing import List, Optional, Union
4
+
5
+ from mcp.server.fastmcp import FastMCP
6
+
7
+ SERVER_NAME = 'local_aria2'
8
+ mcp = FastMCP(SERVER_NAME)
9
+
10
+ @mcp.tool()
11
+ def aria2_download(
12
+ uris: List[str],
13
+ dir: Optional[str] = None,
14
+ out: Optional[str] = None,
15
+ split: int = 5,
16
+ max_connection_per_server: int = 1,
17
+ min_split_size: str = "20M",
18
+ continue_download: bool = True,
19
+ max_download_limit: str = "0",
20
+ user_agent: Optional[str] = None,
21
+ header: Optional[List[str]] = None,
22
+ all_proxy: Optional[str] = None,
23
+ ):
24
+ """
25
+ Download files from HTTP/HTTPS/FTP/SFTP URIs using aria2c.
26
+
27
+ :param uris: List of URIs to download.
28
+ :param dir: The directory to store the downloaded file.
29
+ :param out: The file name of the downloaded file.
30
+ :param split: Download a file using N connections.
31
+ :param max_connection_per_server: The maximum number of connections to one server for each download.
32
+ :param min_split_size: aria2 does not split less than this size. (e.g., 20M)
33
+ :param continue_download: Continue downloading a partially downloaded file.
34
+ :param max_download_limit: Set max download speed in bytes/sec. 0 means unrestricted. (e.g., 1M, 500K)
35
+ :param user_agent: Set user agent.
36
+ :param header: Append HTTP header.
37
+ :param all_proxy: Use proxy server for all protocols.
38
+ """
39
+ cmd = ["aria2c"]
40
+
41
+ if dir:
42
+ path_dir = Path(dir)
43
+ path_dir.mkdir(parents=True, exist_ok=True)
44
+ cmd.extend(["--dir", str(path_dir)])
45
+
46
+ if out:
47
+ cmd.extend(["--out", out])
48
+
49
+ cmd.extend([
50
+ f"--split={split}",
51
+ f"--max-connection-per-server={max_connection_per_server}",
52
+ f"--min-split-size={min_split_size}",
53
+ f"--continue={str(continue_download).lower()}",
54
+ f"--max-download-limit={max_download_limit}"
55
+ ])
56
+
57
+ if user_agent:
58
+ cmd.extend([f"--user-agent={user_agent}"])
59
+
60
+ if header:
61
+ for h in header:
62
+ cmd.extend([f"--header={h}"])
63
+
64
+ if all_proxy:
65
+ cmd.extend([f"--all-proxy={all_proxy}"])
66
+
67
+ cmd.extend(uris)
68
+
69
+ try:
70
+ result = subprocess.run(cmd, capture_output=True, text=True, check=True)
71
+ return {
72
+ "command_executed": " ".join(cmd),
73
+ "stdout": result.stdout,
74
+ "stderr": result.stderr,
75
+ "status": "success"
76
+ }
77
+ except subprocess.CalledProcessError as e:
78
+ return {
79
+ "command_executed": " ".join(cmd),
80
+ "stdout": e.stdout,
81
+ "stderr": e.stderr,
82
+ "error": str(e),
83
+ "status": "error"
84
+ }
85
+
86
+ @mcp.tool()
87
+ def aria2_torrent(
88
+ torrent_path: str,
89
+ dir: Optional[str] = None,
90
+ seed_time: int = 0,
91
+ max_upload_limit: str = "0",
92
+ listen_port: str = "6881-6999",
93
+ select_file: Optional[str] = None,
94
+ follow_torrent: str = "true",
95
+ ):
96
+ """
97
+ Download files using a BitTorrent file or Magnet URI.
98
+
99
+ :param torrent_path: Path to .torrent file or a Magnet URI.
100
+ :param dir: The directory to store the downloaded file.
101
+ :param seed_time: Specify seeding time in minutes. 0 means do not seed.
102
+ :param max_upload_limit: Set max upload speed in bytes/sec.
103
+ :param listen_port: Set TCP port number for BitTorrent.
104
+ :param select_file: Index of the file to download (e.g., "1,2,5").
105
+ :param follow_torrent: If 'true' or 'mem', aria2 will download the torrent file if URI is a torrent file.
106
+ """
107
+ cmd = ["aria2c"]
108
+
109
+ if dir:
110
+ path_dir = Path(dir)
111
+ path_dir.mkdir(parents=True, exist_ok=True)
112
+ cmd.extend(["--dir", str(path_dir)])
113
+
114
+ cmd.extend([
115
+ f"--seed-time={seed_time}",
116
+ f"--max-upload-limit={max_upload_limit}",
117
+ f"--listen-port={listen_port}",
118
+ f"--follow-torrent={follow_torrent}"
119
+ ])
120
+
121
+ if select_file:
122
+ cmd.extend([f"--select-file={select_file}"])
123
+
124
+ # Check if it's a local file or a magnet link
125
+ if not torrent_path.startswith("magnet:?"):
126
+ path_torrent = Path(torrent_path)
127
+ if not path_torrent.exists():
128
+ return {"error": f"Torrent file not found: {torrent_path}"}
129
+ cmd.append(str(path_torrent))
130
+ else:
131
+ cmd.append(torrent_path)
132
+
133
+ try:
134
+ result = subprocess.run(cmd, capture_output=True, text=True, check=True)
135
+ return {
136
+ "command_executed": " ".join(cmd),
137
+ "stdout": result.stdout,
138
+ "stderr": result.stderr,
139
+ "status": "success"
140
+ }
141
+ except subprocess.CalledProcessError as e:
142
+ return {
143
+ "command_executed": " ".join(cmd),
144
+ "stdout": e.stdout,
145
+ "stderr": e.stderr,
146
+ "error": str(e),
147
+ "status": "error"
148
+ }
149
+
150
+ @mcp.tool()
151
+ def aria2_metalink(
152
+ metalink_file: str,
153
+ dir: Optional[str] = None,
154
+ metalink_language: Optional[str] = None,
155
+ metalink_location: Optional[str] = None,
156
+ metalink_os: Optional[str] = None,
157
+ ):
158
+ """
159
+ Download files using a Metalink file.
160
+
161
+ :param metalink_file: Path to the .metalink file.
162
+ :param dir: The directory to store the downloaded file.
163
+ :param metalink_language: The language of the file to download.
164
+ :param metalink_location: The location of the preferred server.
165
+ :param metalink_os: The operating system of the file to download.
166
+ """
167
+ path_meta = Path(metalink_file)
168
+ if not path_meta.exists():
169
+ return {"error": f"Metalink file not found: {metalink_file}"}
170
+
171
+ cmd = ["aria2c"]
172
+
173
+ if dir:
174
+ path_dir = Path(dir)
175
+ path_dir.mkdir(parents=True, exist_ok=True)
176
+ cmd.extend(["--dir", str(path_dir)])
177
+
178
+ if metalink_language:
179
+ cmd.extend([f"--metalink-language={metalink_language}"])
180
+ if metalink_location:
181
+ cmd.extend([f"--metalink-location={metalink_location}"])
182
+ if metalink_os:
183
+ cmd.extend([f"--metalink-os={metalink_os}"])
184
+
185
+ cmd.append(str(path_meta))
186
+
187
+ try:
188
+ result = subprocess.run(cmd, capture_output=True, text=True, check=True)
189
+ return {
190
+ "command_executed": " ".join(cmd),
191
+ "stdout": result.stdout,
192
+ "stderr": result.stderr,
193
+ "status": "success"
194
+ }
195
+ except subprocess.CalledProcessError as e:
196
+ return {
197
+ "command_executed": " ".join(cmd),
198
+ "stdout": e.stdout,
199
+ "stderr": e.stderr,
200
+ "error": str(e),
201
+ "status": "error"
202
+ }
203
+
204
+ @mcp.tool()
205
+ def aria2_batch_download(
206
+ input_file: str,
207
+ dir: Optional[str] = None,
208
+ force_sequential: bool = False,
209
+ max_concurrent_downloads: int = 5,
210
+ parameterized_uris: bool = False,
211
+ ):
212
+ """
213
+ Download multiple URIs from a text file.
214
+
215
+ :param input_file: Path to the file containing URIs (one per line).
216
+ :param dir: The directory to store the downloaded files.
217
+ :param force_sequential: Fetch URIs in the order they appear in the input file.
218
+ :param max_concurrent_downloads: Set maximum number of parallel downloads.
219
+ :param parameterized_uris: Enable parameterized URI support (e.g. http://{host1,host2}/file).
220
+ """
221
+ path_input = Path(input_file)
222
+ if not path_input.exists():
223
+ return {"error": f"Input file not found: {input_file}"}
224
+
225
+ cmd = ["aria2c", f"--input-file={str(path_input)}"]
226
+
227
+ if dir:
228
+ path_dir = Path(dir)
229
+ path_dir.mkdir(parents=True, exist_ok=True)
230
+ cmd.extend(["--dir", str(path_dir)])
231
+
232
+ cmd.extend([
233
+ f"--force-sequential={str(force_sequential).lower()}",
234
+ f"--max-concurrent-downloads={max_concurrent_downloads}",
235
+ f"--parameterized-uri={str(parameterized_uris).lower()}"
236
+ ])
237
+
238
+ try:
239
+ result = subprocess.run(cmd, capture_output=True, text=True, check=True)
240
+ return {
241
+ "command_executed": " ".join(cmd),
242
+ "stdout": result.stdout,
243
+ "stderr": result.stderr,
244
+ "status": "success"
245
+ }
246
+ except subprocess.CalledProcessError as e:
247
+ return {
248
+ "command_executed": " ".join(cmd),
249
+ "stdout": e.stdout,
250
+ "stderr": e.stderr,
251
+ "error": str(e),
252
+ "status": "error"
253
+ }
254
+
255
+ @mcp.tool()
256
+ def aria2_rpc_server(
257
+ rpc_listen_port: int = 6800,
258
+ rpc_listen_all: bool = False,
259
+ rpc_secret: Optional[str] = None,
260
+ rpc_allow_origin_all: bool = False,
261
+ rpc_max_request_size: str = "2M",
262
+ daemon: bool = False,
263
+ ):
264
+ """
265
+ Start aria2 in RPC mode to allow remote control via JSON-RPC or XML-RPC.
266
+
267
+ :param rpc_listen_port: Port number for RPC server.
268
+ :param rpc_listen_all: Listen for RPC requests on all network interfaces.
269
+ :param rpc_secret: Set RPC secret authorization token.
270
+ :param rpc_allow_origin_all: Add Access-Control-Allow-Origin: * to HTTP response.
271
+ :param rpc_max_request_size: Set max size of JSON-RPC/XML-RPC request.
272
+ :param daemon: Run as a background process.
273
+ """
274
+ cmd = ["aria2c", "--enable-rpc"]
275
+
276
+ cmd.extend([
277
+ f"--rpc-listen-port={rpc_listen_port}",
278
+ f"--rpc-listen-all={str(rpc_listen_all).lower()}",
279
+ f"--rpc-allow-origin-all={str(rpc_allow_origin_all).lower()}",
280
+ f"--rpc-max-request-size={rpc_max_request_size}",
281
+ f"--daemon={str(daemon).lower()}"
282
+ ])
283
+
284
+ if rpc_secret:
285
+ cmd.append(f"--rpc-secret={rpc_secret}")
286
+
287
+ try:
288
+ # If daemon is True, we don't wait for completion
289
+ if daemon:
290
+ subprocess.Popen(cmd)
291
+ return {
292
+ "command_executed": " ".join(cmd),
293
+ "status": "daemon_started",
294
+ "message": f"aria2 RPC server started in background on port {rpc_listen_port}"
295
+ }
296
+ else:
297
+ # This will block until the server is stopped
298
+ result = subprocess.run(cmd, capture_output=True, text=True, check=True)
299
+ return {
300
+ "command_executed": " ".join(cmd),
301
+ "stdout": result.stdout,
302
+ "stderr": result.stderr,
303
+ "status": "success"
304
+ }
305
+ except subprocess.CalledProcessError as e:
306
+ return {
307
+ "command_executed": " ".join(cmd),
308
+ "stdout": e.stdout,
309
+ "stderr": e.stderr,
310
+ "error": str(e),
311
+ "status": "error"
312
+ }
313
+
314
+ if __name__ == "__main__":
315
+ mcp.run(transport="stdio")
Biomanus/biomni_web/backend/data/mcp_generated/mcp_aria2/app/aria2_shim_server.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_aria2/app/aria2_server.py')
11
+ LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name)
12
+ SERVER_NAME = 'biosci_aria2'
13
+
14
+
15
+ class _ShimMCP:
16
+ @staticmethod
17
+ def tool(*args, **kwargs):
18
+ if args and callable(args[0]) and len(args) == 1 and not kwargs:
19
+ return args[0]
20
+ def _decorator(fn):
21
+ return fn
22
+ return _decorator
23
+
24
+
25
+ def _resolve_source_server():
26
+ if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name:
27
+ return LOCAL_SERVER
28
+ return SOURCE_SERVER
29
+
30
+
31
+ def _load_functions():
32
+ source_server = _resolve_source_server()
33
+ code = source_server.read_text(encoding="utf-8")
34
+ tree = ast.parse(code, filename=str(source_server))
35
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
36
+ namespace = {
37
+ "__name__": "__mcp_source__",
38
+ "mcp": _ShimMCP(),
39
+ }
40
+ exec(compile(code, str(source_server), "exec"), namespace, namespace)
41
+ loaded = []
42
+ for name in function_names:
43
+ fn = namespace.get(name)
44
+ if callable(fn):
45
+ loaded.append(fn)
46
+ return loaded
47
+
48
+
49
+ mcp = FastMCP(SERVER_NAME)
50
+ for _fn in _load_functions():
51
+ mcp.tool()(_fn)
52
+
53
+
54
+ if __name__ == "__main__":
55
+ mcp.run(transport="stdio")
Biomanus/biomni_web/backend/data/mcp_generated/mcp_aria2/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-aria2:
5
+ build: .
6
+ image: mcp-aria2:latest
7
+ container_name: mcp-aria2
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=aria2
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
+
Biomanus/biomni_web/backend/data/mcp_generated/mcp_aria2/environment.yaml ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ name: mcp-tool
3
+ channels:
4
+ - bioconda
5
+ - conda-forge
6
+ - defaults
7
+ dependencies:
8
+ - aria2
9
+ - python=3.10
10
+
Biomanus/biomni_web/backend/data/mcp_generated/mcp_aria2/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
Biomanus/biomni_web/backend/data/mcp_generated/mcp_augur/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
Biomanus/biomni_web/backend/data/mcp_generated/mcp_bbmap/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 bbmap via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bbmap -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 bbmap_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/bbmap_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/bbmap_server.py"]
40
+
Biomanus/biomni_web/backend/data/mcp_generated/mcp_bbmap/app/__pycache__/bbmap_shim_server.cpython-311.pyc ADDED
Binary file (3.56 kB). View file
 
Biomanus/biomni_web/backend/data/mcp_generated/mcp_bbmap/app/bbmap_server.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import tempfile
3
+ from pathlib import Path
4
+ from typing import Optional, List
5
+
6
+ # This is a placeholder for the MCP decorator.
7
+ # In a real MCP environment, this would be provided by the MCP framework.
8
+ def tool(func):
9
+ def wrapper(*args, **kwargs):
10
+ return func(*args, **kwargs)
11
+ return wrapper
12
+
13
+ mcp = type("mcp", (), {"tool": tool})
14
+
15
+
16
+ @mcp.tool
17
+ def bbmap(
18
+ in_file: Path,
19
+ ref_file: Path,
20
+ out_file: Path,
21
+ in2_file: Optional[Path] = None,
22
+ out_unmapped: Optional[Path] = None,
23
+ java_memory: Optional[str] = None,
24
+ threads: Optional[int] = None,
25
+ overwrite: bool = False,
26
+ interleaved: str = "auto",
27
+ reads: int = -1,
28
+ samplerate: float = 1.0,
29
+ bamscript: Optional[Path] = None,
30
+ scafstats: Optional[Path] = None,
31
+ covstats: Optional[Path] = None,
32
+ fast: bool = False,
33
+ slow: bool = False,
34
+ vslow: bool = False,
35
+ max_indel: int = 16000,
36
+ min_identity: float = 0.76,
37
+ min_hits: int = 1,
38
+ local_alignment: bool = False,
39
+ perfect_mode: bool = False,
40
+ ambiguous_reads_mode: str = "best",
41
+ sam_version: str = "1.4",
42
+ secondary_alignments: bool = True,
43
+ max_sites: int = 5,
44
+ pairlen: int = 32000,
45
+ qtrim: str = "f",
46
+ untrim: bool = False,
47
+ trimq: int = 6,
48
+ min_avg_quality: int = 0,
49
+ nodisk: bool = False,
50
+ ) -> dict:
51
+ """
52
+ Maps sequencing reads to a reference genome using BBMap.
53
+
54
+ BBMap is a fast and accurate splice-aware read mapper. This tool wraps the
55
+ bbmap.sh script, providing a comprehensive set of parameters for fine-tuning
56
+ the mapping process.
57
+
58
+ Args:
59
+ in_file: Path to the primary input file (fasta, fastq, sam; compressed or uncompressed).
60
+ ref_file: Path to the reference genome file (fasta).
61
+ out_file: Path for the output SAM file.
62
+ in2_file: Path to the second input file for paired-end reads.
63
+ out_unmapped: Path to write unmapped reads to.
64
+ java_memory: Java heap size (e.g., '8g', '1000m'). Passed as -Xmx to the JVM.
65
+ threads: Number of threads to use. If not set, BBMap will auto-detect.
66
+ overwrite: If True, allows overwriting of existing output files.
67
+ interleaved: Set to 't' or 'f' if reads are interleaved; 'auto' detects.
68
+ reads: If positive, quit after processing this many reads.
69
+ samplerate: Subsample reads to this fraction (0.0 to 1.0).
70
+ bamscript: Write a shell script to this path for SAM to BAM conversion.
71
+ scafstats: Write statistics on coverage of each reference scaffold.
72
+ covstats: Write coverage statistics to a file.
73
+ fast: Use faster, less sensitive presets.
74
+ slow: Use slower, more sensitive presets.
75
+ vslow: Use very slow, very sensitive presets.
76
+ max_indel: Do not look for indels longer than this.
77
+ min_identity: Approximate minimum identity of reads to map (0.0 to 1.0).
78
+ min_hits: Minimum number of seed hits required for candidate sites.
79
+ local_alignment: Use local instead of global alignments.
80
+ perfect_mode: Allow only perfect mappings.
81
+ ambiguous_reads_mode: Behavior for ambiguously-mapped reads ('best', 'all', 'random', 'toss').
82
+ sam_version: Set SAM version ('1.4' or '1.5').
83
+ secondary_alignments: Allow secondary alignments for ambiguous reads.
84
+ max_sites: Maximum number of sites to record per read.
85
+ pairlen: Maximum insert size for paired-end reads.
86
+ qtrim: Quality trimming mode ('l', 'r', 'lr', 'f' for left, right, both, or none).
87
+ untrim: Untrim reads.
88
+ trimq: Quality threshold for trimming.
89
+ min_avg_quality: Reads with average quality below this will be discarded.
90
+ nodisk: If True, do not write temporary files to disk.
91
+
92
+ Returns:
93
+ A dictionary containing the executed command, stdout, stderr, and a list of output files.
94
+ """
95
+ # --- Input Validation ---
96
+ if not in_file.exists():
97
+ raise FileNotFoundError(f"Input file not found: {in_file}")
98
+ if not ref_file.exists():
99
+ raise FileNotFoundError(f"Reference file not found: {ref_file}")
100
+ if in2_file and not in2_file.exists():
101
+ raise FileNotFoundError(f"Second input file not found: {in2_file}")
102
+
103
+ if not (0.0 <= samplerate <= 1.0):
104
+ raise ValueError("samplerate must be between 0.0 and 1.0")
105
+ if not (0.0 <= min_identity <= 1.0):
106
+ raise ValueError("min_identity must be between 0.0 and 1.0")
107
+
108
+ valid_ambiguous_modes = {"best", "all", "random", "toss"}
109
+ if ambiguous_reads_mode not in valid_ambiguous_modes:
110
+ raise ValueError(f"ambiguous_reads_mode must be one of {valid_ambiguous_modes}")
111
+
112
+ valid_sam_versions = {"1.4", "1.5"}
113
+ if sam_version not in valid_sam_versions:
114
+ raise ValueError(f"sam_version must be one of {valid_sam_versions}")
115
+
116
+ valid_qtrim_modes = {"l", "r", "lr", "f"}
117
+ if qtrim not in valid_qtrim_modes:
118
+ raise ValueError(f"qtrim must be one of {valid_qtrim_modes}")
119
+
120
+ # --- Command Construction ---
121
+ cmd = ["bbmap.sh"]
122
+
123
+ if java_memory:
124
+ cmd.append(f"-Xmx{java_memory}")
125
+
126
+ # Required parameters
127
+ cmd.append(f"in={in_file}")
128
+ cmd.append(f"ref={ref_file}")
129
+ cmd.append(f"out={out_file}")
130
+
131
+ # Optional file paths
132
+ if in2_file:
133
+ cmd.append(f"in2={in2_file}")
134
+ if out_unmapped:
135
+ cmd.append(f"outu={out_unmapped}")
136
+ if bamscript:
137
+ cmd.append(f"bamscript={bamscript}")
138
+ if scafstats:
139
+ cmd.append(f"scafstats={scafstats}")
140
+ if covstats:
141
+ cmd.append(f"covstats={covstats}")
142
+
143
+ # Boolean flags (converted to 't'/'f')
144
+ if overwrite:
145
+ cmd.append("ow=t")
146
+ if fast:
147
+ cmd.append("fast=t")
148
+ if slow:
149
+ cmd.append("slow=t")
150
+ if vslow:
151
+ cmd.append("vslow=t")
152
+ if local_alignment:
153
+ cmd.append("local=t")
154
+ if perfect_mode:
155
+ cmd.append("perfectmode=t")
156
+ if secondary_alignments:
157
+ cmd.append("secondary=t")
158
+ if untrim:
159
+ cmd.append("untrim=t")
160
+ if nodisk:
161
+ cmd.append("nodisk=t")
162
+
163
+ # String and numeric parameters
164
+ if threads is not None:
165
+ cmd.append(f"threads={threads}")
166
+ if interleaved != "auto":
167
+ cmd.append(f"interleaved={interleaved}")
168
+ if reads != -1:
169
+ cmd.append(f"reads={reads}")
170
+ if samplerate != 1.0:
171
+ cmd.append(f"samplerate={samplerate}")
172
+ if max_indel != 16000:
173
+ cmd.append(f"maxindel={max_indel}")
174
+ if min_identity != 0.76:
175
+ cmd.append(f"minid={min_identity}")
176
+ if min_hits != 1:
177
+ cmd.append(f"minhits={min_hits}")
178
+ if ambiguous_reads_mode != "best":
179
+ cmd.append(f"ambiguous={ambiguous_reads_mode}")
180
+ if sam_version != "1.4":
181
+ cmd.append(f"sam={sam_version}")
182
+ if max_sites != 5:
183
+ cmd.append(f"maxsites={max_sites}")
184
+ if pairlen != 32000:
185
+ cmd.append(f"pairlen={pairlen}")
186
+ if qtrim != "f":
187
+ cmd.append(f"qtrim={qtrim}")
188
+ if trimq != 6:
189
+ cmd.append(f"trimq={trimq}")
190
+ if min_avg_quality != 0:
191
+ cmd.append(f"maq={min_avg_quality}")
192
+
193
+ # --- Subprocess Execution ---
194
+ command_str = " ".join(cmd)
195
+ try:
196
+ result = subprocess.run(
197
+ cmd,
198
+ capture_output=True,
199
+ text=True,
200
+ check=True,
201
+ )
202
+ except FileNotFoundError:
203
+ return {
204
+ "error": "bbmap.sh not found. Please ensure BBMap is in your PATH.",
205
+ "command_executed": command_str,
206
+ "stdout": "",
207
+ "stderr": "Executable not found.",
208
+ }
209
+ except subprocess.CalledProcessError as e:
210
+ return {
211
+ "error": "BBMap execution failed.",
212
+ "command_executed": command_str,
213
+ "stdout": e.stdout,
214
+ "stderr": e.stderr,
215
+ "return_code": e.returncode,
216
+ }
217
+
218
+ # --- Collect Output Files ---
219
+ output_files = [str(out_file)]
220
+ if out_unmapped:
221
+ output_files.append(str(out_unmapped))
222
+ if bamscript:
223
+ output_files.append(str(bamscript))
224
+ if scafstats:
225
+ output_files.append(str(scafstats))
226
+ if covstats:
227
+ output_files.append(str(covstats))
228
+
229
+ return {
230
+ "command_executed": command_str,
231
+ "stdout": result.stdout,
232
+ "stderr": result.stderr,
233
+ "output_files": output_files,
234
+ }
Biomanus/biomni_web/backend/data/mcp_generated/mcp_bbmap/app/bbmap_shim_server.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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_bbmap/app/bbmap_server.py')
11
+ LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name)
12
+ SERVER_NAME = 'biosci_bbmap'
13
+
14
+
15
+ class _ShimMCP:
16
+ @staticmethod
17
+ def tool(*args, **kwargs):
18
+ if args and callable(args[0]) and len(args) == 1 and not kwargs:
19
+ return args[0]
20
+ def _decorator(fn):
21
+ return fn
22
+ return _decorator
23
+
24
+
25
+ def _resolve_source_server():
26
+ if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name:
27
+ return LOCAL_SERVER
28
+ return SOURCE_SERVER
29
+
30
+
31
+ def _load_functions():
32
+ source_server = _resolve_source_server()
33
+ code = source_server.read_text(encoding="utf-8")
34
+ tree = ast.parse(code, filename=str(source_server))
35
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
36
+ namespace = {
37
+ "__name__": "__mcp_source__",
38
+ "mcp": _ShimMCP(),
39
+ }
40
+ exec(compile(code, str(source_server), "exec"), namespace, namespace)
41
+ loaded = []
42
+ for name in function_names:
43
+ fn = namespace.get(name)
44
+ if callable(fn):
45
+ loaded.append(fn)
46
+ return loaded
47
+
48
+
49
+ mcp = FastMCP(SERVER_NAME)
50
+ for _fn in _load_functions():
51
+ mcp.tool()(_fn)
52
+
53
+
54
+ if __name__ == "__main__":
55
+ mcp.run(transport="stdio")
Biomanus/biomni_web/backend/data/mcp_generated/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
+
Biomanus/biomni_web/backend/data/mcp_generated/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
+
Biomanus/biomni_web/backend/data/mcp_generated/mcp_bbmap/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affy/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-affy via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bioconductor-affy -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-affy_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-affy_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-affy_server.py"]
40
+
Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affy/app/__pycache__/bioconductor-affy_shim_server.cpython-311.pyc ADDED
Binary file (3.62 kB). View file
 
Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affy/app/bioconductor-affy_server.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import tempfile
3
+ from pathlib import Path
4
+ from typing import Optional, Dict, List
5
+
6
+ # This is a placeholder for the MCP decorator.
7
+ # In a real MCP environment, this would be provided by the MCP framework.
8
+ def tool(func):
9
+ def wrapper(*args, **kwargs):
10
+ # In a real scenario, the MCP framework would handle
11
+ # registration and execution.
12
+ return func(*args, **kwargs)
13
+ return wrapper
14
+ mcp = type("mcp", (), {"tool": tool})
15
+
16
+
17
+ @mcp.tool
18
+ def run_affy_analysis(
19
+ cel_files_dir: Path,
20
+ output_expression_file: Path,
21
+ method: str = "rma",
22
+ pheno_data_file: Optional[Path] = None,
23
+ generate_qc_plot: bool = False,
24
+ qc_plot_file: Optional[Path] = None,
25
+ ) -> Dict:
26
+ """
27
+ Performs exploratory analysis of Affymetrix oligonucleotide arrays.
28
+
29
+ This tool reads raw Affymetrix data from .CEL files, performs background
30
+ correction, normalization, and probe summarization using either the RMA
31
+ (Robust Multi-array Average) or MAS 5.0 algorithm, and outputs a matrix
32
+ of expression values.
33
+
34
+ Args:
35
+ cel_files_dir: Path to the directory containing the input .CEL files.
36
+ output_expression_file: Path to write the output expression matrix (tab-separated).
37
+ method: The processing method to use. Must be one of 'rma' or 'mas5'.
38
+ Defaults to 'rma'.
39
+ pheno_data_file: Optional path to a phenodata file describing the samples.
40
+ This should be a tab-delimited file with row names matching
41
+ the .CEL file names.
42
+ generate_qc_plot: If True, generate a quality control boxplot of the raw
43
+ probe intensities. Defaults to False.
44
+ qc_plot_file: Path to save the QC plot image (e.g., plot.png).
45
+ Required if generate_qc_plot is True.
46
+
47
+ Returns:
48
+ A dictionary containing the executed command, stdout, stderr, and a
49
+ list of output files.
50
+ """
51
+ # 1. Input Validation
52
+ if not cel_files_dir.is_dir():
53
+ raise ValueError(f"Input directory '{cel_files_dir}' does not exist or is not a directory.")
54
+
55
+ if pheno_data_file and not pheno_data_file.is_file():
56
+ raise FileNotFoundError(f"Phenodata file '{pheno_data_file}' not found.")
57
+
58
+ method_lower = method.lower()
59
+ if method_lower not in ["rma", "mas5"]:
60
+ raise ValueError(f"Invalid method '{method}'. Must be 'rma' or 'mas5'.")
61
+
62
+ if generate_qc_plot:
63
+ if qc_plot_file is None:
64
+ raise ValueError("qc_plot_file must be provided when generate_qc_plot is True.")
65
+ if not qc_plot_file.parent.exists():
66
+ qc_plot_file.parent.mkdir(parents=True, exist_ok=True)
67
+ elif qc_plot_file is not None:
68
+ print(f"Warning: qc_plot_file '{qc_plot_file}' is specified but generate_qc_plot is False. The file will not be created.")
69
+
70
+ if not output_expression_file.parent.exists():
71
+ output_expression_file.parent.mkdir(parents=True, exist_ok=True)
72
+
73
+ # 2. R Script Generation
74
+ # This script will be executed by Rscript to perform the analysis.
75
+ r_script_content = f"""
76
+ # Load necessary libraries
77
+ if (!requireNamespace("affy", quietly = TRUE)) {{
78
+ stop("The 'affy' package is not installed. Please install it from Bioconductor.")
79
+ }}
80
+ library(affy)
81
+
82
+ # Parse command-line arguments
83
+ args <- commandArgs(trailingOnly = TRUE)
84
+ if (length(args) < 3) {{
85
+ stop("Usage: Rscript script.R <cel_dir> <output_path> <method> [pheno_path_or_NA] [plot_path_or_NA]", call. = FALSE)
86
+ }}
87
+
88
+ cel_dir <- args[1]
89
+ output_path <- args[2]
90
+ method <- args[3]
91
+ pheno_path <- if (length(args) >= 4 && args[4] != "NA") args[4] else NULL
92
+ plot_path <- if (length(args) >= 5 && args[5] != "NA") args[5] else NULL
93
+
94
+ # --- Main Logic ---
95
+ tryCatch({{
96
+ # Read the data
97
+ cat("Reading CEL files from:", cel_dir, "\\n")
98
+ if (!is.null(pheno_path)) {{
99
+ cat("Using pheno data from:", pheno_path, "\\n")
100
+ # read.AnnotatedDataFrame is deprecated, using read.phenoData is more modern
101
+ pheno <- read.phenoData(pheno_path, header = TRUE, row.names = 1)
102
+ data <- ReadAffy(celfile.path = cel_dir, phenoData = pheno)
103
+ }} else {{
104
+ data <- ReadAffy(celfile.path = cel_dir)
105
+ }}
106
+ cat("Finished reading data.\\n")
107
+
108
+ # Process the data
109
+ cat("Processing data with method:", method, "\\n")
110
+ if (method == "rma") {{
111
+ eset <- rma(data)
112
+ }} else if (method == "mas5") {{
113
+ eset <- mas5(data)
114
+ }} else {{
115
+ stop(paste("Invalid method specified:", method))
116
+ }}
117
+ cat("Finished processing.\\n")
118
+
119
+ # Extract and write expression values
120
+ cat("Writing expression matrix to:", output_path, "\\n")
121
+ expression_matrix <- exprs(eset)
122
+ write.table(expression_matrix, file = output_path, sep = "\\t", quote = FALSE, col.names = NA)
123
+ cat("Done writing expression matrix.\\n")
124
+
125
+ # Generate QC plot if requested
126
+ if (!is.null(plot_path)) {{
127
+ cat("Generating QC plot at:", plot_path, "\\n")
128
+ png(filename = plot_path, width = 800, height = 600)
129
+ boxplot(data, main = "Raw Probe Intensities", las = 2, col="lightblue")
130
+ dev.off()
131
+ cat("Done generating plot.\\n")
132
+ }}
133
+
134
+ cat("Analysis complete.\\n")
135
+ }}, error = function(e) {{
136
+ cat("An error occurred:\\n")
137
+ cat(conditionMessage(e), "\\n")
138
+ quit(status = 1)
139
+ }})
140
+ """
141
+
142
+ # 3. Subprocess Execution
143
+ output_files = {"expression_matrix": str(output_expression_file)}
144
+ cmd = ["Rscript"]
145
+
146
+ try:
147
+ with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R") as r_script_file:
148
+ r_script_file.write(r_script_content)
149
+ r_script_path = r_script_file.name
150
+
151
+ # Prepare arguments for the R script
152
+ pheno_path_arg = str(pheno_data_file.resolve()) if pheno_data_file else "NA"
153
+ plot_path_arg = str(qc_plot_file.resolve()) if generate_qc_plot and qc_plot_file else "NA"
154
+
155
+ cmd.extend([
156
+ r_script_path,
157
+ str(cel_files_dir.resolve()),
158
+ str(output_expression_file.resolve()),
159
+ method_lower,
160
+ pheno_path_arg,
161
+ plot_path_arg
162
+ ])
163
+
164
+ # Execute the command
165
+ process = subprocess.run(
166
+ cmd,
167
+ check=True,
168
+ capture_output=True,
169
+ text=True
170
+ )
171
+
172
+ if generate_qc_plot and qc_plot_file:
173
+ output_files["qc_plot"] = str(qc_plot_file)
174
+
175
+ return {
176
+ "command_executed": " ".join(cmd),
177
+ "stdout": process.stdout,
178
+ "stderr": process.stderr,
179
+ "output_files": output_files
180
+ }
181
+
182
+ except subprocess.CalledProcessError as e:
183
+ return {
184
+ "command_executed": " ".join(cmd),
185
+ "stdout": e.stdout,
186
+ "stderr": e.stderr,
187
+ "error": "R script execution failed.",
188
+ "return_code": e.returncode,
189
+ "output_files": {}
190
+ }
191
+ except Exception as e:
192
+ raise e
193
+ finally:
194
+ # Clean up the temporary R script file
195
+ if 'r_script_path' in locals() and Path(r_script_path).exists():
196
+ Path(r_script_path).unlink()
Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affy/app/bioconductor-affy_shim_server.py ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-affy/app/bioconductor-affy_server.py')
11
+ LOCAL_SERVER = Path(__file__).with_name(SOURCE_SERVER.name)
12
+ SERVER_NAME = 'biosci_bioconductor_affy'
13
+
14
+
15
+ class _ShimMCP:
16
+ @staticmethod
17
+ def tool(*args, **kwargs):
18
+ if args and callable(args[0]) and len(args) == 1 and not kwargs:
19
+ return args[0]
20
+ def _decorator(fn):
21
+ return fn
22
+ return _decorator
23
+
24
+
25
+ def _resolve_source_server():
26
+ if LOCAL_SERVER.exists() and LOCAL_SERVER.name != Path(__file__).name:
27
+ return LOCAL_SERVER
28
+ return SOURCE_SERVER
29
+
30
+
31
+ def _load_functions():
32
+ source_server = _resolve_source_server()
33
+ code = source_server.read_text(encoding="utf-8")
34
+ tree = ast.parse(code, filename=str(source_server))
35
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
36
+ namespace = {
37
+ "__name__": "__mcp_source__",
38
+ "mcp": _ShimMCP(),
39
+ }
40
+ exec(compile(code, str(source_server), "exec"), namespace, namespace)
41
+ loaded = []
42
+ for name in function_names:
43
+ fn = namespace.get(name)
44
+ if callable(fn):
45
+ loaded.append(fn)
46
+ return loaded
47
+
48
+
49
+ mcp = FastMCP(SERVER_NAME)
50
+ for _fn in _load_functions():
51
+ mcp.tool()(_fn)
52
+
53
+
54
+ if __name__ == "__main__":
55
+ mcp.run(transport="stdio")
Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affy/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affy/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-bioconductor-affy:
5
+ build: .
6
+ image: mcp-bioconductor-affy:latest
7
+ container_name: mcp-bioconductor-affy
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=bioconductor-affy
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
+
Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affy/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-affy
9
+ - python=3.10
10
+
Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-affy/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
Biomanus/biomni_web/backend/data/mcp_generated/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
+
Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-biocfilecache/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-biocfilecache via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bioconductor-biocfilecache -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-biocfilecache_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-biocfilecache_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-biocfilecache_server.py"]
40
+
Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-biocfilecache/app/__pycache__/bioconductor-biocfilecache_shim_server.cpython-311.pyc ADDED
Binary file (3.66 kB). View file
 
Biomanus/biomni_web/backend/data/mcp_generated/mcp_bioconductor-biocfilecache/app/bioconductor-biocfilecache_server.py ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import logging
3
+ from pathlib import Path
4
+ from typing import List, Literal, Optional, Dict
5
+
6
+ # This is a placeholder for the actual MCP decorator.
7
+ # In a real MCP environment, this would be provided by the MCP framework.
8
+ class mcp:
9
+ @staticmethod
10
+ def tool():
11
+ def decorator(func):
12
+ return func
13
+ return decorator
14
+
15
+ def _validate_cache_path(cache_path: Path, check_exists: bool = True) -> None:
16
+ """Helper function to validate the cache path."""
17
+ if check_exists and not cache_path.is_dir():
18
+ raise FileNotFoundError(f"BiocFileCache directory not found at '{cache_path}'")
19
+
20
+ def _r_string_vector(items: List[str]) -> str:
21
+ """Converts a Python list of strings to an R character vector string."""
22
+ if not items:
23
+ return "c()"
24
+ # Escape single quotes for R: ' -> \'
25
+ escaped_items = [item.replace("'", "\\'") for item in items]
26
+ quoted_items = [f"'{item}'" for item in escaped_items]
27
+ return f"c({', '.join(quoted_items)})"
28
+
29
+ def _run_r_command(r_command: str) -> Dict:
30
+ """Executes an R command and returns a structured response."""
31
+ command = ["Rscript", "-e", r_command]
32
+ command_str = " ".join(command)
33
+ try:
34
+ result = subprocess.run(
35
+ command,
36
+ check=True,
37
+ capture_output=True,
38
+ text=True,
39
+ encoding='utf-8'
40
+ )
41
+ return {
42
+ "command_executed": command_str,
43
+ "stdout": result.stdout.strip(),
44
+ "stderr": result.stderr.strip(),
45
+ }
46
+ except FileNotFoundError:
47
+ logging.error("Rscript not found. R must be installed and in the system's PATH.")
48
+ raise RuntimeError("Rscript not found. R must be installed and in the system's PATH.")
49
+ except subprocess.CalledProcessError as e:
50
+ logging.error(f"R script execution failed.\nStderr: {e.stderr}\nStdout: {e.stdout}")
51
+ return {
52
+ "command_executed": command_str,
53
+ "stdout": e.stdout.strip(),
54
+ "stderr": e.stderr.strip(),
55
+ "error": "R script execution failed."
56
+ }
57
+
58
+ from mcp.server.fastmcp import FastMCP
59
+
60
+ SERVER_NAME = 'local_bioconductor_biocfilecache'
61
+ mcp = FastMCP(SERVER_NAME)
62
+
63
+ @mcp.tool()
64
+ def biocfilecache_new(cache_path: Path) -> Dict:
65
+ """
66
+ Creates a new, empty BiocFileCache at the specified location.
67
+
68
+ Args:
69
+ cache_path: The directory path where the cache will be created.
70
+ The parent directory must exist, and the target path must not.
71
+
72
+ Returns:
73
+ A dictionary containing the command executed, stdout (the cache path),
74
+ stderr, and the path to the created cache directory.
75
+ """
76
+ if cache_path.exists():
77
+ raise ValueError(f"Cache path '{cache_path}' already exists. Cannot create a new cache here.")
78
+ if not cache_path.parent.is_dir():
79
+ raise FileNotFoundError(f"Parent directory '{cache_path.parent}' does not exist.")
80
+
81
+ # Use forward slashes for R path compatibility
82
+ safe_cache_path = str(cache_path).replace('\\', '/')
83
+ r_command = (
84
+ f"library(BiocFileCache); "
85
+ f"bfc <- bfcnew('{safe_cache_path}', ask=FALSE); "
86
+ f"cat(bfcpath(bfc))"
87
+ )
88
+
89
+ response = _run_r_command(r_command)
90
+ if "error" not in response:
91
+ response["output_files"] = {"cache_directory": str(cache_path)}
92
+ return response
93
+
94
+ @mcp.tool()
95
+ def biocfilecache_add(
96
+ cache_path: Path,
97
+ rname: str,
98
+ fpath: str,
99
+ action: Literal["copy", "move", "asis"] = "copy",
100
+ rtype: Literal["web", "local"] = "web"
101
+ ) -> Dict:
102
+ """
103
+ Adds a resource to the BiocFileCache.
104
+
105
+ Args:
106
+ cache_path: Path to the BiocFileCache directory.
107
+ rname: A user-friendly name for the resource.
108
+ fpath: The path to the resource, either a URL or a local file path.
109
+ action: How to handle the file. 'copy' (default), 'move', or 'asis' (for remote files).
110
+ rtype: The type of resource, 'web' (default) or 'local'.
111
+
112
+ Returns:
113
+ A dictionary containing the command executed, stdout (the new resource ID), and stderr.
114
+ """
115
+ _validate_cache_path(cache_path)
116
+ if rtype == "local" and not Path(fpath).exists():
117
+ raise FileNotFoundError(f"Local file '{fpath}' not found for adding to cache.")
118
+
119
+ safe_cache_path = str(cache_path).replace('\\', '/')
120
+ # Escape single quotes and normalize path for R
121
+ safe_rname = rname.replace("'", "\\'")
122
+ safe_fpath = fpath.replace('\\', '/').replace("'", "\\'")
123
+
124
+ r_command = (
125
+ f"library(BiocFileCache); "
126
+ f"bfc <- BiocFileCache('{safe_cache_path}', ask=FALSE); "
127
+ f"rid <- bfcadd(bfc, rname='{safe_rname}', fpath='{safe_fpath}', action='{action}', rtype='{rtype}'); "
128
+ f"cat(rid)"
129
+ )
130
+ return _run_r_command(r_command)
131
+
132
+ @mcp.tool()
133
+ def biocfilecache_rpath(cache_path: Path, rids: List[str]) -> Dict:
134
+ """
135
+ Retrieves the local file paths of resources from the cache using their resource IDs (rids).
136
+
137
+ Args:
138
+ cache_path: Path to the BiocFileCache directory.
139
+ rids: A list of resource IDs (e.g., ['BFC1', 'BFC2']) to look up.
140
+
141
+ Returns:
142
+ A dictionary containing the command executed, stdout (newline-separated file paths), and stderr.
143
+ """
144
+ _validate_cache_path(cache_path)
145
+ if not rids:
146
+ raise ValueError("The 'rids' list cannot be empty.")
147
+
148
+ safe_cache_path = str(cache_path).replace('\\', '/')
149
+ rids_vector = _r_string_vector(rids)
150
+ r_command = (
151
+ f"library(BiocFileCache); "
152
+ f"bfc <- BiocFileCache('{safe_cache_path}', ask=FALSE); "
153
+ f"paths <- bfcrpath(bfc, rids={rids_vector}); "
154
+ f"cat(paths, sep='\\n')"
155
+ )
156
+ return _run_r_command(r_command)
157
+
158
+ @mcp.tool()
159
+ def biocfilecache_query(cache_path: Path, query: str, field: Optional[str] = None) -> Dict:
160
+ """
161
+ Queries the cache metadata using an SQL-like expression.
162
+
163
+ Args:
164
+ cache_path: Path to the BiocFileCache directory.
165
+ query: The SQL 'WHERE' clause for filtering resources (e.g., "rname == 'my_file'").
166
+ field: Optional. The specific column/field to return from the query results.
167
+
168
+ Returns:
169
+ A dictionary containing the command executed, stdout (query results as a table), and stderr.
170
+ """
171
+ _validate_cache_path(cache_path)
172
+ safe_cache_path = str(cache_path).replace('\\', '/')
173
+ safe_query = query.replace("'", "\\'")
174
+
175
+ field_arg = ""
176
+ if field:
177
+ safe_field = field.replace("'", "\\'")
178
+ field_arg = f", field='{safe_field}'"
179
+
180
+ r_command = (
181
+ f"library(BiocFileCache); "
182
+ f"bfc <- BiocFileCache('{safe_cache_path}', ask=FALSE); "
183
+ f"res <- bfcquery(bfc, query='{safe_query}'{field_arg}); "
184
+ f"print(res)"
185
+ )
186
+ return _run_r_command(r_command)
187
+
188
+ @mcp.tool()
189
+ def biocfilecache_remove(cache_path: Path, rids: List[str]) -> Dict:
190
+ """
191
+ Removes resources and their associated files from the cache.
192
+
193
+ Args:
194
+ cache_path: Path to the BiocFileCache directory.
195
+ rids: A list of resource IDs to remove.
196
+
197
+ Returns:
198
+ A dictionary containing the command executed, stdout, and stderr.
199
+ """
200
+ _validate_cache_path(cache_path)
201
+ if not rids:
202
+ raise ValueError("The 'rids' list cannot be empty.")
203
+
204
+ safe_cache_path = str(cache_path).replace('\\', '/')
205
+ rids_vector = _r_string_vector(rids)
206
+ r_command = (
207
+ f"library(BiocFileCache); "
208
+ f"bfc <- BiocFileCache('{safe_cache_path}', ask=FALSE); "
209
+ f"bfcremove(bfc, rids={rids_vector}); "
210
+ f"cat('Specified resources removed.')"
211
+ )
212
+ return _run_r_command(r_command)
213
+
214
+ @mcp.tool()
215
+ def biocfilecache_ls(cache_path: Path, pattern: Optional[str] = None) -> Dict:
216
+ """
217
+ Lists resources in the cache, optionally filtering by a regular expression.
218
+
219
+ Args:
220
+ cache_path: Path to the BiocFileCache directory.
221
+ pattern: An optional regular expression to filter resource names (rname).
222
+
223
+ Returns:
224
+ A dictionary containing the command executed, stdout (a table of resources), and stderr.
225
+ """
226
+ _validate_cache_path(cache_path)
227
+ safe_cache_path = str(cache_path).replace('\\', '/')
228
+
229
+ pattern_arg = ""
230
+ if pattern:
231
+ safe_pattern = pattern.replace("'", "\\'")
232
+ pattern_arg = f", pattern='{safe_pattern}'"
233
+
234
+ r_command = (
235
+ f"library(BiocFileCache); "
236
+ f"bfc <- BiocFileCache('{safe_cache_path}', ask=FALSE); "
237
+ f"res <- bfcls(bfc{pattern_arg}); "
238
+ f"print(res)"
239
+ )
240
+ return _run_r_command(r_command)
241
+
242
+ @mcp.tool()
243
+ def biocfilecache_update(cache_path: Path, rids: List[str]) -> Dict:
244
+ """
245
+ Updates resources in the cache by re-downloading them.
246
+
247
+ Args:
248
+ cache_path: Path to the BiocFileCache directory.
249
+ rids: A list of resource IDs to update.
250
+
251
+ Returns:
252
+ A dictionary containing the command executed, stdout (updated resource info), and stderr.
253
+ """
254
+ _validate_cache_path(cache_path)
255
+ if not rids:
256
+ raise ValueError("The 'rids' list cannot be empty.")
257
+
258
+ safe_cache_path = str(cache_path).replace('\\', '/')
259
+ rids_vector = _r_string_vector(rids)
260
+ r_command = (
261
+ f"library(BiocFileCache); "
262
+ f"bfc <- BiocFileCache('{safe_cache_path}', ask=FALSE); "
263
+ f"res <- bfcupdate(bfc, rids={rids_vector}); "
264
+ f"print(res)"
265
+ )
266
+ return _run_r_command(r_command)
267
+
268
+ @mcp.tool()
269
+ def biocfilecache_clean(cache_path: Path) -> Dict:
270
+ """
271
+ Cleans the cache by removing files that are no longer tracked in the database.
272
+
273
+ Args:
274
+ cache_path: Path to the BiocFileCache directory.
275
+
276
+ Returns:
277
+ A dictionary containing the command executed, stdout, and stderr.
278
+ """
279
+ _validate_cache_path(cache_path)
280
+ safe_cache_path = str(cache_path).replace('\\', '/')
281
+ r_command = (
282
+ f"library(BiocFileCache); "
283
+ f"bfc <- BiocFileCache('{safe_cache_path}', ask=FALSE); "
284
+ f"bfcclean(bfc, ask=FALSE); "
285
+ f"cat('Cache cleaned.')"
286
+ )
287
+ return _run_r_command(r_command)
288
+
289
+ @mcp.tool()
290
+ def biocfilecache_info(cache_path: Path, rids: Optional[List[str]] = None) -> Dict:
291
+ """
292
+ Retrieves detailed metadata for all or specified resources in the cache.
293
+
294
+ Args:
295
+ cache_path: Path to the BiocFileCache directory.
296
+ rids: Optional list of resource IDs to get information for. If None, info for all resources is returned.
297
+
298
+ Returns:
299
+ A dictionary containing the command executed, stdout (a table of resource info), and stderr.
300
+ """
301
+ _validate_cache_path(cache_path)
302
+ safe_cache_path = str(cache_path).replace('\\', '/')
303
+ rids_arg = f", rids={_r_string_vector(rids)}" if rids else ""
304
+
305
+ r_command = (
306
+ f"library(BiocFileCache); "
307
+ f"bfc <- BiocFileCache('{safe_cache_path}', ask=FALSE); "
308
+ f"res <- bfcinfo(bfc{rids_arg}); "
309
+ f"print(res)"
310
+ )
311
+ return _run_r_command(r_command)
312
+
313
+ if __name__ == "__main__":
314
+ mcp.run(transport="stdio")