czty commited on
Commit
43230fd
·
verified ·
1 Parent(s): abcddf7

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

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/app/bioconductor-protgenerics_server.py +281 -0
  2. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/app/bioconductor-protgenerics_shim_server.py +45 -0
  3. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/app/requirements.txt +1 -0
  4. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/docker-compose.yml +22 -0
  5. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/environment.yaml +10 -0
  6. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/requirements.txt +2 -0
  7. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/Dockerfile +40 -0
  8. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/app/bioconductor-qvalue_server.py +220 -0
  9. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/app/bioconductor-qvalue_shim_server.py +45 -0
  10. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/app/requirements.txt +1 -0
  11. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/docker-compose.yml +22 -0
  12. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/environment.yaml +10 -0
  13. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/requirements.txt +2 -0
  14. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/Dockerfile +40 -0
  15. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/app/bioconductor-rbgl_server.py +129 -0
  16. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/app/bioconductor-rbgl_shim_server.py +45 -0
  17. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/app/requirements.txt +1 -0
  18. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/docker-compose.yml +22 -0
  19. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/environment.yaml +10 -0
  20. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/requirements.txt +2 -0
  21. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-reactomegsa.data/Dockerfile +40 -0
  22. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-reactomegsa.data/app/bioconductor-reactomegsa.data_server.py +112 -0
  23. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-reactomegsa.data/app/bioconductor-reactomegsa.data_shim_server.py +45 -0
  24. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-reactomegsa.data/docker-compose.yml +22 -0
  25. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-reactomegsa.data/environment.yaml +10 -0
  26. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-reactomegsa.data/requirements.txt +2 -0
  27. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-regionalst/Dockerfile +40 -0
  28. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-regionalst/app/bioconductor-regionalst_server.py +459 -0
  29. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-regionalst/app/bioconductor-regionalst_shim_server.py +45 -0
  30. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-regionalst/docker-compose.yml +22 -0
  31. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-regionalst/environment.yaml +10 -0
  32. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-regionalst/requirements.txt +2 -0
  33. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/Dockerfile +40 -0
  34. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/app/bioconductor-rgraphviz_server.py +204 -0
  35. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/app/bioconductor-rgraphviz_shim_server.py +45 -0
  36. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/app/requirements.txt +1 -0
  37. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/docker-compose.yml +22 -0
  38. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/environment.yaml +10 -0
  39. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/requirements.txt +2 -0
  40. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/Dockerfile +40 -0
  41. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/app/bioconductor-rhdf5_server.py +132 -0
  42. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/app/bioconductor-rhdf5_shim_server.py +45 -0
  43. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/app/requirements.txt +1 -0
  44. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/docker-compose.yml +22 -0
  45. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/environment.yaml +10 -0
  46. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/requirements.txt +2 -0
  47. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5filters/Dockerfile +40 -0
  48. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5filters/app/bioconductor-rhdf5filters_server.py +70 -0
  49. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5filters/app/bioconductor-rhdf5filters_shim_server.py +45 -0
  50. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5filters/app/requirements.txt +1 -0
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/app/bioconductor-protgenerics_server.py ADDED
@@ -0,0 +1,281 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ from pathlib import Path
3
+ from typing import Optional, List, Dict, Any
4
+
5
+ @mcp.tool()
6
+ def protgenerics_check_installation() -> Dict[str, Any]:
7
+ """
8
+ Verifies if R and the bioconductor-protgenerics package are correctly installed and accessible.
9
+ This is essential because ProtGenerics is an R-based infrastructure package.
10
+ """
11
+ r_code = "if (!requireNamespace('ProtGenerics', quietly = TRUE)) { quit(status = 1) } else { cat(as.character(packageVersion('ProtGenerics'))) }"
12
+
13
+ try:
14
+ result = subprocess.run(
15
+ ["Rscript", "-e", r_code],
16
+ capture_output=True,
17
+ text=True,
18
+ check=True
19
+ )
20
+ return {
21
+ "status": "installed",
22
+ "version": result.stdout.strip(),
23
+ "command_executed": f"Rscript -e \"{r_code}\"",
24
+ "stdout": result.stdout,
25
+ "stderr": result.stderr
26
+ }
27
+ except subprocess.CalledProcessError as e:
28
+ return {
29
+ "status": "not_installed",
30
+ "error": "ProtGenerics package not found in R environment or Rscript not in PATH.",
31
+ "stdout": e.stdout,
32
+ "stderr": e.stderr
33
+ }
34
+ except FileNotFoundError:
35
+ return {
36
+ "status": "error",
37
+ "error": "Rscript command not found. Please ensure R is installed.",
38
+ "stdout": "",
39
+ "stderr": ""
40
+ }
41
+
42
+ @mcp.tool()
43
+ def protgenerics_get_package_info() -> Dict[str, Any]:
44
+ """
45
+ Returns detailed metadata about the ProtGenerics package, including its description,
46
+ maintainer, and dependencies.
47
+ """
48
+ r_code = "print(packageDescription('ProtGenerics'))"
49
+
50
+ try:
51
+ result = subprocess.run(
52
+ ["Rscript", "-e", r_code],
53
+ capture_output=True,
54
+ text=True,
55
+ check=True
56
+ )
57
+ return {
58
+ "command_executed": f"Rscript -e \"{r_code}\"",
59
+ "stdout": result.stdout,
60
+ "stderr": result.stderr
61
+ }
62
+ except subprocess.CalledProcessError as e:
63
+ return {
64
+ "error": "Failed to retrieve package information.",
65
+ "stdout": e.stdout,
66
+ "stderr": e.stderr
67
+ }
68
+
69
+ @mcp.tool()
70
+ def protgenerics_list_generics() -> Dict[str, Any]:
71
+ """
72
+ Lists all S4 generic functions exported by the ProtGenerics package.
73
+ These generics define the standard interface for proteomics data in Bioconductor.
74
+ Common generics include: mz, intensity, rtime, precursorMz, spectra, etc.
75
+ """
76
+ r_code = "cat(paste(getNamespaceExports('ProtGenerics'), collapse='\n'))"
77
+
78
+ try:
79
+ result = subprocess.run(
80
+ ["Rscript", "-e", r_code],
81
+ capture_output=True,
82
+ text=True,
83
+ check=True
84
+ )
85
+ generics = result.stdout.strip().split('\n')
86
+ return {
87
+ "count": len(generics),
88
+ "generics": generics,
89
+ "command_executed": f"Rscript -e \"{r_code}\"",
90
+ "stdout": result.stdout,
91
+ "stderr": result.stderr
92
+ }
93
+ except subprocess.CalledProcessError as e:
94
+ return {
95
+ "error": "Failed to list generics.",
96
+ "stdout": e.stdout,
97
+ "stderr": e.stderr
98
+ }
99
+
100
+ @mcp.tool()
101
+ def protgenerics_inspect_generic(generic_name: str) -> Dict[str, Any]:
102
+ """
103
+ Inspects a specific S4 generic function to show its arguments and definition.
104
+
105
+ Args:
106
+ generic_name: The name of the generic function to inspect (e.g., 'mz', 'rtime').
107
+ """
108
+ # Validate generic_name to prevent R injection
109
+ if not generic_name.replace(".", "").replace("_", "").isalnum():
110
+ return {"error": "Invalid generic name format."}
111
+
112
+ r_code = f"library(ProtGenerics); print(getGeneric('{generic_name}'))"
113
+
114
+ try:
115
+ result = subprocess.run(
116
+ ["Rscript", "-e", r_code],
117
+ capture_output=True,
118
+ text=True,
119
+ check=True
120
+ )
121
+ return {
122
+ "generic": generic_name,
123
+ "command_executed": f"Rscript -e \"{r_code}\"",
124
+ "stdout": result.stdout,
125
+ "stderr": result.stderr
126
+ }
127
+ except subprocess.CalledProcessError as e:
128
+ return {
129
+ "error": f"Failed to inspect generic '{generic_name}'. Ensure it is exported by ProtGenerics.",
130
+ "stdout": e.stdout,
131
+ "stderr": e.stderr
132
+ }
133
+
134
+ @mcp.tool()
135
+ def protgenerics_list_methods(generic_name: str) -> Dict[str, Any]:
136
+ """
137
+ Lists all available methods (implementations) for a specific ProtGenerics generic.
138
+ This shows which classes (e.g., Spectra, MSnExp) implement the generic.
139
+
140
+ Args:
141
+ generic_name: The name of the generic function (e.g., 'mz', 'intensity').
142
+ """
143
+ if not generic_name.replace(".", "").replace("_", "").isalnum():
144
+ return {"error": "Invalid generic name format."}
145
+
146
+ r_code = f"library(ProtGenerics); print(methods('{generic_name}'))"
147
+
148
+ try:
149
+ result = subprocess.run(
150
+ ["Rscript", "-e", r_code],
151
+ capture_output=True,
152
+ text=True,
153
+ check=True
154
+ )
155
+ return {
156
+ "generic": generic_name,
157
+ "command_executed": f"Rscript -e \"{r_code}\"",
158
+ "stdout": result.stdout,
159
+ "stderr": result.stderr
160
+ }
161
+ except subprocess.CalledProcessError as e:
162
+ return {
163
+ "error": f"Failed to list methods for '{generic_name}'.",
164
+ "stdout": e.stdout,
165
+ "stderr": e.stderr
166
+ }
167
+
168
+ @mcp.tool()
169
+ def protgenerics_execute_generic(
170
+ generic_name: str,
171
+ input_rds: str,
172
+ output_rds: Optional[str] = None,
173
+ additional_params: str = ""
174
+ ) -> Dict[str, Any]:
175
+ """
176
+ Executes a ProtGenerics S4 generic function on a proteomics object stored in an RDS file.
177
+ This is the primary way to use the generics defined in this package.
178
+
179
+ Args:
180
+ generic_name: The name of the generic to call (e.g., 'mz', 'intensity', 'rtime', 'msLevel').
181
+ input_rds: Path to an R RDS file containing a proteomics object (e.g., Spectra, MSnExp).
182
+ output_rds: Optional path to save the result as an RDS file if the output is a complex object.
183
+ additional_params: Optional string of additional R arguments (e.g., 'msLevel = 1').
184
+ """
185
+ input_path = Path(input_rds)
186
+ if not input_path.exists():
187
+ return {"error": f"Input file {input_rds} does not exist."}
188
+
189
+ if not generic_name.replace(".", "").replace("_", "").isalnum():
190
+ return {"error": "Invalid generic name format."}
191
+
192
+ # Construct R script
193
+ # We load ProtGenerics and the input object, then call the generic
194
+ r_script = [
195
+ "library(ProtGenerics)",
196
+ f"obj <- readRDS('{input_rds}')",
197
+ f"res <- {generic_name}(obj, {additional_params})" if additional_params else f"res <- {generic_name}(obj)"
198
+ ]
199
+
200
+ if output_rds:
201
+ r_script.append(f"saveRDS(res, '{output_rds}')")
202
+ r_script.append("cat('Result saved to RDS file.')")
203
+ else:
204
+ r_script.append("print(res)")
205
+
206
+ full_r_code = "; ".join(r_script)
207
+
208
+ try:
209
+ result = subprocess.run(
210
+ ["Rscript", "-e", full_r_code],
211
+ capture_output=True,
212
+ text=True,
213
+ check=True
214
+ )
215
+
216
+ output_files = [output_rds] if output_rds else []
217
+
218
+ return {
219
+ "command_executed": f"Rscript -e \"{full_r_code}\"",
220
+ "stdout": result.stdout,
221
+ "stderr": result.stderr,
222
+ "output_files": output_files
223
+ }
224
+ except subprocess.CalledProcessError as e:
225
+ return {
226
+ "error": f"Execution of generic '{generic_name}' failed.",
227
+ "stdout": e.stdout,
228
+ "stderr": e.stderr
229
+ }
230
+
231
+ @mcp.tool()
232
+ def protgenerics_get_news() -> Dict[str, Any]:
233
+ """
234
+ Retrieves the NEWS file for the ProtGenerics package to see recent changes and updates.
235
+ """
236
+ r_code = "print(news(package='ProtGenerics'))"
237
+
238
+ try:
239
+ result = subprocess.run(
240
+ ["Rscript", "-e", r_code],
241
+ capture_output=True,
242
+ text=True,
243
+ check=True
244
+ )
245
+ return {
246
+ "command_executed": f"Rscript -e \"{r_code}\"",
247
+ "stdout": result.stdout,
248
+ "stderr": result.stderr
249
+ }
250
+ except subprocess.CalledProcessError as e:
251
+ return {
252
+ "error": "Failed to retrieve NEWS.",
253
+ "stdout": e.stdout,
254
+ "stderr": e.stderr
255
+ }
256
+
257
+ @mcp.tool()
258
+ def protgenerics_citation() -> Dict[str, Any]:
259
+ """
260
+ Returns the citation information for the ProtGenerics package.
261
+ """
262
+ r_code = "print(citation('ProtGenerics'))"
263
+
264
+ try:
265
+ result = subprocess.run(
266
+ ["Rscript", "-e", r_code],
267
+ capture_output=True,
268
+ text=True,
269
+ check=True
270
+ )
271
+ return {
272
+ "command_executed": f"Rscript -e \"{r_code}\"",
273
+ "stdout": result.stdout,
274
+ "stderr": result.stderr
275
+ }
276
+ except subprocess.CalledProcessError as e:
277
+ return {
278
+ "error": "Failed to retrieve citation.",
279
+ "stdout": e.stdout,
280
+ "stderr": e.stderr
281
+ }
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/app/bioconductor-protgenerics_shim_server.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/app/bioconductor-protgenerics_server.py')
11
+ SERVER_NAME = 'biosci_bioconductor_protgenerics'
12
+
13
+
14
+ class _ShimMCP:
15
+ @staticmethod
16
+ def tool():
17
+ def _decorator(fn):
18
+ return fn
19
+ return _decorator
20
+
21
+
22
+ def _load_functions():
23
+ code = SOURCE_SERVER.read_text(encoding="utf-8")
24
+ tree = ast.parse(code, filename=str(SOURCE_SERVER))
25
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
26
+ namespace = {
27
+ "__name__": "__mcp_source__",
28
+ "mcp": _ShimMCP(),
29
+ }
30
+ exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace)
31
+ loaded = []
32
+ for name in function_names:
33
+ fn = namespace.get(name)
34
+ if callable(fn):
35
+ loaded.append(fn)
36
+ return loaded
37
+
38
+
39
+ mcp = FastMCP(SERVER_NAME)
40
+ for _fn in _load_functions():
41
+ mcp.tool()(_fn)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ mcp.run(transport="stdio")
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-bioconductor-protgenerics:
5
+ build: .
6
+ image: mcp-bioconductor-protgenerics:latest
7
+ container_name: mcp-bioconductor-protgenerics
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=bioconductor-protgenerics
12
+ volumes:
13
+ - ./workspace:/app/workspace
14
+ - ./output:/app/output
15
+ restart: unless-stopped
16
+ healthcheck:
17
+ test: ["CMD", "python", "-c", "import sys; sys.exit(0)"]
18
+ interval: 30s
19
+ timeout: 10s
20
+ retries: 3
21
+ start_period: 5s
22
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/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-protgenerics
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-protgenerics/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/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-qvalue via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bioconductor-qvalue -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-qvalue_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-qvalue_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-qvalue_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/app/bioconductor-qvalue_server.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import tempfile
3
+ from pathlib import Path
4
+ from typing import Optional, Dict, List, Any
5
+
6
+ # This is a placeholder for the MCP decorator.
7
+ # It supports both `@mcp.tool` and `@mcp.tool()` styles so shim loading works.
8
+ def mcp_tool_decorator(func=None):
9
+ if func is None:
10
+ def _decorator(inner_func):
11
+ return inner_func
12
+ return _decorator
13
+ return func
14
+
15
+ mcp = type("mcp", (), {"tool": staticmethod(mcp_tool_decorator)})
16
+
17
+ @mcp.tool()
18
+ def run_qvalue(
19
+ p_values_file: Path,
20
+ output_dir: Path,
21
+ output_prefix: str = "qvalue_results",
22
+ fdr_level: Optional[float] = None,
23
+ pfdr: bool = False,
24
+ lfdr_out: bool = True,
25
+ pi0_method: str = "smoother",
26
+ smooth_df: int = 3,
27
+ smooth_log_pi0: bool = False,
28
+ lambda_seq: Optional[str] = None,
29
+ plot_results: bool = True,
30
+ ) -> Dict[str, Any]:
31
+ """
32
+ Estimates q-values and local FDRs from a list of p-values using the bioconductor-qvalue R package.
33
+
34
+ This tool takes a list of p-values and estimates their q-values and local FDR values.
35
+ The q-value of a test measures the proportion of false positives incurred (the false
36
+ discovery rate) when that particular test is called significant. The local FDR measures
37
+ the posterior probability the null hypothesis is true given the test's p-value.
38
+
39
+ Args:
40
+ p_values_file: Path to a file containing a single column of p-values without a header.
41
+ output_dir: Path to the directory where output files will be saved.
42
+ output_prefix: Prefix for the output files.
43
+ fdr_level: The level at which to control the False Discovery Rate (FDR). Must be between 0 and 1.
44
+ pfdr: An indicator of whether the p-values are already sorted (p-value false discovery rate).
45
+ lfdr_out: If True, local FDR values will be calculated and included in the output.
46
+ pi0_method: Method for estimating pi0, the proportion of true null hypotheses.
47
+ Must be one of 'smoother' or 'bootstrap'.
48
+ smooth_df: Degrees of freedom to use in the smoother spline fit. Only used if pi0_method is 'smoother'.
49
+ smooth_log_pi0: If True and pi0_method is 'smoother', the spline is fit to log(pi0) instead of pi0.
50
+ lambda_seq: A comma-separated string of tuning parameter values for pi0 estimation (e.g., "0.1,0.2,0.3").
51
+ If not provided, the default R sequence `seq(0, 0.95, 0.01)` is used.
52
+ plot_results: If True, generates a PDF with diagnostic plots.
53
+
54
+ Returns:
55
+ A dictionary containing the executed command, stdout, stderr, and a list of output file paths.
56
+ """
57
+ # 1. Input Validation
58
+ if not p_values_file.is_file():
59
+ raise FileNotFoundError(f"Input file not found: {p_values_file}")
60
+
61
+ if fdr_level is not None and not (0 <= fdr_level <= 1):
62
+ raise ValueError("fdr_level must be between 0 and 1.")
63
+
64
+ if pi0_method not in ["smoother", "bootstrap"]:
65
+ raise ValueError("pi0_method must be either 'smoother' or 'bootstrap'.")
66
+
67
+ if pi0_method == "smoother" and smooth_df < 3:
68
+ raise ValueError("smooth_df must be an integer >= 3 when using the 'smoother' method.")
69
+
70
+ if lambda_seq:
71
+ try:
72
+ # Validate that all parts of the comma-separated string are numbers
73
+ [float(x) for x in lambda_seq.split(',')]
74
+ except ValueError:
75
+ raise ValueError("lambda_seq must be a comma-separated string of valid numbers.")
76
+
77
+ # 2. File Path Handling
78
+ output_dir.mkdir(parents=True, exist_ok=True)
79
+ output_prefix_path = output_dir / output_prefix
80
+
81
+ # 3. Prepare R script
82
+ # Convert Python types to R-compatible strings
83
+ r_fdr_level = "NULL" if fdr_level is None else str(fdr_level)
84
+ r_pfdr = "TRUE" if pfdr else "FALSE"
85
+ r_lfdr_out = "TRUE" if lfdr_out else "FALSE"
86
+ r_smooth_log_pi0 = "TRUE" if smooth_log_pi0 else "FALSE"
87
+ r_plot_results = "TRUE" if plot_results else "FALSE"
88
+ r_lambda_seq = "NULL" if lambda_seq is None else f"c({lambda_seq})"
89
+
90
+ r_script_content = f"""
91
+ # Load required library
92
+ library(qvalue)
93
+
94
+ # --- Parameters ---
95
+ p_values_file <- "{p_values_file.resolve()}"
96
+ output_prefix <- "{output_prefix_path.resolve()}"
97
+
98
+ # --- Read Input Data ---
99
+ # Using tryCatch for robust error handling on file read
100
+ p_values <- tryCatch({{
101
+ read.table(p_values_file, header = FALSE, col.names = c("pvalue"))$pvalue
102
+ }}, error = function(e) {{
103
+ stop(paste("Error reading p-values file:", e$message))
104
+ }})
105
+
106
+ # --- Build Argument List for qvalue() ---
107
+ qvalue_args <- list(
108
+ p = p_values,
109
+ fdr.level = {r_fdr_level},
110
+ pfdr = {r_pfdr},
111
+ lfdr.out = {r_lfdr_out},
112
+ pi0.method = "{pi0_method}",
113
+ smooth.df = {smooth_df},
114
+ smooth.log.pi0 = {r_smooth_log_pi0}
115
+ )
116
+
117
+ # Only add lambda if it was provided by the user to allow R default to be used
118
+ r_lambda_val <- {r_lambda_seq}
119
+ if (!is.null(r_lambda_val)) {{
120
+ qvalue_args$lambda <- r_lambda_val
121
+ }}
122
+
123
+ # --- Run qvalue Analysis ---
124
+ qobj <- tryCatch({{
125
+ do.call(qvalue, qvalue_args)
126
+ }}, error = function(e) {{
127
+ stop(paste("Error during qvalue execution:", e$message))
128
+ }})
129
+
130
+ # --- Save Outputs ---
131
+ # 1. Main results table
132
+ results_df <- data.frame(p_values = qobj$pvalues, q_values = qobj$qvalues)
133
+ if ({r_lfdr_out} && "lfdr" %in% names(qobj) && !is.null(qobj$lfdr)) {{
134
+ results_df$lfdr <- qobj$lfdr
135
+ }}
136
+ write.table(
137
+ results_df,
138
+ file = paste0(output_prefix, ".tsv"),
139
+ sep = "\\t",
140
+ row.names = FALSE,
141
+ quote = FALSE
142
+ )
143
+
144
+ # 2. Summary file
145
+ summary_file <- paste0(output_prefix, "_summary.txt")
146
+ sink(summary_file)
147
+ print(summary(qobj))
148
+ sink()
149
+
150
+ # 3. Plots if requested
151
+ if ({r_plot_results}) {{
152
+ pdf(paste0(output_prefix, "_plots.pdf"))
153
+ plot(qobj)
154
+ dev.off()
155
+ }}
156
+ """
157
+
158
+ # 4. Subprocess Execution
159
+ command = []
160
+ stdout_str, stderr_str = "", ""
161
+ output_files: List[str] = []
162
+
163
+ try:
164
+ with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as r_script:
165
+ r_script.write(r_script_content)
166
+ r_script_path = r_script.name
167
+
168
+ command = ["Rscript", r_script_path]
169
+ process = subprocess.run(
170
+ command,
171
+ capture_output=True,
172
+ text=True,
173
+ check=True,
174
+ )
175
+ stdout_str = process.stdout
176
+ stderr_str = process.stderr
177
+
178
+ # 5. Collect output files
179
+ results_tsv = output_prefix_path.with_suffix(".tsv")
180
+ if results_tsv.exists():
181
+ output_files.append(str(results_tsv))
182
+
183
+ summary_txt = output_dir / f"{output_prefix}_summary.txt"
184
+ if summary_txt.exists():
185
+ output_files.append(str(summary_txt))
186
+
187
+ if plot_results:
188
+ plots_pdf = output_prefix_path.with_suffix("_plots.pdf")
189
+ if plots_pdf.exists():
190
+ output_files.append(str(plots_pdf))
191
+
192
+ except subprocess.CalledProcessError as e:
193
+ return {
194
+ "command_executed": " ".join(command),
195
+ "stdout": e.stdout,
196
+ "stderr": e.stderr,
197
+ "return_code": e.returncode,
198
+ "output_files": [],
199
+ }
200
+ except Exception as e:
201
+ # Catch other potential errors like file I/O
202
+ return {
203
+ "command_executed": " ".join(command),
204
+ "stdout": "",
205
+ "stderr": str(e),
206
+ "return_code": 1,
207
+ "output_files": [],
208
+ }
209
+ finally:
210
+ # Clean up the temporary R script
211
+ if 'r_script_path' in locals() and Path(r_script_path).exists():
212
+ Path(r_script_path).unlink()
213
+
214
+ # 6. Return Structured Output
215
+ return {
216
+ "command_executed": " ".join(command),
217
+ "stdout": stdout_str,
218
+ "stderr": stderr_str,
219
+ "output_files": output_files,
220
+ }
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/app/bioconductor-qvalue_shim_server.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/app/bioconductor-qvalue_server.py')
11
+ SERVER_NAME = 'biosci_bioconductor_qvalue'
12
+
13
+
14
+ class _ShimMCP:
15
+ @staticmethod
16
+ def tool():
17
+ def _decorator(fn):
18
+ return fn
19
+ return _decorator
20
+
21
+
22
+ def _load_functions():
23
+ code = SOURCE_SERVER.read_text(encoding="utf-8")
24
+ tree = ast.parse(code, filename=str(SOURCE_SERVER))
25
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
26
+ namespace = {
27
+ "__name__": "__mcp_source__",
28
+ "mcp": _ShimMCP(),
29
+ }
30
+ exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace)
31
+ loaded = []
32
+ for name in function_names:
33
+ fn = namespace.get(name)
34
+ if callable(fn):
35
+ loaded.append(fn)
36
+ return loaded
37
+
38
+
39
+ mcp = FastMCP(SERVER_NAME)
40
+ for _fn in _load_functions():
41
+ mcp.tool()(_fn)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ mcp.run(transport="stdio")
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-bioconductor-qvalue:
5
+ build: .
6
+ image: mcp-bioconductor-qvalue:latest
7
+ container_name: mcp-bioconductor-qvalue
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=bioconductor-qvalue
12
+ volumes:
13
+ - ./workspace:/app/workspace
14
+ - ./output:/app/output
15
+ restart: unless-stopped
16
+ healthcheck:
17
+ test: ["CMD", "python", "-c", "import sys; sys.exit(0)"]
18
+ interval: 30s
19
+ timeout: 10s
20
+ retries: 3
21
+ start_period: 5s
22
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/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-qvalue
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-qvalue/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/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-rbgl via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bioconductor-rbgl -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-rbgl_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-rbgl_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-rbgl_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/app/bioconductor-rbgl_server.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import tempfile
3
+ from pathlib import Path
4
+ from typing import Optional, List, Dict, Any
5
+
6
+ # No mcp import needed as per instructions
7
+
8
+ # The bioconductor-rbgl package is an R library and does not expose a direct
9
+ # command-line interface with subcommands or parameters that can be parsed
10
+ # from standard CLI help. The provided documentation confirms this by showing
11
+ # an Rscript error and directing users to R-specific documentation (vignettes,
12
+ # reference manual) for usage.
13
+ #
14
+ # To interact with RBGL, one typically writes an R script that loads the
15
+ # package and calls its functions. Since the specific R functions, their
16
+ # arguments, and return types are not detailed in the provided documentation,
17
+ # it is impossible to create individual MCP tools for "EVERY internal functions"
18
+ # of the RBGL package.
19
+ #
20
+ # This MCP tool provides a generic interface to execute R code, allowing users
21
+ # to leverage RBGL's functionality by supplying the necessary R script.
22
+
23
+ @mcp.tool()
24
+ def execute_rbgl_r_code(
25
+ r_code: str,
26
+ output_file_patterns: Optional[List[str]] = None,
27
+ r_args: Optional[List[str]] = None,
28
+ working_directory: Optional[Path] = None,
29
+ ) -> Dict[str, Any]:
30
+ """
31
+ Executes R code that can utilize the Bioconductor RBGL package.
32
+
33
+ This tool provides a generic interface to run R scripts that leverage
34
+ the RBGL library for graph algorithms. Since RBGL is an R package and
35
+ does not expose a direct command-line interface, users are expected
36
+ to provide the R code directly. The R code should typically include
37
+ `library(RBGL)` to load the package.
38
+
39
+ Args:
40
+ r_code: A string containing the R code to execute. This code should
41
+ include `library(RBGL)` and calls to RBGL functions as needed.
42
+ output_file_patterns: An optional list of glob patterns (e.g., "*.csv", "output_*.txt")
43
+ to identify and collect output files generated by the R script
44
+ within the working directory.
45
+ r_args: Optional list of additional arguments to pass to Rscript.
46
+ These can be accessed within the R script via `commandArgs(trailingOnly=TRUE)`.
47
+ working_directory: Optional path to a directory where the R script
48
+ should be executed. If not provided, a temporary
49
+ directory will be used.
50
+
51
+ Returns:
52
+ A dictionary containing the command executed, stdout, stderr, and
53
+ a list of any output files generated.
54
+ """
55
+ if not r_code:
56
+ raise ValueError("R code cannot be empty.")
57
+
58
+ command = ["Rscript", "-e", r_code]
59
+
60
+ if r_args:
61
+ command.extend(r_args)
62
+
63
+ output_files: List[Path] = []
64
+ temp_dir: Optional[tempfile.TemporaryDirectory] = None
65
+ actual_working_dir: Path
66
+
67
+ try:
68
+ if working_directory:
69
+ if not working_directory.is_dir():
70
+ raise ValueError(f"Working directory '{working_directory}' does not exist or is not a directory.")
71
+ actual_working_dir = working_directory
72
+ else:
73
+ temp_dir = tempfile.TemporaryDirectory()
74
+ actual_working_dir = Path(temp_dir.name)
75
+
76
+ process = subprocess.run(
77
+ command,
78
+ cwd=actual_working_dir,
79
+ capture_output=True,
80
+ text=True,
81
+ check=True
82
+ )
83
+
84
+ # Collect output files based on provided patterns or list all if no patterns
85
+ if output_file_patterns:
86
+ for pattern in output_file_patterns:
87
+ for f in actual_working_dir.glob(pattern):
88
+ if f.is_file():
89
+ output_files.append(f)
90
+ else:
91
+ # If no patterns, collect all non-hidden files in the working directory
92
+ for f in actual_working_dir.iterdir():
93
+ if f.is_file() and not f.name.startswith("."):
94
+ output_files.append(f)
95
+
96
+ return {
97
+ "command_executed": " ".join(command),
98
+ "stdout": process.stdout,
99
+ "stderr": process.stderr,
100
+ "output_files": [str(f) for f in output_files]
101
+ }
102
+
103
+ except subprocess.CalledProcessError as e:
104
+ return {
105
+ "command_executed": " ".join(command),
106
+ "stdout": e.stdout,
107
+ "stderr": e.stderr,
108
+ "error": f"Rscript execution failed with exit code {e.returncode}",
109
+ "output_files": []
110
+ }
111
+ except FileNotFoundError:
112
+ return {
113
+ "command_executed": " ".join(command),
114
+ "stdout": "",
115
+ "stderr": "Error: Rscript command not found. Is R installed and in PATH?",
116
+ "error": "Rscript command not found",
117
+ "output_files": []
118
+ }
119
+ except ValueError as e:
120
+ return {
121
+ "command_executed": " ".join(command),
122
+ "stdout": "",
123
+ "stderr": str(e),
124
+ "error": "Input validation error",
125
+ "output_files": []
126
+ }
127
+ finally:
128
+ if temp_dir:
129
+ temp_dir.cleanup()
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/app/bioconductor-rbgl_shim_server.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/app/bioconductor-rbgl_server.py')
11
+ SERVER_NAME = 'biosci_bioconductor_rbgl'
12
+
13
+
14
+ class _ShimMCP:
15
+ @staticmethod
16
+ def tool():
17
+ def _decorator(fn):
18
+ return fn
19
+ return _decorator
20
+
21
+
22
+ def _load_functions():
23
+ code = SOURCE_SERVER.read_text(encoding="utf-8")
24
+ tree = ast.parse(code, filename=str(SOURCE_SERVER))
25
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
26
+ namespace = {
27
+ "__name__": "__mcp_source__",
28
+ "mcp": _ShimMCP(),
29
+ }
30
+ exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace)
31
+ loaded = []
32
+ for name in function_names:
33
+ fn = namespace.get(name)
34
+ if callable(fn):
35
+ loaded.append(fn)
36
+ return loaded
37
+
38
+
39
+ mcp = FastMCP(SERVER_NAME)
40
+ for _fn in _load_functions():
41
+ mcp.tool()(_fn)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ mcp.run(transport="stdio")
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-bioconductor-rbgl:
5
+ build: .
6
+ image: mcp-bioconductor-rbgl:latest
7
+ container_name: mcp-bioconductor-rbgl
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=bioconductor-rbgl
12
+ volumes:
13
+ - ./workspace:/app/workspace
14
+ - ./output:/app/output
15
+ restart: unless-stopped
16
+ healthcheck:
17
+ test: ["CMD", "python", "-c", "import sys; sys.exit(0)"]
18
+ interval: 30s
19
+ timeout: 10s
20
+ retries: 3
21
+ start_period: 5s
22
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/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-rbgl
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rbgl/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-reactomegsa.data/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-reactomegsa.data via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bioconductor-reactomegsa.data -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-reactomegsa.data_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-reactomegsa.data_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-reactomegsa.data_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-reactomegsa.data/app/bioconductor-reactomegsa.data_server.py ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ from pathlib import Path
3
+ from typing import Optional, List
4
+
5
+ @mcp.tool()
6
+ def get_citation(
7
+ rscript_path: Path = Path("Rscript"),
8
+ output_file: Optional[Path] = None,
9
+ ) -> dict:
10
+ """
11
+ Retrieves the citation information for the bioconductor-reactomegsa.data R package.
12
+
13
+ This package is a Bioconductor data package for the R environment and does not
14
+ expose direct command-line subcommands in the traditional sense. This function
15
+ wraps an Rscript call to ensure the package and its manager (BiocManager) are
16
+ installed, then loads the package, and finally extracts its citation information.
17
+
18
+ Args:
19
+ rscript_path: Path to the Rscript executable. Defaults to 'Rscript',
20
+ assuming it's in the system's PATH.
21
+ output_file: Optional path to save the citation output to a file.
22
+ If not provided, the citation will be returned in stdout.
23
+
24
+ Returns:
25
+ A dictionary containing the command executed, stdout, stderr, and
26
+ a list of any output files.
27
+ """
28
+ # Validate rscript_path
29
+ rscript_executable: str
30
+ if not rscript_path.is_absolute():
31
+ try:
32
+ # Check if 'Rscript' is in PATH
33
+ subprocess.run(["which", "Rscript"], check=True, capture_output=True)
34
+ rscript_executable = "Rscript"
35
+ except subprocess.CalledProcessError:
36
+ raise FileNotFoundError(
37
+ f"Rscript not found in system PATH. Please ensure R is installed "
38
+ "and Rscript is accessible, or provide an absolute path to Rscript."
39
+ )
40
+ elif not rscript_path.is_file():
41
+ raise FileNotFoundError(f"Rscript not found at the specified path: {rscript_path}")
42
+ else:
43
+ rscript_executable = str(rscript_path)
44
+
45
+ # R command to:
46
+ # 1. Install BiocManager if not already installed.
47
+ # 2. Install ReactomeGSA.data if not already installed (using BiocManager).
48
+ # 3. Load the ReactomeGSA.data library.
49
+ # 4. Print the citation information.
50
+ r_code = (
51
+ 'if (!require("BiocManager", quietly = TRUE)) install.packages("BiocManager"); '
52
+ 'if (!require("ReactomeGSA.data", quietly = TRUE)) BiocManager::install("ReactomeGSA.data", update = FALSE, ask = FALSE); '
53
+ 'library(ReactomeGSA.data); '
54
+ 'print(citation("ReactomeGSA.data"))'
55
+ )
56
+
57
+ command = [
58
+ rscript_executable,
59
+ "-e",
60
+ r_code
61
+ ]
62
+
63
+ stdout_capture = ""
64
+ stderr_capture = ""
65
+ output_files_list: List[str] = []
66
+
67
+ try:
68
+ process = subprocess.run(
69
+ command,
70
+ check=True,
71
+ capture_output=True,
72
+ text=True
73
+ )
74
+ stdout_capture = process.stdout
75
+ stderr_capture = process.stderr
76
+
77
+ if output_file:
78
+ output_file.parent.mkdir(parents=True, exist_ok=True)
79
+ output_file.write_text(stdout_capture)
80
+ output_files_list.append(str(output_file))
81
+
82
+ except subprocess.CalledProcessError as e:
83
+ return {
84
+ "command_executed": " ".join(command),
85
+ "stdout": e.stdout,
86
+ "stderr": e.stderr,
87
+ "output_files": [],
88
+ "error": f"Rscript execution failed with exit code {e.returncode}. Stderr: {e.stderr}"
89
+ }
90
+ except FileNotFoundError as e:
91
+ return {
92
+ "command_executed": " ".join(command),
93
+ "stdout": "",
94
+ "stderr": str(e),
95
+ "output_files": [],
96
+ "error": f"Executable not found: {e}"
97
+ }
98
+ except Exception as e:
99
+ return {
100
+ "command_executed": " ".join(command),
101
+ "stdout": stdout_capture,
102
+ "stderr": stderr_capture,
103
+ "output_files": [],
104
+ "error": f"An unexpected error occurred: {str(e)}"
105
+ }
106
+
107
+ return {
108
+ "command_executed": " ".join(command),
109
+ "stdout": stdout_capture,
110
+ "stderr": stderr_capture,
111
+ "output_files": output_files_list
112
+ }
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-reactomegsa.data/app/bioconductor-reactomegsa.data_shim_server.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-reactomegsa.data/app/bioconductor-reactomegsa.data_server.py')
11
+ SERVER_NAME = 'biosci_bioconductor_reactomegsa_data'
12
+
13
+
14
+ class _ShimMCP:
15
+ @staticmethod
16
+ def tool():
17
+ def _decorator(fn):
18
+ return fn
19
+ return _decorator
20
+
21
+
22
+ def _load_functions():
23
+ code = SOURCE_SERVER.read_text(encoding="utf-8")
24
+ tree = ast.parse(code, filename=str(SOURCE_SERVER))
25
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
26
+ namespace = {
27
+ "__name__": "__mcp_source__",
28
+ "mcp": _ShimMCP(),
29
+ }
30
+ exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace)
31
+ loaded = []
32
+ for name in function_names:
33
+ fn = namespace.get(name)
34
+ if callable(fn):
35
+ loaded.append(fn)
36
+ return loaded
37
+
38
+
39
+ mcp = FastMCP(SERVER_NAME)
40
+ for _fn in _load_functions():
41
+ mcp.tool()(_fn)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ mcp.run(transport="stdio")
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-reactomegsa.data/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-bioconductor-reactomegsa.data:
5
+ build: .
6
+ image: mcp-bioconductor-reactomegsa.data:latest
7
+ container_name: mcp-bioconductor-reactomegsa.data
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=bioconductor-reactomegsa.data
12
+ volumes:
13
+ - ./workspace:/app/workspace
14
+ - ./output:/app/output
15
+ restart: unless-stopped
16
+ healthcheck:
17
+ test: ["CMD", "python", "-c", "import sys; sys.exit(0)"]
18
+ interval: 30s
19
+ timeout: 10s
20
+ retries: 3
21
+ start_period: 5s
22
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-reactomegsa.data/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-reactomegsa.data
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-reactomegsa.data/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-regionalst/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-regionalst via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bioconductor-regionalst -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-regionalst_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-regionalst_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-regionalst_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-regionalst/app/bioconductor-regionalst_server.py ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import tempfile
3
+ import shutil
4
+ from pathlib import Path
5
+ from typing import Optional, List, Dict, Any
6
+
7
+ # MCP decorators are omitted as per the instructions, but would be present in a real MCP file.
8
+ # from mcp import tool
9
+
10
+ # --- R Script Templates ---
11
+ # These strings contain self-contained R scripts that will be executed.
12
+ # They use the 'optparse' library to accept command-line arguments.
13
+
14
+ REGIONAL_LIMMA_RSCRIPT = """
15
+ # R script to run regionalST::regional_limma
16
+ suppressPackageStartupMessages(library(optparse))
17
+ suppressPackageStartupMessages(library(regionalST))
18
+ suppressPackageStartupMessages(library(SpatialExperiment))
19
+
20
+ option_list <- list(
21
+ make_option(c("-i", "--input_rds"), type="character", help="Path to input SpatialExperiment RDS file."),
22
+ make_option(c("-o", "--output_csv"), type="character", help="Path for the output CSV file."),
23
+ make_option(c("--col_group"), type="character", help="Column name for grouping variable."),
24
+ make_option(c("--group1"), type="character", help="Name of the first group for comparison."),
25
+ make_option(c("--group2"), type="character", default=NULL, help="Name of the second group (optional)."),
26
+ make_option(c("--col_covariate"), type="character", default=NULL, help="Comma-separated column names for covariates (optional)."),
27
+ make_option(c("--n_neighbors"), type="integer", default=6, help="Number of neighbors."),
28
+ make_option(c("--log2fc_threshold"), type="double", default=0, help="Log2 fold change threshold."),
29
+ make_option(c("--pval_threshold"), type="double", default=1, help="P-value threshold."),
30
+ make_option(c("--assay_name"), type="character", default="logcounts", help="Name of the assay to use.")
31
+ )
32
+
33
+ opt_parser <- OptionParser(option_list=option_list)
34
+ opt <- parse_args(opt_parser)
35
+
36
+ if (is.null(opt$input_rds) || is.null(opt$output_csv) || is.null(opt$col_group) || is.null(opt$group1)) {
37
+ print_help(opt_parser)
38
+ stop("Missing required arguments: --input_rds, --output_csv, --col_group, --group1", call.=FALSE)
39
+ }
40
+
41
+ spe <- readRDS(opt$input_rds)
42
+
43
+ covariates <- NULL
44
+ if (!is.null(opt$col_covariate)) {
45
+ covariates <- strsplit(opt$col_covariate, ",")[[1]]
46
+ }
47
+
48
+ results <- regional_limma(
49
+ spe = spe,
50
+ col_group = opt$col_group,
51
+ col_covariate = covariates,
52
+ group1 = opt$group1,
53
+ group2 = opt$group2,
54
+ n_neighbors = opt$n_neighbors,
55
+ log2fc_threshold = opt$log2fc_threshold,
56
+ pval_threshold = opt$pval_threshold,
57
+ assay_name = opt$assay_name
58
+ )
59
+
60
+ write.csv(as.data.frame(results), file = opt$output_csv, row.names = FALSE)
61
+
62
+ cat("regional_limma analysis complete. Results saved to", opt$output_csv, "\\n")
63
+ """
64
+
65
+ REGIONAL_VOOM_RSCRIPT = """
66
+ # R script to run regionalST::regional_voom
67
+ suppressPackageStartupMessages(library(optparse))
68
+ suppressPackageStartupMessages(library(regionalST))
69
+ suppressPackageStartupMessages(library(SpatialExperiment))
70
+
71
+ option_list <- list(
72
+ make_option(c("-i", "--input_rds"), type="character", help="Path to input SpatialExperiment RDS file."),
73
+ make_option(c("-o", "--output_csv"), type="character", help="Path for the output CSV file."),
74
+ make_option(c("--col_group"), type="character", help="Column name for grouping variable."),
75
+ make_option(c("--group1"), type="character", help="Name of the first group for comparison."),
76
+ make_option(c("--group2"), type="character", default=NULL, help="Name of the second group (optional)."),
77
+ make_option(c("--col_covariate"), type="character", default=NULL, help="Comma-separated column names for covariates (optional)."),
78
+ make_option(c("--n_neighbors"), type="integer", default=6, help="Number of neighbors."),
79
+ make_option(c("--log2fc_threshold"), type="double", default=0, help="Log2 fold change threshold."),
80
+ make_option(c("--pval_threshold"), type="double", default=1, help="P-value threshold."),
81
+ make_option(c("--assay_name"), type="character", default="counts", help="Name of the assay to use.")
82
+ )
83
+
84
+ opt_parser <- OptionParser(option_list=option_list)
85
+ opt <- parse_args(opt_parser)
86
+
87
+ if (is.null(opt$input_rds) || is.null(opt$output_csv) || is.null(opt$col_group) || is.null(opt$group1)) {
88
+ print_help(opt_parser)
89
+ stop("Missing required arguments: --input_rds, --output_csv, --col_group, --group1", call.=FALSE)
90
+ }
91
+
92
+ spe <- readRDS(opt$input_rds)
93
+
94
+ covariates <- NULL
95
+ if (!is.null(opt$col_covariate)) {
96
+ covariates <- strsplit(opt$col_covariate, ",")[[1]]
97
+ }
98
+
99
+ results <- regional_voom(
100
+ spe = spe,
101
+ col_group = opt$col_group,
102
+ col_covariate = covariates,
103
+ group1 = opt$group1,
104
+ group2 = opt$group2,
105
+ n_neighbors = opt$n_neighbors,
106
+ log2fc_threshold = opt$log2fc_threshold,
107
+ pval_threshold = opt$pval_threshold,
108
+ assay_name = opt$assay_name
109
+ )
110
+
111
+ write.csv(as.data.frame(results), file = opt$output_csv, row.names = FALSE)
112
+
113
+ cat("regional_voom analysis complete. Results saved to", opt$output_csv, "\\n")
114
+ """
115
+
116
+ REGIONAL_NONPARAMETRIC_RSCRIPT_TEMPLATE = """
117
+ # R script to run regionalST non-parametric tests
118
+ suppressPackageStartupMessages(library(optparse))
119
+ suppressPackageStartupMessages(library(regionalST))
120
+ suppressPackageStartupMessages(library(SpatialExperiment))
121
+
122
+ option_list <- list(
123
+ make_option(c("-i", "--input_rds"), type="character", help="Path to input SpatialExperiment RDS file."),
124
+ make_option(c("-o", "--output_csv"), type="character", help="Path for the output CSV file."),
125
+ make_option(c("--col_group"), type="character", help="Column name for grouping variable."),
126
+ make_option(c("--group1"), type="character", help="Name of the first group for comparison."),
127
+ make_option(c("--group2"), type="character", default=NULL, help="Name of the second group (optional)."),
128
+ make_option(c("--n_neighbors"), type="integer", default=6, help="Number of neighbors."),
129
+ make_option(c("--log2fc_threshold"), type="double", default=0, help="Log2 fold change threshold."),
130
+ make_option(c("--pval_threshold"), type="double", default=1, help="P-value threshold."),
131
+ make_option(c("--assay_name"), type="character", default="logcounts", help="Name of the assay to use."),
132
+ make_option(c("--test_function"), type="character", help="The R function to call (e.g., 'regional_wilcox').")
133
+ )
134
+
135
+ opt_parser <- OptionParser(option_list=option_list)
136
+ opt <- parse_args(opt_parser)
137
+
138
+ if (is.null(opt$input_rds) || is.null(opt$output_csv) || is.null(opt$col_group) || is.null(opt$group1) || is.null(opt$test_function)) {
139
+ print_help(opt_parser)
140
+ stop("Missing required arguments: --input_rds, --output_csv, --col_group, --group1, --test_function", call.=FALSE)
141
+ }
142
+
143
+ spe <- readRDS(opt$input_rds)
144
+
145
+ # Dynamically get the function from the regionalST package
146
+ test_func <- get(opt$test_function, asNamespace("regionalST"))
147
+
148
+ results <- test_func(
149
+ spe = spe,
150
+ col_group = opt$col_group,
151
+ group1 = opt$group1,
152
+ group2 = opt$group2,
153
+ n_neighbors = opt$n_neighbors,
154
+ log2fc_threshold = opt$log2fc_threshold,
155
+ pval_threshold = opt$pval_threshold,
156
+ assay_name = opt$assay_name
157
+ )
158
+
159
+ write.csv(as.data.frame(results), file = opt$output_csv, row.names = FALSE)
160
+
161
+ cat(paste(opt$test_function, "analysis complete. Results saved to", opt$output_csv, "\\n"))
162
+ """
163
+
164
+ def _run_regionalst_script(
165
+ script_content: str,
166
+ cmd_args: List[str],
167
+ output_filename: str
168
+ ) -> Dict[str, Any]:
169
+ """
170
+ Internal helper to execute a regionalST R script.
171
+
172
+ This function sets up a temporary environment, writes the provided R script
173
+ to a file, executes it with Rscript, and captures the output. It is not
174
+ intended to be an MCP tool itself.
175
+
176
+ Args:
177
+ script_content: A string containing the R script to execute.
178
+ cmd_args: A list of command-line arguments for the R script.
179
+ output_filename: The name of the output file to be generated.
180
+
181
+ Returns:
182
+ A dictionary containing execution details and output file paths.
183
+ """
184
+ if not shutil.which("Rscript"):
185
+ raise RuntimeError(
186
+ "Rscript executable not found in system PATH. "
187
+ "Please install R and ensure Rscript is accessible."
188
+ )
189
+
190
+ with tempfile.TemporaryDirectory() as temp_dir:
191
+ temp_path = Path(temp_dir)
192
+ r_script_path = temp_path / "run_script.R"
193
+ output_csv_path = temp_path / output_filename
194
+
195
+ r_script_path.write_text(script_content)
196
+
197
+ command = [
198
+ "Rscript", str(r_script_path),
199
+ *cmd_args,
200
+ "--output_csv", str(output_csv_path)
201
+ ]
202
+ command_str = " ".join(command)
203
+
204
+ try:
205
+ result = subprocess.run(
206
+ command,
207
+ capture_output=True,
208
+ text=True,
209
+ check=True,
210
+ cwd=temp_path,
211
+ )
212
+ return {
213
+ "command_executed": command_str,
214
+ "stdout": result.stdout,
215
+ "stderr": result.stderr,
216
+ "output_files": {"results_csv": str(output_csv_path)}
217
+ }
218
+ except subprocess.CalledProcessError as e:
219
+ error_message = (
220
+ f"R script execution failed with return code {e.returncode}.\n"
221
+ f"STDOUT:\n{e.stdout}\n"
222
+ f"STDERR:\n{e.stderr}"
223
+ )
224
+ raise RuntimeError(error_message) from e
225
+
226
+ # @mcp.tool()
227
+ def regional_limma(
228
+ input_rds: Path,
229
+ col_group: str,
230
+ group1: str,
231
+ group2: Optional[str] = None,
232
+ col_covariate: Optional[List[str]] = None,
233
+ n_neighbors: int = 6,
234
+ log2fc_threshold: float = 0.0,
235
+ pval_threshold: float = 1.0,
236
+ assay_name: str = "logcounts",
237
+ ) -> Dict[str, Any]:
238
+ """
239
+ Performs regional differential expression analysis using limma.
240
+
241
+ This function wraps `regional_limma` from the R package `regionalST`, suitable
242
+ for analyzing microarray data or transformed RNA-seq data (e.g., log-CPM).
243
+ It requires R, Rscript, and the Bioconductor packages `regionalST`,
244
+ `SpatialExperiment`, and `optparse` to be installed.
245
+
246
+ Args:
247
+ input_rds: Path to the input SpatialExperiment object saved as an RDS file.
248
+ col_group: The column name in `colData` that defines the groups to compare.
249
+ group1: The name of the first group for comparison.
250
+ group2: The name of the second group. If not provided, performs a one-vs-all comparison.
251
+ col_covariate: List of column names in `colData` to use as covariates.
252
+ n_neighbors: The number of nearest neighbors to consider for each spot.
253
+ log2fc_threshold: The log2 fold change threshold for determining significance.
254
+ pval_threshold: The p-value threshold for determining significance.
255
+ assay_name: The name of the assay in the SpatialExperiment object to use.
256
+
257
+ Returns:
258
+ A dictionary with the command, stdout, stderr, and output CSV file path.
259
+ """
260
+ if not input_rds.is_file():
261
+ raise FileNotFoundError(f"Input file not found: {input_rds}")
262
+ if n_neighbors <= 0:
263
+ raise ValueError("n_neighbors must be a positive integer.")
264
+ if not (0.0 <= pval_threshold <= 1.0):
265
+ raise ValueError("pval_threshold must be between 0.0 and 1.0.")
266
+
267
+ cmd_args = [
268
+ "--input_rds", str(input_rds),
269
+ "--col_group", col_group,
270
+ "--group1", group1,
271
+ "--n_neighbors", str(n_neighbors),
272
+ "--log2fc_threshold", str(log2fc_threshold),
273
+ "--pval_threshold", str(pval_threshold),
274
+ "--assay_name", assay_name,
275
+ ]
276
+ if group2:
277
+ cmd_args.extend(["--group2", group2])
278
+ if col_covariate:
279
+ cmd_args.extend(["--col_covariate", ",".join(col_covariate)])
280
+
281
+ return _run_regionalst_script(
282
+ script_content=REGIONAL_LIMMA_RSCRIPT,
283
+ cmd_args=cmd_args,
284
+ output_filename="regional_limma_results.csv"
285
+ )
286
+
287
+ # @mcp.tool()
288
+ def regional_voom(
289
+ input_rds: Path,
290
+ col_group: str,
291
+ group1: str,
292
+ group2: Optional[str] = None,
293
+ col_covariate: Optional[List[str]] = None,
294
+ n_neighbors: int = 6,
295
+ log2fc_threshold: float = 0.0,
296
+ pval_threshold: float = 1.0,
297
+ assay_name: str = "counts",
298
+ ) -> Dict[str, Any]:
299
+ """
300
+ Performs regional differential expression analysis using voom.
301
+
302
+ This function wraps `regional_voom` from `regionalST`, suitable for RNA-seq
303
+ count data. It requires R, Rscript, and the Bioconductor packages `regionalST`,
304
+ `SpatialExperiment`, and `optparse` to be installed.
305
+
306
+ Args:
307
+ input_rds: Path to the input SpatialExperiment object saved as an RDS file.
308
+ col_group: The column name in `colData` that defines the groups to compare.
309
+ group1: The name of the first group for comparison.
310
+ group2: The name of the second group. If not provided, performs a one-vs-all comparison.
311
+ col_covariate: List of column names in `colData` to use as covariates.
312
+ n_neighbors: The number of nearest neighbors to consider for each spot.
313
+ log2fc_threshold: The log2 fold change threshold for determining significance.
314
+ pval_threshold: The p-value threshold for determining significance.
315
+ assay_name: The name of the assay containing raw counts.
316
+
317
+ Returns:
318
+ A dictionary with the command, stdout, stderr, and output CSV file path.
319
+ """
320
+ if not input_rds.is_file():
321
+ raise FileNotFoundError(f"Input file not found: {input_rds}")
322
+ if n_neighbors <= 0:
323
+ raise ValueError("n_neighbors must be a positive integer.")
324
+ if not (0.0 <= pval_threshold <= 1.0):
325
+ raise ValueError("pval_threshold must be between 0.0 and 1.0.")
326
+
327
+ cmd_args = [
328
+ "--input_rds", str(input_rds),
329
+ "--col_group", col_group,
330
+ "--group1", group1,
331
+ "--n_neighbors", str(n_neighbors),
332
+ "--log2fc_threshold", str(log2fc_threshold),
333
+ "--pval_threshold", str(pval_threshold),
334
+ "--assay_name", assay_name,
335
+ ]
336
+ if group2:
337
+ cmd_args.extend(["--group2", group2])
338
+ if col_covariate:
339
+ cmd_args.extend(["--col_covariate", ",".join(col_covariate)])
340
+
341
+ return _run_regionalst_script(
342
+ script_content=REGIONAL_VOOM_RSCRIPT,
343
+ cmd_args=cmd_args,
344
+ output_filename="regional_voom_results.csv"
345
+ )
346
+
347
+ # @mcp.tool()
348
+ def regional_wilcox(
349
+ input_rds: Path,
350
+ col_group: str,
351
+ group1: str,
352
+ group2: Optional[str] = None,
353
+ n_neighbors: int = 6,
354
+ log2fc_threshold: float = 0.0,
355
+ pval_threshold: float = 1.0,
356
+ assay_name: str = "logcounts",
357
+ ) -> Dict[str, Any]:
358
+ """
359
+ Performs regional DE analysis using the Wilcoxon rank-sum test.
360
+
361
+ This function wraps `regional_wilcox` from `regionalST`, a non-parametric test.
362
+ It requires R, Rscript, and the Bioconductor packages `regionalST`,
363
+ `SpatialExperiment`, and `optparse` to be installed.
364
+
365
+ Args:
366
+ input_rds: Path to the input SpatialExperiment object saved as an RDS file.
367
+ col_group: The column name in `colData` that defines the groups to compare.
368
+ group1: The name of the first group for comparison.
369
+ group2: The name of the second group. If not provided, performs a one-vs-all comparison.
370
+ n_neighbors: The number of nearest neighbors to consider for each spot.
371
+ log2fc_threshold: The log2 fold change threshold for determining significance.
372
+ pval_threshold: The p-value threshold for determining significance.
373
+ assay_name: The name of the assay to use for analysis.
374
+
375
+ Returns:
376
+ A dictionary with the command, stdout, stderr, and output CSV file path.
377
+ """
378
+ if not input_rds.is_file():
379
+ raise FileNotFoundError(f"Input file not found: {input_rds}")
380
+ if n_neighbors <= 0:
381
+ raise ValueError("n_neighbors must be a positive integer.")
382
+ if not (0.0 <= pval_threshold <= 1.0):
383
+ raise ValueError("pval_threshold must be between 0.0 and 1.0.")
384
+
385
+ cmd_args = [
386
+ "--input_rds", str(input_rds),
387
+ "--col_group", col_group,
388
+ "--group1", group1,
389
+ "--n_neighbors", str(n_neighbors),
390
+ "--log2fc_threshold", str(log2fc_threshold),
391
+ "--pval_threshold", str(pval_threshold),
392
+ "--assay_name", assay_name,
393
+ "--test_function", "regional_wilcox",
394
+ ]
395
+ if group2:
396
+ cmd_args.extend(["--group2", group2])
397
+
398
+ return _run_regionalst_script(
399
+ script_content=REGIONAL_NONPARAMETRIC_RSCRIPT_TEMPLATE,
400
+ cmd_args=cmd_args,
401
+ output_filename="regional_wilcox_results.csv"
402
+ )
403
+
404
+ # @mcp.tool()
405
+ def regional_ttest(
406
+ input_rds: Path,
407
+ col_group: str,
408
+ group1: str,
409
+ group2: Optional[str] = None,
410
+ n_neighbors: int = 6,
411
+ log2fc_threshold: float = 0.0,
412
+ pval_threshold: float = 1.0,
413
+ assay_name: str = "logcounts",
414
+ ) -> Dict[str, Any]:
415
+ """
416
+ Performs regional differential expression analysis using a t-test.
417
+
418
+ This function wraps `regional_ttest` from `regionalST`, a parametric test.
419
+ It requires R, Rscript, and the Bioconductor packages `regionalST`,
420
+ `SpatialExperiment`, and `optparse` to be installed.
421
+
422
+ Args:
423
+ input_rds: Path to the input SpatialExperiment object saved as an RDS file.
424
+ col_group: The column name in `colData` that defines the groups to compare.
425
+ group1: The name of the first group for comparison.
426
+ group2: The name of the second group. If not provided, performs a one-vs-all comparison.
427
+ n_neighbors: The number of nearest neighbors to consider for each spot.
428
+ log2fc_threshold: The log2 fold change threshold for determining significance.
429
+ pval_threshold: The p-value threshold for determining significance.
430
+ assay_name: The name of the assay to use for analysis.
431
+
432
+ Returns:
433
+ A dictionary with the command, stdout, stderr, and output CSV file path.
434
+ """
435
+ if not input_rds.is_file():
436
+ raise FileNotFoundError(f"Input file not found: {input_rds}")
437
+ if n_neighbors <= 0:
438
+ raise ValueError("n_neighbors must be a positive integer.")
439
+ if not (0.0 <= pval_threshold <= 1.0):
440
+ raise ValueError("pval_threshold must be between 0.0 and 1.0.")
441
+
442
+ cmd_args = [
443
+ "--input_rds", str(input_rds),
444
+ "--col_group", col_group,
445
+ "--group1", group1,
446
+ "--n_neighbors", str(n_neighbors),
447
+ "--log2fc_threshold", str(log2fc_threshold),
448
+ "--pval_threshold", str(pval_threshold),
449
+ "--assay_name", assay_name,
450
+ "--test_function", "regional_ttest",
451
+ ]
452
+ if group2:
453
+ cmd_args.extend(["--group2", group2])
454
+
455
+ return _run_regionalst_script(
456
+ script_content=REGIONAL_NONPARAMETRIC_RSCRIPT_TEMPLATE,
457
+ cmd_args=cmd_args,
458
+ output_filename="regional_ttest_results.csv"
459
+ )
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-regionalst/app/bioconductor-regionalst_shim_server.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-regionalst/app/bioconductor-regionalst_server.py')
11
+ SERVER_NAME = 'biosci_bioconductor_regionalst'
12
+
13
+
14
+ class _ShimMCP:
15
+ @staticmethod
16
+ def tool():
17
+ def _decorator(fn):
18
+ return fn
19
+ return _decorator
20
+
21
+
22
+ def _load_functions():
23
+ code = SOURCE_SERVER.read_text(encoding="utf-8")
24
+ tree = ast.parse(code, filename=str(SOURCE_SERVER))
25
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
26
+ namespace = {
27
+ "__name__": "__mcp_source__",
28
+ "mcp": _ShimMCP(),
29
+ }
30
+ exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace)
31
+ loaded = []
32
+ for name in function_names:
33
+ fn = namespace.get(name)
34
+ if callable(fn):
35
+ loaded.append(fn)
36
+ return loaded
37
+
38
+
39
+ mcp = FastMCP(SERVER_NAME)
40
+ for _fn in _load_functions():
41
+ mcp.tool()(_fn)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ mcp.run(transport="stdio")
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-regionalst/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-bioconductor-regionalst:
5
+ build: .
6
+ image: mcp-bioconductor-regionalst:latest
7
+ container_name: mcp-bioconductor-regionalst
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=bioconductor-regionalst
12
+ volumes:
13
+ - ./workspace:/app/workspace
14
+ - ./output:/app/output
15
+ restart: unless-stopped
16
+ healthcheck:
17
+ test: ["CMD", "python", "-c", "import sys; sys.exit(0)"]
18
+ interval: 30s
19
+ timeout: 10s
20
+ retries: 3
21
+ start_period: 5s
22
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-regionalst/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-regionalst
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-regionalst/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/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-rgraphviz via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bioconductor-rgraphviz -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-rgraphviz_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-rgraphviz_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-rgraphviz_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/app/bioconductor-rgraphviz_server.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import tempfile
3
+ import textwrap
4
+ from pathlib import Path
5
+ from typing import Dict, List, Optional
6
+
7
+ # In a real MCP environment, this would be imported.
8
+ # from mcp import tool as mcp_tool
9
+ # For the purpose of this exercise, we define a placeholder.
10
+ class mcp:
11
+ @staticmethod
12
+ def tool(func=None, **kwargs):
13
+ if func:
14
+ return func
15
+ return lambda f: f
16
+
17
+ @mcp.tool
18
+ def plot_graph(
19
+ graph_file: Path,
20
+ output_file: Path,
21
+ layout_engine: str = "dot",
22
+ output_format: str = "png",
23
+ graph_attributes: Optional[str] = None,
24
+ node_attributes: Optional[str] = None,
25
+ edge_attributes: Optional[str] = None,
26
+ ) -> Dict:
27
+ """
28
+ Generates a graph visualization using the Rgraphviz library.
29
+
30
+ This tool takes a graph defined in a simple edge list format (CSV with 'from'
31
+ and 'to' headers) and uses Rgraphviz to create a visual representation,
32
+ saving it to a specified output file.
33
+
34
+ Args:
35
+ graph_file: Path to the input graph file. Must be a CSV with 'from' and 'to' columns.
36
+ output_file: Path to save the output image file.
37
+ layout_engine: The Graphviz layout algorithm to use.
38
+ Valid options: 'dot', 'neato', 'twopi', 'circo', 'fdp'.
39
+ output_format: The format of the output image.
40
+ Valid options: 'png', 'pdf', 'svg', 'jpg'.
41
+ graph_attributes: Semicolon-separated key-value pairs for global graph attributes
42
+ (e.g., "rankdir=LR;bgcolor=lightblue;").
43
+ node_attributes: Semicolon-separated key-value pairs for global node attributes
44
+ (e.g., "shape=ellipse;color=blue;").
45
+ edge_attributes: Semicolon-separated key-value pairs for global edge attributes
46
+ (e.g., "color=red;").
47
+
48
+ Returns:
49
+ A dictionary containing the execution command, stdout, stderr, and a list of output files.
50
+ """
51
+ # 1. Input Validation
52
+ if not graph_file.is_file():
53
+ raise FileNotFoundError(f"Input graph file not found: {graph_file}")
54
+
55
+ allowed_layouts = ["dot", "neato", "twopi", "circo", "fdp"]
56
+ if layout_engine not in allowed_layouts:
57
+ raise ValueError(f"Invalid layout_engine '{layout_engine}'. Must be one of {allowed_layouts}.")
58
+
59
+ allowed_formats = ["png", "pdf", "svg", "jpg"]
60
+ if output_format not in allowed_formats:
61
+ raise ValueError(f"Invalid output_format '{output_format}'. Must be one of {allowed_formats}.")
62
+
63
+ if not output_file.parent.exists():
64
+ output_file.parent.mkdir(parents=True, exist_ok=True)
65
+
66
+ # 2. R Script Generation
67
+ r_script_content = textwrap.dedent("""
68
+ # Load required libraries
69
+ # Suppress startup messages for cleaner output
70
+ suppressPackageStartupMessages(library(graph))
71
+ suppressPackageStartupMessages(library(Rgraphviz))
72
+
73
+ # Get command line arguments
74
+ args <- commandArgs(trailingOnly = TRUE)
75
+ if (length(args) < 4) {
76
+ stop("Usage: Rscript plot_script.R <input_csv> <output_file> <layout_engine> <output_format> [graph_attrs] [node_attrs] [edge_attrs]", call. = FALSE)
77
+ }
78
+
79
+ inputFile <- args[1]
80
+ outputFile <- args[2]
81
+ layoutEngine <- args[3]
82
+ outputFormat <- args[4]
83
+
84
+ # Read the edge list
85
+ edge_df <- read.csv(inputFile, header = TRUE, stringsAsFactors = FALSE)
86
+
87
+ # Check for correct columns
88
+ if (!all(c("from", "to") %in% names(edge_df))) {
89
+ stop("Input CSV must have 'from' and 'to' columns.", call. = FALSE)
90
+ }
91
+
92
+ # Create a graphNEL object from the edge list
93
+ g <- ftM2graphNEL(as.matrix(edge_df), edgemode = "directed")
94
+
95
+ # Helper function to parse attribute strings like "key1=val1;key2=val2"
96
+ parse_attrs <- function(attr_string) {
97
+ if (is.na(attr_string) || nchar(attr_string) == 0) {
98
+ return(list())
99
+ }
100
+ # Split by semicolon, but not if it's inside quotes
101
+ pairs <- strsplit(attr_string, ";(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)", perl=TRUE)[[1]]
102
+ attrs <- list()
103
+ for (pair in pairs) {
104
+ if (grepl("=", pair)) {
105
+ kv <- strsplit(pair, "=")[[1]]
106
+ key <- trimws(kv[1])
107
+ value <- trimws(kv[2])
108
+ # Try to convert to numeric if possible, otherwise keep as string
109
+ if (!is.na(suppressWarnings(as.numeric(value)))) {
110
+ attrs[[key]] <- as.numeric(value)
111
+ } else {
112
+ # Remove quotes if they exist
113
+ attrs[[key]] <- gsub('^"|"$', '', value)
114
+ }
115
+ }
116
+ }
117
+ return(attrs)
118
+ }
119
+
120
+ graphAttrs <- if (length(args) >= 5) parse_attrs(args[5]) else list()
121
+ nodeAttrs <- if (length(args) >= 6) parse_attrs(args[6]) else list()
122
+ edgeAttrs <- if (length(args) >= 7) parse_attrs(args[7]) else list()
123
+
124
+ # Open the correct graphics device based on output format
125
+ if (outputFormat == "png") {
126
+ png(outputFile, width=1024, height=768, res=100)
127
+ } else if (outputFormat == "pdf") {
128
+ pdf(outputFile)
129
+ } else if (outputFormat == "svg") {
130
+ svg(outputFile)
131
+ } else if (outputFormat == "jpg") {
132
+ jpeg(outputFile, width=1024, height=768, res=100)
133
+ } else {
134
+ stop(paste("Unsupported output format:", outputFormat), call. = FALSE)
135
+ }
136
+
137
+ # Plot the graph with specified attributes
138
+ plot(g, layoutEngine, attrs=list(graph=graphAttrs, node=nodeAttrs, edge=edgeAttrs))
139
+
140
+ # Close the device
141
+ dev.off()
142
+
143
+ cat(paste("Graph successfully plotted to", outputFile, "\\n"))
144
+ """)
145
+
146
+ # 3. Subprocess Execution
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 = Path(r_script_file.name)
150
+
151
+ cmd = [
152
+ "Rscript",
153
+ str(r_script_path),
154
+ str(graph_file),
155
+ str(output_file),
156
+ layout_engine,
157
+ output_format,
158
+ ]
159
+
160
+ # Add optional attributes to the command if they are provided
161
+ # Pass them as single arguments to prevent shell interpretation issues
162
+ cmd.append(graph_attributes if graph_attributes else "")
163
+ cmd.append(node_attributes if node_attributes else "")
164
+ cmd.append(edge_attributes if edge_attributes else "")
165
+
166
+ command_executed = " ".join(f'"{arg}"' if ' ' in arg else arg for arg in cmd)
167
+
168
+ try:
169
+ result = subprocess.run(
170
+ cmd,
171
+ capture_output=True,
172
+ text=True,
173
+ check=True,
174
+ encoding='utf-8'
175
+ )
176
+ stdout = result.stdout
177
+ stderr = result.stderr
178
+ output_files = [str(output_file)] if output_file.exists() else []
179
+
180
+ except FileNotFoundError:
181
+ return {
182
+ "command_executed": command_executed,
183
+ "stdout": "",
184
+ "stderr": "Error: Rscript not found. Please ensure R is installed and in your PATH.",
185
+ "output_files": []
186
+ }
187
+ except subprocess.CalledProcessError as e:
188
+ return {
189
+ "command_executed": command_executed,
190
+ "stdout": e.stdout,
191
+ "stderr": e.stderr,
192
+ "output_files": []
193
+ }
194
+ finally:
195
+ # Clean up the temporary R script
196
+ if r_script_path.exists():
197
+ r_script_path.unlink()
198
+
199
+ return {
200
+ "command_executed": command_executed,
201
+ "stdout": stdout,
202
+ "stderr": stderr,
203
+ "output_files": output_files,
204
+ }
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/app/bioconductor-rgraphviz_shim_server.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/app/bioconductor-rgraphviz_server.py')
11
+ SERVER_NAME = 'biosci_bioconductor_rgraphviz'
12
+
13
+
14
+ class _ShimMCP:
15
+ @staticmethod
16
+ def tool():
17
+ def _decorator(fn):
18
+ return fn
19
+ return _decorator
20
+
21
+
22
+ def _load_functions():
23
+ code = SOURCE_SERVER.read_text(encoding="utf-8")
24
+ tree = ast.parse(code, filename=str(SOURCE_SERVER))
25
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
26
+ namespace = {
27
+ "__name__": "__mcp_source__",
28
+ "mcp": _ShimMCP(),
29
+ }
30
+ exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace)
31
+ loaded = []
32
+ for name in function_names:
33
+ fn = namespace.get(name)
34
+ if callable(fn):
35
+ loaded.append(fn)
36
+ return loaded
37
+
38
+
39
+ mcp = FastMCP(SERVER_NAME)
40
+ for _fn in _load_functions():
41
+ mcp.tool()(_fn)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ mcp.run(transport="stdio")
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-bioconductor-rgraphviz:
5
+ build: .
6
+ image: mcp-bioconductor-rgraphviz:latest
7
+ container_name: mcp-bioconductor-rgraphviz
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=bioconductor-rgraphviz
12
+ volumes:
13
+ - ./workspace:/app/workspace
14
+ - ./output:/app/output
15
+ restart: unless-stopped
16
+ healthcheck:
17
+ test: ["CMD", "python", "-c", "import sys; sys.exit(0)"]
18
+ interval: 30s
19
+ timeout: 10s
20
+ retries: 3
21
+ start_period: 5s
22
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/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-rgraphviz
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rgraphviz/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/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-rhdf5 via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bioconductor-rhdf5 -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-rhdf5_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-rhdf5_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-rhdf5_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/app/bioconductor-rhdf5_server.py ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ from pathlib import Path
3
+ from typing import Optional, List, Dict, Any
4
+
5
+ # This is a placeholder for the MCP decorator.
6
+ # In a real MCP environment, this would be provided by the MCP framework.
7
+ def tool(*args, **kwargs):
8
+ def decorator(func):
9
+ return func
10
+ return decorator
11
+
12
+ mcp = type("mcp", (), {"tool": tool})
13
+
14
+
15
+ @mcp.tool()
16
+ def execute_rhdf5_script(
17
+ script_file: Optional[Path] = None,
18
+ expression: Optional[str] = None,
19
+ script_args: Optional[List[str]] = None,
20
+ verbose: bool = False,
21
+ default_packages: Optional[str] = None,
22
+ vanilla: bool = False,
23
+ save: bool = False,
24
+ no_environ: bool = False,
25
+ no_site_file: bool = False,
26
+ no_init_file: bool = False,
27
+ restore: bool = False,
28
+ ) -> Dict[str, Any]:
29
+ """
30
+ Executes an R script using Rscript in an environment with bioconductor-rhdf5.
31
+
32
+ This tool serves as a wrapper for the Rscript executable, allowing you to run
33
+ R code that utilizes the rhdf5 library for interacting with HDF5 files.
34
+ You must provide either an R script file (`script_file`) or a string
35
+ containing an R expression (`expression`).
36
+
37
+ Args:
38
+ script_file: Path to the R script file to be executed.
39
+ expression: An R expression to be executed. Use instead of 'script_file'.
40
+ script_args: A list of arguments to be passed to the R script.
41
+ verbose: If True, enables verbose output from Rscript.
42
+ default_packages: A comma-separated list of packages to be loaded by default.
43
+ vanilla: Combines --no-save, --no-restore, --no-site-file, --no-init-file,
44
+ and --no-environ. A best practice for clean, reproducible runs.
45
+ save: If True, the workspace is saved at the end of the session.
46
+ no_environ: If True, site and user environment files are not read.
47
+ no_site_file: If True, the site-wide Rprofile is not read.
48
+ no_init_file: If True, the user's R profile is not read.
49
+ restore: If True, previously saved objects are restored at startup.
50
+
51
+ Returns:
52
+ A dictionary containing the execution details, including the command,
53
+ stdout, stderr, and a list of output files (if any were generated).
54
+ """
55
+ # --- Input Validation ---
56
+ if not (script_file or expression):
57
+ raise ValueError("Either 'script_file' or 'expression' must be provided.")
58
+ if script_file and expression:
59
+ raise ValueError("'script_file' and 'expression' are mutually exclusive and cannot be used together.")
60
+ if script_file:
61
+ if not script_file.is_file():
62
+ raise FileNotFoundError(f"The specified script file does not exist: {script_file}")
63
+
64
+ # --- Command Construction ---
65
+ cmd = ["Rscript"]
66
+
67
+ if verbose:
68
+ cmd.append("--verbose")
69
+ if default_packages:
70
+ cmd.extend(["--default-packages", default_packages])
71
+
72
+ if vanilla:
73
+ cmd.append("--vanilla")
74
+ else:
75
+ if save:
76
+ cmd.append("--save")
77
+ if no_environ:
78
+ cmd.append("--no-environ")
79
+ if no_site_file:
80
+ cmd.append("--no-site-file")
81
+ if no_init_file:
82
+ cmd.append("--no-init-file")
83
+ if restore:
84
+ cmd.append("--restore")
85
+
86
+ if expression:
87
+ cmd.extend(["-e", expression])
88
+ elif script_file:
89
+ cmd.append(str(script_file))
90
+
91
+ if script_args:
92
+ cmd.extend(script_args)
93
+
94
+ command_executed = " ".join(cmd)
95
+
96
+ # --- Subprocess Execution ---
97
+ try:
98
+ result = subprocess.run(
99
+ cmd,
100
+ capture_output=True,
101
+ text=True,
102
+ check=True,
103
+ )
104
+ stdout = result.stdout
105
+ stderr = result.stderr
106
+ except FileNotFoundError:
107
+ # This error occurs if 'Rscript' is not in the system's PATH
108
+ return {
109
+ "error": "Rscript executable not found. Please ensure R is installed and accessible in the environment's PATH.",
110
+ "command_executed": command_executed,
111
+ "stdout": "",
112
+ "stderr": "",
113
+ }
114
+ except subprocess.CalledProcessError as e:
115
+ # This error occurs if the R script returns a non-zero exit code
116
+ return {
117
+ "error": f"R script execution failed with return code {e.returncode}.",
118
+ "command_executed": command_executed,
119
+ "stdout": e.stdout,
120
+ "stderr": e.stderr,
121
+ "return_code": e.returncode,
122
+ }
123
+
124
+ # --- Structured Result Return ---
125
+ # Since this tool runs a generic script, it cannot know what files will be
126
+ # created. The user is responsible for knowing the outputs of their script.
127
+ return {
128
+ "command_executed": command_executed,
129
+ "stdout": stdout,
130
+ "stderr": stderr,
131
+ "output_files": [],
132
+ }
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/app/bioconductor-rhdf5_shim_server.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/app/bioconductor-rhdf5_server.py')
11
+ SERVER_NAME = 'biosci_bioconductor_rhdf5'
12
+
13
+
14
+ class _ShimMCP:
15
+ @staticmethod
16
+ def tool():
17
+ def _decorator(fn):
18
+ return fn
19
+ return _decorator
20
+
21
+
22
+ def _load_functions():
23
+ code = SOURCE_SERVER.read_text(encoding="utf-8")
24
+ tree = ast.parse(code, filename=str(SOURCE_SERVER))
25
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
26
+ namespace = {
27
+ "__name__": "__mcp_source__",
28
+ "mcp": _ShimMCP(),
29
+ }
30
+ exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace)
31
+ loaded = []
32
+ for name in function_names:
33
+ fn = namespace.get(name)
34
+ if callable(fn):
35
+ loaded.append(fn)
36
+ return loaded
37
+
38
+
39
+ mcp = FastMCP(SERVER_NAME)
40
+ for _fn in _load_functions():
41
+ mcp.tool()(_fn)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ mcp.run(transport="stdio")
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-bioconductor-rhdf5:
5
+ build: .
6
+ image: mcp-bioconductor-rhdf5:latest
7
+ container_name: mcp-bioconductor-rhdf5
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=bioconductor-rhdf5
12
+ volumes:
13
+ - ./workspace:/app/workspace
14
+ - ./output:/app/output
15
+ restart: unless-stopped
16
+ healthcheck:
17
+ test: ["CMD", "python", "-c", "import sys; sys.exit(0)"]
18
+ interval: 30s
19
+ timeout: 10s
20
+ retries: 3
21
+ start_period: 5s
22
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/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-rhdf5
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5filters/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-rhdf5filters via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bioconductor-rhdf5filters -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-rhdf5filters_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-rhdf5filters_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-rhdf5filters_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5filters/app/bioconductor-rhdf5filters_server.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import tempfile
3
+ import shutil
4
+ from pathlib import Path
5
+ from typing import Dict, Any, List
6
+
7
+ # MCP decorator is commented out as per instructions
8
+ # @mcp.tool()
9
+ def check_installation() -> Dict[str, Any]:
10
+ """
11
+ Verifies the installation of the bioconductor-rhdf5filters R library.
12
+
13
+ bioconductor-rhdf5filters is an R library that provides HDF5 compression
14
+ filters and does not have a direct command-line interface. This function
15
+ executes a simple R script to confirm that the library is installed and
16
+ can be loaded in the R environment, and it reports the installed version.
17
+ """
18
+ # Pre-flight check for Rscript executable
19
+ if not shutil.which("Rscript"):
20
+ raise FileNotFoundError("Rscript executable not found in PATH. R is required to run this tool.")
21
+
22
+ r_script_content = """
23
+ if (!requireNamespace("rhdf5filters", quietly = TRUE)) {
24
+ cat("Error: The 'rhdf5filters' package is not installed.\\n", file = stderr())
25
+ quit(status = 1)
26
+ }
27
+ ver <- as.character(packageVersion("rhdf5filters"))
28
+ cat(paste0("Successfully loaded 'rhdf5filters' version: ", ver, "\\n"))
29
+ quit(status = 0)
30
+ """
31
+
32
+ command_executed = ""
33
+ script_path = ""
34
+ try:
35
+ with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R", encoding='utf-8') as tmp_r_script:
36
+ script_path = tmp_r_script.name
37
+ tmp_r_script.write(r_script_content)
38
+
39
+ cmd: List[str] = ["Rscript", script_path]
40
+ command_executed = " ".join(cmd)
41
+
42
+ process = subprocess.run(
43
+ cmd,
44
+ capture_output=True,
45
+ text=True,
46
+ check=True,
47
+ encoding='utf-8'
48
+ )
49
+
50
+ return {
51
+ "command_executed": command_executed,
52
+ "stdout": process.stdout,
53
+ "stderr": process.stderr,
54
+ "output_files": []
55
+ }
56
+
57
+ except subprocess.CalledProcessError as e:
58
+ # This will catch the case where the R script exits with a non-zero status
59
+ # (e.g., package not installed) and return a structured error.
60
+ return {
61
+ "command_executed": command_executed,
62
+ "stdout": e.stdout,
63
+ "stderr": e.stderr,
64
+ "return_code": e.returncode,
65
+ "error": "R script execution failed. The 'rhdf5filters' package may not be installed or accessible."
66
+ }
67
+ finally:
68
+ # Ensure the temporary file is cleaned up
69
+ if script_path and Path(script_path).exists():
70
+ Path(script_path).unlink()
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5filters/app/bioconductor-rhdf5filters_shim_server.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5filters/app/bioconductor-rhdf5filters_server.py')
11
+ SERVER_NAME = 'biosci_bioconductor_rhdf5filters'
12
+
13
+
14
+ class _ShimMCP:
15
+ @staticmethod
16
+ def tool():
17
+ def _decorator(fn):
18
+ return fn
19
+ return _decorator
20
+
21
+
22
+ def _load_functions():
23
+ code = SOURCE_SERVER.read_text(encoding="utf-8")
24
+ tree = ast.parse(code, filename=str(SOURCE_SERVER))
25
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
26
+ namespace = {
27
+ "__name__": "__mcp_source__",
28
+ "mcp": _ShimMCP(),
29
+ }
30
+ exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace)
31
+ loaded = []
32
+ for name in function_names:
33
+ fn = namespace.get(name)
34
+ if callable(fn):
35
+ loaded.append(fn)
36
+ return loaded
37
+
38
+
39
+ mcp = FastMCP(SERVER_NAME)
40
+ for _fn in _load_functions():
41
+ mcp.tool()(_fn)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ mcp.run(transport="stdio")
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-rhdf5filters/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+