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

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

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/Dockerfile +40 -0
  2. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/app/bioconductor-multtest_server.py +230 -0
  3. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/app/bioconductor-multtest_shim_server.py +45 -0
  4. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/app/requirements.txt +1 -0
  5. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/docker-compose.yml +22 -0
  6. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/environment.yaml +10 -0
  7. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/requirements.txt +2 -0
  8. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-nebulosa/Dockerfile +40 -0
  9. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-nebulosa/app/bioconductor-nebulosa_server.py +177 -0
  10. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-nebulosa/app/bioconductor-nebulosa_shim_server.py +45 -0
  11. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-nebulosa/docker-compose.yml +22 -0
  12. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-nebulosa/environment.yaml +10 -0
  13. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-nebulosa/requirements.txt +2 -0
  14. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/Dockerfile +40 -0
  15. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/app/bioconductor-noiseq_server.py +413 -0
  16. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/app/bioconductor-noiseq_shim_server.py +45 -0
  17. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/app/requirements.txt +1 -0
  18. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/docker-compose.yml +22 -0
  19. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/environment.yaml +10 -0
  20. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/requirements.txt +2 -0
  21. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/Dockerfile +40 -0
  22. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/app/bioconductor-org.hs.eg.db_server.py +187 -0
  23. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/app/bioconductor-org.hs.eg.db_shim_server.py +45 -0
  24. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/app/requirements.txt +1 -0
  25. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/docker-compose.yml +22 -0
  26. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/environment.yaml +10 -0
  27. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/requirements.txt +2 -0
  28. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-phemd/Dockerfile +40 -0
  29. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-phemd/app/bioconductor-phemd_server.py +141 -0
  30. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-phemd/app/bioconductor-phemd_shim_server.py +45 -0
  31. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-phemd/docker-compose.yml +22 -0
  32. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-phemd/environment.yaml +10 -0
  33. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-phemd/requirements.txt +2 -0
  34. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/Dockerfile +40 -0
  35. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/app/bioconductor-preprocesscore_server.py +332 -0
  36. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/app/bioconductor-preprocesscore_shim_server.py +45 -0
  37. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/app/requirements.txt +1 -0
  38. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/docker-compose.yml +22 -0
  39. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/environment.yaml +10 -0
  40. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/requirements.txt +2 -0
  41. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-proteomicsannotationhubdata/Dockerfile +40 -0
  42. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-proteomicsannotationhubdata/app/bioconductor-proteomicsannotationhubdata_server.py +120 -0
  43. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-proteomicsannotationhubdata/app/bioconductor-proteomicsannotationhubdata_shim_server.py +45 -0
  44. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-proteomicsannotationhubdata/docker-compose.yml +22 -0
  45. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-proteomicsannotationhubdata/environment.yaml +10 -0
  46. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-proteomicsannotationhubdata/requirements.txt +2 -0
  47. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-protgenerics/Dockerfile +40 -0
  48. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-protgenerics/app/bioconductor-protgenerics_server.py +85 -0
  49. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-protgenerics/app/bioconductor-protgenerics_shim_server.py +45 -0
  50. BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-protgenerics/app/requirements.txt +1 -0
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/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-multtest via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bioconductor-multtest -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-multtest_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-multtest_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-multtest_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/app/bioconductor-multtest_server.py ADDED
@@ -0,0 +1,230 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import tempfile
3
+ import logging
4
+ from pathlib import Path
5
+ from typing import List, Optional, Literal
6
+
7
+ # Configure logging
8
+ logging.basicConfig(level=logging.INFO)
9
+
10
+ # Define allowed choices for parameters based on the multtest R package documentation.
11
+ MTP_TEST_CHOICES = Literal[
12
+ "t.onesamp", "t.twosamp.equalvar", "t.twosamp.unequalvar",
13
+ "f", "pairt", "blockf"
14
+ ]
15
+ MTP_ALTERNATIVE_CHOICES = Literal["two.sided", "less", "greater"]
16
+ MTP_TYPEONE_CHOICES = Literal["fwer", "gfwer", "tppfp", "fdr"]
17
+ MTP_NULLDIST_CHOICES = Literal["boot.cs", "boot.ctr", "perm"]
18
+ MTP_METHOD_CHOICES = Literal["ss.maxT", "ss.minP", "sd.maxT", "sd.minP"]
19
+
20
+ ADJP_PROCEDURE_CHOICES = Literal[
21
+ "Bonferroni", "Holm", "Hochberg", "SidakSS", "SidakSD",
22
+ "BH", "BY", "ABH", "TSBH"
23
+ ]
24
+
25
+
26
+ @mcp.tool()
27
+ def multtest_mtp(
28
+ data_file: Path,
29
+ class_labels_file: Path,
30
+ output_prefix: str,
31
+ test: MTP_TEST_CHOICES = "t.twosamp.equalvar",
32
+ alternative: MTP_ALTERNATIVE_CHOICES = "two.sided",
33
+ typeone: MTP_TYPEONE_CHOICES = "fwer",
34
+ alpha: float = 0.05,
35
+ nulldist: MTP_NULLDIST_CHOICES = "boot.cs",
36
+ b: int = 10000,
37
+ method: MTP_METHOD_CHOICES = "ss.maxT",
38
+ seed: Optional[int] = None,
39
+ ) -> dict:
40
+ """
41
+ Performs a Multiple Testing Procedure (MTP) using the bioconductor-multtest package.
42
+
43
+ This function is a wrapper for the main `MTP` function in the `multtest` R package.
44
+ It takes a data matrix and class labels to perform hypothesis testing, controlling
45
+ for a specified type of error rate (e.g., FWER, FDR).
46
+
47
+ Args:
48
+ data_file: Path to the input data file (CSV format). Rows should be features/genes,
49
+ and columns should be samples. A header with sample names and a column
50
+ with feature names are expected.
51
+ class_labels_file: Path to a single-column CSV file containing class labels for
52
+ the samples. The order must match the columns in data_file.
53
+ No header is expected.
54
+ output_prefix: Prefix for the output files (e.g., 'my_analysis').
55
+ test: The statistical test to use.
56
+ alternative: Specifies the alternative hypothesis.
57
+ typeone: The type of error rate to control.
58
+ alpha: The significance level for the error rate.
59
+ nulldist: Method for estimating the null distribution.
60
+ b: The number of bootstrap or permutation resamples.
61
+ method: The multiple testing procedure to use for adjusting p-values.
62
+ seed: An optional integer seed for random number generation to ensure reproducibility.
63
+
64
+ Returns:
65
+ A dictionary containing the executed command, stdout, stderr, and paths to output files.
66
+ """
67
+ # --- Input Validation ---
68
+ if not data_file.is_file():
69
+ raise FileNotFoundError(f"Data file not found: {data_file}")
70
+ if not class_labels_file.is_file():
71
+ raise FileNotFoundError(f"Class labels file not found: {class_labels_file}")
72
+ if not (0 < alpha < 1):
73
+ raise ValueError("alpha must be between 0 and 1.")
74
+ if b <= 0:
75
+ raise ValueError("Number of resamples (b) must be a positive integer.")
76
+
77
+ output_dir = Path.cwd()
78
+ adjp_output_file = output_dir / f"{output_prefix}_adjp.csv"
79
+ reject_output_file = output_dir / f"{output_prefix}_rejected_indices.csv"
80
+
81
+ # --- R Script Generation ---
82
+ # Handle optional seed value for R script
83
+ r_seed_code = f"set.seed({seed})" if seed is not None else ""
84
+
85
+ r_script_content = f"""
86
+ # Load the library
87
+ library(multtest)
88
+
89
+ # Set seed for reproducibility if provided
90
+ {r_seed_code}
91
+
92
+ # Read input data
93
+ # Using tryCatch for better error reporting from R
94
+ tryCatch({{
95
+ X <- as.matrix(read.csv('{data_file}', header=TRUE, row.names=1, check.names=FALSE))
96
+ Y <- read.csv('{class_labels_file}', header=FALSE)$V1
97
+
98
+ # Run the Multiple Testing Procedure
99
+ mtp_results <- MTP(X=X, Y=Y, test='{test}', alternative='{alternative}',
100
+ typeone='{typeone}', alpha={alpha}, nulldist='{nulldist}',
101
+ B={b}, method='{method}')
102
+
103
+ # Write adjusted p-values to output file
104
+ write.csv(mtp_results@adjp, file='{adjp_output_file}', row.names=TRUE)
105
+
106
+ # Write indices of rejected hypotheses
107
+ rejected_indices <- which(mtp_results@reject)
108
+ write.csv(rejected_indices, file='{reject_output_file}', row.names=FALSE)
109
+
110
+ cat("MTP analysis completed successfully.\\n")
111
+ }}, error = function(e) {{
112
+ stop("R script failed with error: ", e$message)
113
+ }})
114
+ """
115
+
116
+ with tempfile.TemporaryDirectory() as temp_dir:
117
+ r_script_path = Path(temp_dir) / "run_mtp.R"
118
+ with open(r_script_path, "w") as f:
119
+ f.write(r_script_content)
120
+
121
+ command = ["Rscript", str(r_script_path)]
122
+ command_str = " ".join(command)
123
+ logging.info(f"Executing command: {command_str}")
124
+
125
+ try:
126
+ result = subprocess.run(
127
+ command,
128
+ check=True,
129
+ capture_output=True,
130
+ text=True,
131
+ )
132
+ return {
133
+ "command_executed": command_str,
134
+ "stdout": result.stdout,
135
+ "stderr": result.stderr,
136
+ "output_files": {
137
+ "adjusted_p_values": str(adjp_output_file),
138
+ "rejected_indices": str(reject_output_file)
139
+ }
140
+ }
141
+ except subprocess.CalledProcessError as e:
142
+ logging.error(f"Error executing R script for MTP: {e.stderr}")
143
+ raise RuntimeError(f"R script execution failed: {e.stderr}") from e
144
+
145
+
146
+ @mcp.tool()
147
+ def multtest_adjust_pvalues(
148
+ raw_pvalues_file: Path,
149
+ procedures: List[ADJP_PROCEDURE_CHOICES],
150
+ output_prefix: str,
151
+ ) -> dict:
152
+ """
153
+ Computes adjusted p-values from a set of raw (unadjusted) p-values.
154
+
155
+ This function is a wrapper for the `mt.rawp2adjp` function in the `multtest` R package.
156
+ It applies one or more specified adjustment procedures to a given list of p-values.
157
+
158
+ Args:
159
+ raw_pvalues_file: Path to a CSV file of raw p-values. The file should have a header
160
+ and the first column should contain feature/gene names.
161
+ procedures: A list of adjustment procedures to apply.
162
+ output_prefix: Prefix for the output file (e.g., 'my_analysis_adjp').
163
+
164
+ Returns:
165
+ A dictionary containing the executed command, stdout, stderr, and the path to the output file.
166
+ """
167
+ # --- Input Validation ---
168
+ if not raw_pvalues_file.is_file():
169
+ raise FileNotFoundError(f"Raw p-values file not found: {raw_pvalues_file}")
170
+ if not procedures:
171
+ raise ValueError("At least one adjustment procedure must be specified.")
172
+
173
+ output_dir = Path.cwd()
174
+ output_file = output_dir / f"{output_prefix}_adjusted_pvalues.csv"
175
+
176
+ # --- R Script Generation ---
177
+ # Format the list of procedures into an R character vector string, e.g., c("BH", "Bonferroni")
178
+ r_proc_vector = 'c(' + ', '.join(f'"{p}"' for p in procedures) + ')'
179
+
180
+ r_script_content = f"""
181
+ # Load the library
182
+ library(multtest)
183
+
184
+ # Read input data
185
+ tryCatch({{
186
+ rawp <- as.matrix(read.csv('{raw_pvalues_file}', header=TRUE, row.names=1, check.names=FALSE))
187
+
188
+ # Define the adjustment procedures
189
+ procs <- {r_proc_vector}
190
+
191
+ # Run the p-value adjustment
192
+ adj_results <- mt.rawp2adjp(rawp, proc=procs)
193
+
194
+ # Write the adjusted p-values to the output file
195
+ # The result 'adjp' contains the adjusted p-values, with original p-values in the first column
196
+ write.csv(adj_results$adjp, file='{output_file}', row.names=TRUE)
197
+
198
+ cat("P-value adjustment completed successfully.\\n")
199
+ }}, error = function(e) {{
200
+ stop("R script failed with error: ", e$message)
201
+ }})
202
+ """
203
+
204
+ with tempfile.TemporaryDirectory() as temp_dir:
205
+ r_script_path = Path(temp_dir) / "run_adjp.R"
206
+ with open(r_script_path, "w") as f:
207
+ f.write(r_script_content)
208
+
209
+ command = ["Rscript", str(r_script_path)]
210
+ command_str = " ".join(command)
211
+ logging.info(f"Executing command: {command_str}")
212
+
213
+ try:
214
+ result = subprocess.run(
215
+ command,
216
+ check=True,
217
+ capture_output=True,
218
+ text=True,
219
+ )
220
+ return {
221
+ "command_executed": command_str,
222
+ "stdout": result.stdout,
223
+ "stderr": result.stderr,
224
+ "output_files": {
225
+ "adjusted_p_values": str(output_file)
226
+ }
227
+ }
228
+ except subprocess.CalledProcessError as e:
229
+ logging.error(f"Error executing R script for p-value adjustment: {e.stderr}")
230
+ raise RuntimeError(f"R script execution failed: {e.stderr}") from e
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/app/bioconductor-multtest_shim_server.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/app/bioconductor-multtest_server.py')
11
+ SERVER_NAME = 'biosci_bioconductor_multtest'
12
+
13
+
14
+ class _ShimMCP:
15
+ @staticmethod
16
+ def tool():
17
+ def _decorator(fn):
18
+ return fn
19
+ return _decorator
20
+
21
+
22
+ def _load_functions():
23
+ code = SOURCE_SERVER.read_text(encoding="utf-8")
24
+ tree = ast.parse(code, filename=str(SOURCE_SERVER))
25
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
26
+ namespace = {
27
+ "__name__": "__mcp_source__",
28
+ "mcp": _ShimMCP(),
29
+ }
30
+ exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace)
31
+ loaded = []
32
+ for name in function_names:
33
+ fn = namespace.get(name)
34
+ if callable(fn):
35
+ loaded.append(fn)
36
+ return loaded
37
+
38
+
39
+ mcp = FastMCP(SERVER_NAME)
40
+ for _fn in _load_functions():
41
+ mcp.tool()(_fn)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ mcp.run(transport="stdio")
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-bioconductor-multtest:
5
+ build: .
6
+ image: mcp-bioconductor-multtest:latest
7
+ container_name: mcp-bioconductor-multtest
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=bioconductor-multtest
12
+ volumes:
13
+ - ./workspace:/app/workspace
14
+ - ./output:/app/output
15
+ restart: unless-stopped
16
+ healthcheck:
17
+ test: ["CMD", "python", "-c", "import sys; sys.exit(0)"]
18
+ interval: 30s
19
+ timeout: 10s
20
+ retries: 3
21
+ start_period: 5s
22
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/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-multtest
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-multtest/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-nebulosa/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-nebulosa via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bioconductor-nebulosa -y && conda clean -a
15
+
16
+ # Install Python dependencies
17
+ RUN pip install uv
18
+ RUN uv pip install --system fastmcp
19
+
20
+ # Create app directory
21
+ WORKDIR /app
22
+
23
+ # Copy your MCP server
24
+ COPY bioconductor-nebulosa_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-nebulosa_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-nebulosa_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-nebulosa/app/bioconductor-nebulosa_server.py ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import tempfile
3
+ from pathlib import Path
4
+ from typing import List, Optional, Tuple
5
+
6
+ # This is a placeholder for the MCP decorator.
7
+ # In a real MCP environment, this would be imported.
8
+ def tool(*args, **kwargs):
9
+ def decorator(func):
10
+ return func
11
+ return decorator
12
+
13
+ mcp = type("mcp", (), {"tool": tool})
14
+
15
+
16
+ @mcp.tool()
17
+ def nebulosa_plot_density(
18
+ object_file: Path,
19
+ features: List[str],
20
+ output_file: Path,
21
+ reduction: Optional[str] = None,
22
+ dims: Tuple[int, int] = (1, 2),
23
+ pal: str = "viridis",
24
+ joint: bool = False,
25
+ combine: bool = True,
26
+ pt_size: float = 0.1,
27
+ pt_shape: int = 16,
28
+ pt_alpha: float = 1.0,
29
+ dens_alpha: float = 0.5,
30
+ plot_width: float = 8.0,
31
+ plot_height: float = 6.0,
32
+ ) -> dict:
33
+ """
34
+ Generates density plots for single-cell features using the Nebulosa R package.
35
+
36
+ This tool wraps the `plot_density` function from `bioconductor-nebulosa`. It takes a
37
+ single-cell object (e.g., from Seurat, saved as an .rds file), a list of features
38
+ (e.g., genes), and generates a plot showing the expression density of these
39
+ features on a dimensionality reduction embedding (like UMAP or t-SNE).
40
+
41
+ Args:
42
+ object_file: Path to the input single-cell object file in .rds format.
43
+ features: A list of features (e.g., genes) to plot.
44
+ output_file: Path to save the output plot. Supported formats include PDF, PNG, JPEG.
45
+ reduction: The dimensionality reduction to use (e.g., 'umap', 'tsne').
46
+ If None, the default from the object is used.
47
+ dims: A tuple of two integers specifying the dimensions to plot (e.g., (1, 2)).
48
+ pal: The color palette to use for the density plot (e.g., 'viridis', 'magma').
49
+ joint: If True, plots all features jointly on a single plot.
50
+ combine: If True and `joint` is False, combines multiple feature plots into a single grid.
51
+ pt_size: The size of the points in the plot.
52
+ pt_shape: The shape of the points (integer code).
53
+ pt_alpha: The transparency of the points (0.0 to 1.0).
54
+ dens_alpha: The transparency of the density layer (0.0 to 1.0).
55
+ plot_width: The width of the output plot in inches.
56
+ plot_height: The height of the output plot in inches.
57
+
58
+ Returns:
59
+ A dictionary containing the execution command, stdout, stderr, and a
60
+ mapping to the generated output plot file.
61
+ """
62
+ # --- Input Validation ---
63
+ if not object_file.is_file():
64
+ raise FileNotFoundError(f"Input object file not found: {object_file}")
65
+
66
+ if not features:
67
+ raise ValueError("The 'features' list cannot be empty.")
68
+
69
+ if not output_file.parent.exists():
70
+ raise FileNotFoundError(f"Output directory does not exist: {output_file.parent}")
71
+
72
+ if len(dims) != 2:
73
+ raise ValueError(f"'dims' must be a tuple of two integers, but got {dims}")
74
+
75
+ if not (0.0 <= pt_alpha <= 1.0):
76
+ raise ValueError(f"'pt_alpha' must be between 0.0 and 1.0, but got {pt_alpha}")
77
+
78
+ if not (0.0 <= dens_alpha <= 1.0):
79
+ raise ValueError(f"'dens_alpha' must be between 0.0 and 1.0, but got {dens_alpha}")
80
+
81
+ # --- R Script Generation ---
82
+ # Convert Python types to R syntax strings
83
+ features_r_str = ', '.join(f'"{f}"' for f in features)
84
+ reduction_r_str = f'"{reduction}"' if reduction else "NULL"
85
+ joint_r_str = str(joint).upper()
86
+ combine_r_str = str(combine).upper()
87
+
88
+ r_script_content = f"""
89
+ # Suppress package startup messages for cleaner output
90
+ suppressPackageStartupMessages(library(Nebulosa))
91
+ suppressPackageStartupMessages(library(Seurat)) # Assumes a Seurat object for loading
92
+ suppressPackageStartupMessages(library(ggplot2))
93
+
94
+ # --- Parameters from Python ---
95
+ object_path <- "{object_file.resolve()}"
96
+ output_path <- "{output_file.resolve()}"
97
+ features_vec <- c({features_r_str})
98
+ reduction_val <- {reduction_r_str}
99
+ dims_vec <- c({dims[0]}, {dims[1]})
100
+ pal_str <- "{pal}"
101
+ joint_bool <- {joint_r_str}
102
+ combine_bool <- {combine_r_str}
103
+ pt_size_num <- {pt_size}
104
+ pt_shape_num <- {pt_shape}
105
+ pt_alpha_num <- {pt_alpha}
106
+ dens_alpha_num <- {dens_alpha}
107
+ plot_width_num <- {plot_width}
108
+ plot_height_num <- {plot_height}
109
+
110
+ # --- Main Logic ---
111
+ cat("Loading single-cell object from:", object_path, "\\n")
112
+ sobj <- readRDS(object_path)
113
+
114
+ cat("Generating density plot for features:", paste(features_vec, collapse=", "), "\\n")
115
+ p <- plot_density(
116
+ object = sobj,
117
+ features = features_vec,
118
+ reduction = reduction_val,
119
+ dims = dims_vec,
120
+ pal = pal_str,
121
+ joint = joint_bool,
122
+ combine = combine_bool,
123
+ pt.size = pt_size_num,
124
+ pt.shape = pt_shape_num,
125
+ pt.alpha = pt_alpha_num,
126
+ dens.alpha = dens_alpha_num
127
+ )
128
+
129
+ cat("Saving plot to:", output_path, "\\n")
130
+ ggsave(
131
+ filename = output_path,
132
+ plot = p,
133
+ width = plot_width_num,
134
+ height = plot_height_num,
135
+ units = "in"
136
+ )
137
+
138
+ cat("Plot generation complete.\\n")
139
+ """
140
+
141
+ # --- Subprocess Execution ---
142
+ stdout_str, stderr_str = "", ""
143
+ command_to_run = []
144
+
145
+ try:
146
+ with tempfile.NamedTemporaryFile(
147
+ mode="w", suffix=".R", delete=False
148
+ ) as tmp_script:
149
+ tmp_script_path = Path(tmp_script.name)
150
+ tmp_script.write(r_script_content)
151
+
152
+ command_to_run = ["Rscript", str(tmp_script_path)]
153
+ process = subprocess.run(
154
+ command_to_run,
155
+ capture_output=True,
156
+ text=True,
157
+ check=True,
158
+ )
159
+ stdout_str = process.stdout
160
+ stderr_str = process.stderr
161
+
162
+ except FileNotFoundError:
163
+ raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.")
164
+ except subprocess.CalledProcessError as e:
165
+ stderr_str = e.stderr + f"\n--- R Script Content ---\n{r_script_content}"
166
+ raise RuntimeError(f"R script execution failed with exit code {e.returncode}:\n{stderr_str}")
167
+ finally:
168
+ if 'tmp_script_path' in locals() and tmp_script_path.exists():
169
+ tmp_script_path.unlink()
170
+
171
+ # --- Structured Result Return ---
172
+ return {
173
+ "command_executed": " ".join(command_to_run),
174
+ "stdout": stdout_str,
175
+ "stderr": stderr_str,
176
+ "output_files": {"density_plot": str(output_file)},
177
+ }
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-nebulosa/app/bioconductor-nebulosa_shim_server.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-nebulosa/app/bioconductor-nebulosa_server.py')
11
+ SERVER_NAME = 'biosci_bioconductor_nebulosa'
12
+
13
+
14
+ class _ShimMCP:
15
+ @staticmethod
16
+ def tool():
17
+ def _decorator(fn):
18
+ return fn
19
+ return _decorator
20
+
21
+
22
+ def _load_functions():
23
+ code = SOURCE_SERVER.read_text(encoding="utf-8")
24
+ tree = ast.parse(code, filename=str(SOURCE_SERVER))
25
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
26
+ namespace = {
27
+ "__name__": "__mcp_source__",
28
+ "mcp": _ShimMCP(),
29
+ }
30
+ exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace)
31
+ loaded = []
32
+ for name in function_names:
33
+ fn = namespace.get(name)
34
+ if callable(fn):
35
+ loaded.append(fn)
36
+ return loaded
37
+
38
+
39
+ mcp = FastMCP(SERVER_NAME)
40
+ for _fn in _load_functions():
41
+ mcp.tool()(_fn)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ mcp.run(transport="stdio")
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-nebulosa/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-bioconductor-nebulosa:
5
+ build: .
6
+ image: mcp-bioconductor-nebulosa:latest
7
+ container_name: mcp-bioconductor-nebulosa
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=bioconductor-nebulosa
12
+ volumes:
13
+ - ./workspace:/app/workspace
14
+ - ./output:/app/output
15
+ restart: unless-stopped
16
+ healthcheck:
17
+ test: ["CMD", "python", "-c", "import sys; sys.exit(0)"]
18
+ interval: 30s
19
+ timeout: 10s
20
+ retries: 3
21
+ start_period: 5s
22
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-nebulosa/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-nebulosa
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-nebulosa/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/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-noiseq via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bioconductor-noiseq -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-noiseq_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-noiseq_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-noiseq_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/app/bioconductor-noiseq_server.py ADDED
@@ -0,0 +1,413 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import tempfile
3
+ import textwrap
4
+ from pathlib import Path
5
+ from typing import List, Optional
6
+
7
+ # MCP decorator is not imported as per instructions.
8
+ # It is assumed to be available in the execution environment.
9
+ # from mcp import tool as mcp_tool
10
+
11
+ @mcp.tool()
12
+ def noiseqbio(
13
+ counts_file: Path,
14
+ phenodata_file: Path,
15
+ factor: str,
16
+ condition1: str,
17
+ condition2: str,
18
+ output_prefix: str,
19
+ gene_info_file: Optional[Path] = None,
20
+ k: Optional[float] = 0.5,
21
+ norm: str = "tmm",
22
+ lc: int = 1,
23
+ r: int = 20,
24
+ adj: float = 1.5,
25
+ a0per: float = 0.9,
26
+ filter_method: int = 1,
27
+ q_threshold: float = 0.8,
28
+ ) -> dict:
29
+ """
30
+ Performs differential expression analysis for RNA-Seq data with biological
31
+ replicates using NOISeqbio.
32
+
33
+ NOISeq is a non-parametric approach for the identification of differentially
34
+ expressed genes from count data. This function is specifically for experiments
35
+ with biological replicates.
36
+
37
+ Args:
38
+ counts_file: Path to the input counts matrix file (e.g., TSV, CSV).
39
+ Rows should be genes/features and columns should be samples.
40
+ phenodata_file: Path to the phenodata/metadata file. Rows must correspond
41
+ to samples (columns in counts_file) and columns to experimental
42
+ factors.
43
+ factor: The name of the column in phenodata_file that contains the
44
+ experimental conditions to be compared.
45
+ condition1: The first condition or level of the factor to compare.
46
+ condition2: The second condition or level of the factor to compare.
47
+ output_prefix: The prefix for the output result file.
48
+ gene_info_file: Optional path to a file containing gene information like
49
+ length, GC content, or biotype. Required for certain
50
+ normalizations.
51
+ k: Value to be added to the counts for log-transformation. If None, no
52
+ transformation is applied. Defaults to 0.5.
53
+ norm: Normalization method. One of "rpkm", "uqua", "tmm", "n" (none).
54
+ Defaults to "tmm".
55
+ lc: Length correction parameter. Defaults to 1.
56
+ r: Number of permutations to compute the null distribution. Defaults to 20.
57
+ adj: Adjustment factor for feature length in saturation study. Defaults to 1.5.
58
+ a0per: Percentile of feature length distribution for saturation study.
59
+ Must be between 0 and 1. Defaults to 0.9.
60
+ filter_method: Method for filtering low count features. 0: no filter;
61
+ 1: CPM-based; 2: count-based. Defaults to 1.
62
+ q_threshold: Probability threshold for defining differentially expressed
63
+ genes. Must be between 0 and 1. Defaults to 0.8.
64
+
65
+ Returns:
66
+ A dictionary containing the execution command, stdout, stderr, and a list
67
+ of output file paths.
68
+ """
69
+ # --- Input Validation ---
70
+ if not counts_file.is_file():
71
+ raise FileNotFoundError(f"Counts file not found: {counts_file}")
72
+ if not phenodata_file.is_file():
73
+ raise FileNotFoundError(f"Phenodata file not found: {phenodata_file}")
74
+ if gene_info_file and not gene_info_file.is_file():
75
+ raise FileNotFoundError(f"Gene info file not found: {gene_info_file}")
76
+
77
+ valid_norms = ["rpkm", "uqua", "tmm", "n"]
78
+ if norm not in valid_norms:
79
+ raise ValueError(f"Invalid normalization method '{norm}'. Must be one of {valid_norms}.")
80
+
81
+ if not 0.0 <= a0per <= 1.0:
82
+ raise ValueError("a0per must be between 0.0 and 1.0.")
83
+ if not 0.0 <= q_threshold <= 1.0:
84
+ raise ValueError("q_threshold must be between 0.0 and 1.0.")
85
+ if filter_method not in [0, 1, 2]:
86
+ raise ValueError("filter_method must be 0, 1, or 2.")
87
+ if lc < 0:
88
+ raise ValueError("lc must be a non-negative integer.")
89
+ if r < 1:
90
+ raise ValueError("r must be a positive integer.")
91
+ if adj < 0:
92
+ raise ValueError("adj must be a non-negative float.")
93
+
94
+ with tempfile.TemporaryDirectory() as temp_dir:
95
+ work_dir = Path(temp_dir)
96
+ output_file = work_dir / f"{output_prefix}_noiseqbio_results.tsv"
97
+ r_script_path = work_dir / "run_noiseqbio.R"
98
+
99
+ # --- R Script Generation ---
100
+ r_script = textwrap.dedent(f"""\
101
+ suppressPackageStartupMessages(library(argparse))
102
+ suppressPackageStartupMessages(library(NOISeq))
103
+
104
+ parser <- ArgumentParser(description='Run NOISeqbio analysis')
105
+ parser$add_argument('--counts', type='character', required=TRUE)
106
+ parser$add_argument('--pheno', type='character', required=TRUE)
107
+ parser$add_argument('--gene_info', type='character', default=NULL)
108
+ parser$add_argument('--factor', type='character', required=TRUE)
109
+ parser$add_argument('--cond1', type='character', required=TRUE)
110
+ parser$add_argument('--cond2', type='character', required=TRUE)
111
+ parser$add_argument('--output', type='character', required=TRUE)
112
+ parser$add_argument('--k', type='double', default=NA)
113
+ parser$add_argument('--norm', type='character', default='tmm')
114
+ parser$add_argument('--lc', type='integer', default=1)
115
+ parser$add_argument('--r', type='integer', default=20)
116
+ parser$add_argument('--adj', type='double', default=1.5)
117
+ parser$add_argument('--a0per', type='double', default=0.9)
118
+ parser$add_argument('--filter', type='integer', default=1)
119
+ parser$add_argument('--q', type='double', default=0.8)
120
+ args <- parser$parse_args()
121
+
122
+ # Read data
123
+ counts_data <- read.delim(args$counts, row.names=1, check.names=FALSE)
124
+ pheno_data <- read.delim(args$pheno, row.names=1, check.names=FALSE)
125
+
126
+ # Prepare optional data
127
+ length_data <- NULL
128
+ gc_data <- NULL
129
+ biotype_data <- NULL
130
+ if (!is.null(args$gene_info)) {{
131
+ gene_info_data <- read.delim(args$gene_info, row.names=1, check.names=FALSE)
132
+ if ("length" %in% colnames(gene_info_data)) length_data <- gene_info_data[,"length", drop=FALSE]
133
+ if ("gc" %in% colnames(gene_info_data)) gc_data <- gene_info_data[,"gc", drop=FALSE]
134
+ if ("biotype" %in% colnames(gene_info_data)) biotype_data <- gene_info_data[,"biotype", drop=FALSE]
135
+ }}
136
+
137
+ # Create NOISeq object
138
+ mydata <- readData(
139
+ data = counts_data,
140
+ factors = pheno_data,
141
+ length = length_data,
142
+ gc = gc_data,
143
+ biotype = biotype_data
144
+ )
145
+
146
+ # Handle optional k
147
+ k_val <- if (is.na(args$k)) NULL else args$k
148
+
149
+ # Run analysis
150
+ mynoiseqbio <- noiseqbio(
151
+ mydata,
152
+ factor = args$factor,
153
+ conditions = c(args$cond1, args$cond2),
154
+ k = k_val,
155
+ norm = args$norm,
156
+ lc = as.integer(args$lc),
157
+ r = as.integer(args$r),
158
+ adj = as.double(args$adj),
159
+ a0per = as.double(args$a0per),
160
+ filter = as.integer(args$filter)
161
+ )
162
+
163
+ # Write results
164
+ results_df <- degenes(mynoiseqbio, q = args$q, M = NULL)
165
+ write.table(results_df, file=args$output, sep="\\t", quote=FALSE, row.names=TRUE, col.names=NA)
166
+
167
+ cat("NOISeqbio analysis completed successfully.\\n")
168
+ """)
169
+ with open(r_script_path, "w") as f:
170
+ f.write(r_script)
171
+
172
+ # --- Command Construction ---
173
+ cmd = [
174
+ "Rscript", str(r_script_path),
175
+ "--counts", str(counts_file.resolve()),
176
+ "--pheno", str(phenodata_file.resolve()),
177
+ "--factor", factor,
178
+ "--cond1", condition1,
179
+ "--cond2", condition2,
180
+ "--output", str(output_file.resolve()),
181
+ "--norm", norm,
182
+ "--lc", str(lc),
183
+ "--r", str(r),
184
+ "--adj", str(adj),
185
+ "--a0per", str(a0per),
186
+ "--filter", str(filter_method),
187
+ "--q", str(q_threshold),
188
+ ]
189
+ if k is not None:
190
+ cmd.extend(["--k", str(k)])
191
+ if gene_info_file:
192
+ cmd.extend(["--gene_info", str(gene_info_file.resolve())])
193
+
194
+ # --- Subprocess Execution ---
195
+ try:
196
+ process = subprocess.run(
197
+ cmd,
198
+ capture_output=True,
199
+ text=True,
200
+ check=True,
201
+ cwd=work_dir,
202
+ )
203
+ final_output_file = Path.cwd() / f"{output_prefix}_noiseqbio_results.tsv"
204
+ output_file.rename(final_output_file)
205
+
206
+ return {
207
+ "command_executed": " ".join(cmd),
208
+ "stdout": process.stdout,
209
+ "stderr": process.stderr,
210
+ "output_files": [str(final_output_file)],
211
+ }
212
+ except subprocess.CalledProcessError as e:
213
+ return {
214
+ "command_executed": " ".join(cmd),
215
+ "stdout": e.stdout,
216
+ "stderr": e.stderr,
217
+ "error": "NOISeqbio execution failed.",
218
+ "return_code": e.returncode,
219
+ }
220
+
221
+ @mcp.tool()
222
+ def noiseq(
223
+ counts_file: Path,
224
+ phenodata_file: Path,
225
+ factor: str,
226
+ condition1: str,
227
+ condition2: str,
228
+ replicates: str,
229
+ output_prefix: str,
230
+ gene_info_file: Optional[Path] = None,
231
+ k: Optional[float] = 0.5,
232
+ norm: str = "rpkm",
233
+ pnr: float = 0.2,
234
+ nss: int = 5,
235
+ v: float = 0.02,
236
+ lc: int = 1,
237
+ q_threshold: float = 0.8,
238
+ ) -> dict:
239
+ """
240
+ Performs differential expression analysis for RNA-Seq data with technical
241
+ replicates or no replicates using NOISeq.
242
+
243
+ This function is suited for experiments where biological replicates are not
244
+ available. It simulates technical replicates to assess noise.
245
+
246
+ Args:
247
+ counts_file: Path to the input counts matrix file (e.g., TSV, CSV).
248
+ phenodata_file: Path to the phenodata/metadata file.
249
+ factor: The name of the column in phenodata_file that contains the
250
+ experimental conditions.
251
+ condition1: The first condition to compare.
252
+ condition2: The second condition to compare.
253
+ replicates: Type of replicates. Must be "technical" or "no".
254
+ output_prefix: The prefix for the output result file.
255
+ gene_info_file: Optional path to a file with gene information (length, etc.).
256
+ k: Value for log-transformation. If None, no transformation. Defaults to 0.5.
257
+ norm: Normalization method. One of "rpkm", "uqua", "tmm", "n". Defaults to "rpkm".
258
+ pnr: Percentage of lowest expression features for noise estimation.
259
+ Must be between 0 and 1. Defaults to 0.2.
260
+ nss: Number of samples for null distribution estimation (if replicates="technical").
261
+ Defaults to 5.
262
+ v: Variability parameter. Must be between 0 and 1. Defaults to 0.02.
263
+ lc: Length correction parameter. Defaults to 1.
264
+ q_threshold: Probability threshold for DE genes. Defaults to 0.8.
265
+
266
+ Returns:
267
+ A dictionary containing the execution command, stdout, stderr, and a list
268
+ of output file paths.
269
+ """
270
+ # --- Input Validation ---
271
+ if not counts_file.is_file():
272
+ raise FileNotFoundError(f"Counts file not found: {counts_file}")
273
+ if not phenodata_file.is_file():
274
+ raise FileNotFoundError(f"Phenodata file not found: {phenodata_file}")
275
+ if gene_info_file and not gene_info_file.is_file():
276
+ raise FileNotFoundError(f"Gene info file not found: {gene_info_file}")
277
+
278
+ valid_replicates = ["technical", "no"]
279
+ if replicates not in valid_replicates:
280
+ raise ValueError(f"Invalid replicates type '{replicates}'. Must be one of {valid_replicates}.")
281
+ valid_norms = ["rpkm", "uqua", "tmm", "n"]
282
+ if norm not in valid_norms:
283
+ raise ValueError(f"Invalid normalization method '{norm}'. Must be one of {valid_norms}.")
284
+
285
+ if not 0.0 <= pnr <= 1.0:
286
+ raise ValueError("pnr must be between 0.0 and 1.0.")
287
+ if not 0.0 <= v <= 1.0:
288
+ raise ValueError("v must be between 0.0 and 1.0.")
289
+ if not 0.0 <= q_threshold <= 1.0:
290
+ raise ValueError("q_threshold must be between 0.0 and 1.0.")
291
+ if nss < 1:
292
+ raise ValueError("nss must be a positive integer.")
293
+ if lc < 0:
294
+ raise ValueError("lc must be a non-negative integer.")
295
+
296
+ with tempfile.TemporaryDirectory() as temp_dir:
297
+ work_dir = Path(temp_dir)
298
+ output_file = work_dir / f"{output_prefix}_noiseq_results.tsv"
299
+ r_script_path = work_dir / "run_noiseq.R"
300
+
301
+ # --- R Script Generation ---
302
+ r_script = textwrap.dedent(f"""\
303
+ suppressPackageStartupMessages(library(argparse))
304
+ suppressPackageStartupMessages(library(NOISeq))
305
+
306
+ parser <- ArgumentParser(description='Run NOISeq analysis')
307
+ parser$add_argument('--counts', type='character', required=TRUE)
308
+ parser$add_argument('--pheno', type='character', required=TRUE)
309
+ parser$add_argument('--gene_info', type='character', default=NULL)
310
+ parser$add_argument('--factor', type='character', required=TRUE)
311
+ parser$add_argument('--cond1', type='character', required=TRUE)
312
+ parser$add_argument('--cond2', type='character', required=TRUE)
313
+ parser$add_argument('--replicates', type='character', required=TRUE)
314
+ parser$add_argument('--output', type='character', required=TRUE)
315
+ parser$add_argument('--k', type='double', default=NA)
316
+ parser$add_argument('--norm', type='character', default='rpkm')
317
+ parser$add_argument('--pnr', type='double', default=0.2)
318
+ parser$add_argument('--nss', type='integer', default=5)
319
+ parser$add_argument('--v', type='double', default=0.02)
320
+ parser$add_argument('--lc', type='integer', default=1)
321
+ parser$add_argument('--q', type='double', default=0.8)
322
+ args <- parser$parse_args()
323
+
324
+ counts_data <- read.delim(args$counts, row.names=1, check.names=FALSE)
325
+ pheno_data <- read.delim(args$pheno, row.names=1, check.names=FALSE)
326
+
327
+ length_data <- NULL; gc_data <- NULL; biotype_data <- NULL
328
+ if (!is.null(args$gene_info)) {{
329
+ gene_info_data <- read.delim(args$gene_info, row.names=1, check.names=FALSE)
330
+ if ("length" %in% colnames(gene_info_data)) length_data <- gene_info_data[,"length", drop=FALSE]
331
+ if ("gc" %in% colnames(gene_info_data)) gc_data <- gene_info_data[,"gc", drop=FALSE]
332
+ if ("biotype" %in% colnames(gene_info_data)) biotype_data <- gene_info_data[,"biotype", drop=FALSE]
333
+ }}
334
+
335
+ mydata <- readData(
336
+ data = counts_data,
337
+ factors = pheno_data,
338
+ length = length_data,
339
+ gc = gc_data,
340
+ biotype = biotype_data
341
+ )
342
+
343
+ k_val <- if (is.na(args$k)) NULL else args$k
344
+
345
+ mynoiseq <- noiseq(
346
+ mydata,
347
+ factor = args$factor,
348
+ replicates = args$replicates,
349
+ conditions = c(args$cond1, args$cond2),
350
+ k = k_val,
351
+ norm = args$norm,
352
+ pnr = as.double(args$pnr),
353
+ nss = as.integer(args$nss),
354
+ v = as.double(args$v),
355
+ lc = as.integer(args$lc)
356
+ )
357
+
358
+ results_df <- degenes(mynoiseq, q = args$q, M = NULL)
359
+ write.table(results_df, file=args$output, sep="\\t", quote=FALSE, row.names=TRUE, col.names=NA)
360
+
361
+ cat("NOISeq analysis completed successfully.\\n")
362
+ """)
363
+ with open(r_script_path, "w") as f:
364
+ f.write(r_script)
365
+
366
+ # --- Command Construction ---
367
+ cmd = [
368
+ "Rscript", str(r_script_path),
369
+ "--counts", str(counts_file.resolve()),
370
+ "--pheno", str(phenodata_file.resolve()),
371
+ "--factor", factor,
372
+ "--cond1", condition1,
373
+ "--cond2", condition2,
374
+ "--replicates", replicates,
375
+ "--output", str(output_file.resolve()),
376
+ "--norm", norm,
377
+ "--pnr", str(pnr),
378
+ "--nss", str(nss),
379
+ "--v", str(v),
380
+ "--lc", str(lc),
381
+ "--q", str(q_threshold),
382
+ ]
383
+ if k is not None:
384
+ cmd.extend(["--k", str(k)])
385
+ if gene_info_file:
386
+ cmd.extend(["--gene_info", str(gene_info_file.resolve())])
387
+
388
+ # --- Subprocess Execution ---
389
+ try:
390
+ process = subprocess.run(
391
+ cmd,
392
+ capture_output=True,
393
+ text=True,
394
+ check=True,
395
+ cwd=work_dir,
396
+ )
397
+ final_output_file = Path.cwd() / f"{output_prefix}_noiseq_results.tsv"
398
+ output_file.rename(final_output_file)
399
+
400
+ return {
401
+ "command_executed": " ".join(cmd),
402
+ "stdout": process.stdout,
403
+ "stderr": process.stderr,
404
+ "output_files": [str(final_output_file)],
405
+ }
406
+ except subprocess.CalledProcessError as e:
407
+ return {
408
+ "command_executed": " ".join(cmd),
409
+ "stdout": e.stdout,
410
+ "stderr": e.stderr,
411
+ "error": "NOISeq execution failed.",
412
+ "return_code": e.returncode,
413
+ }
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/app/bioconductor-noiseq_shim_server.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/app/bioconductor-noiseq_server.py')
11
+ SERVER_NAME = 'biosci_bioconductor_noiseq'
12
+
13
+
14
+ class _ShimMCP:
15
+ @staticmethod
16
+ def tool():
17
+ def _decorator(fn):
18
+ return fn
19
+ return _decorator
20
+
21
+
22
+ def _load_functions():
23
+ code = SOURCE_SERVER.read_text(encoding="utf-8")
24
+ tree = ast.parse(code, filename=str(SOURCE_SERVER))
25
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
26
+ namespace = {
27
+ "__name__": "__mcp_source__",
28
+ "mcp": _ShimMCP(),
29
+ }
30
+ exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace)
31
+ loaded = []
32
+ for name in function_names:
33
+ fn = namespace.get(name)
34
+ if callable(fn):
35
+ loaded.append(fn)
36
+ return loaded
37
+
38
+
39
+ mcp = FastMCP(SERVER_NAME)
40
+ for _fn in _load_functions():
41
+ mcp.tool()(_fn)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ mcp.run(transport="stdio")
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-bioconductor-noiseq:
5
+ build: .
6
+ image: mcp-bioconductor-noiseq:latest
7
+ container_name: mcp-bioconductor-noiseq
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=bioconductor-noiseq
12
+ volumes:
13
+ - ./workspace:/app/workspace
14
+ - ./output:/app/output
15
+ restart: unless-stopped
16
+ healthcheck:
17
+ test: ["CMD", "python", "-c", "import sys; sys.exit(0)"]
18
+ interval: 30s
19
+ timeout: 10s
20
+ retries: 3
21
+ start_period: 5s
22
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/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-noiseq
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-noiseq/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/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-org.hs.eg.db via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bioconductor-org.hs.eg.db -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-org.hs.eg.db_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-org.hs.eg.db_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-org.hs.eg.db_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/app/bioconductor-org.hs.eg.db_server.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import json
3
+ import tempfile
4
+ from pathlib import Path
5
+ from typing import List, Optional, Dict, Any
6
+
7
+ def run_r_command(script: str) -> Dict[str, Any]:
8
+ """
9
+ Helper function to execute R code and capture output.
10
+ Uses jsonlite in R to return structured data.
11
+ """
12
+ # Wrap the script to load the library and output JSON
13
+ full_script = f"""
14
+ suppressPackageStartupMessages(library(org.hs.eg.db))
15
+ suppressPackageStartupMessages(library(jsonlite))
16
+
17
+ tryCatch({{
18
+ {script}
19
+ }}, error = function(e) {{
20
+ write(paste("ERROR:", e$message), stderr())
21
+ q(status = 1)
22
+ }})
23
+ """
24
+
25
+ with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp:
26
+ tmp.write(full_script)
27
+ tmp_path = tmp.name
28
+
29
+ try:
30
+ process = subprocess.run(
31
+ ["Rscript", tmp_path],
32
+ capture_output=True,
33
+ text=True,
34
+ check=True
35
+ )
36
+ return {
37
+ "stdout": process.stdout,
38
+ "stderr": process.stderr,
39
+ "command_executed": f"Rscript {tmp_path}"
40
+ }
41
+ except subprocess.CalledProcessError as e:
42
+ return {
43
+ "error": e.stderr or e.stdout,
44
+ "command_executed": f"Rscript {tmp_path}",
45
+ "stdout": e.stdout,
46
+ "stderr": e.stderr
47
+ }
48
+ finally:
49
+ if Path(tmp_path).exists():
50
+ Path(tmp_path).unlink()
51
+
52
+ @mcp.tool()
53
+ def org_hs_eg_db_select(
54
+ keys: List[str],
55
+ columns: List[str],
56
+ keytype: str = "ENTREZID",
57
+ ) -> Dict[str, Any]:
58
+ """
59
+ Retrieve annotations for the specified keys from the Human (org.hs.eg.db) database.
60
+
61
+ Args:
62
+ keys: A list of identifiers to look up (e.g., ["7157", "4312"] or ["TP53", "BRCA1"]).
63
+ columns: The types of data to retrieve (e.g., ["SYMBOL", "GENENAME", "ENSEMBL"]).
64
+ keytype: The type of the input keys (e.g., "ENTREZID", "SYMBOL", "ENSEMBL").
65
+ """
66
+ # Validation
67
+ if not keys:
68
+ return {"error": "At least one key must be provided."}
69
+ if not columns:
70
+ return {"error": "At least one column must be provided."}
71
+
72
+ # Format R vectors
73
+ r_keys = 'c("' + '","'.join(keys) + '")'
74
+ r_cols = 'c("' + '","'.join(columns) + '")'
75
+
76
+ script = f"""
77
+ res <- select(org.hs.eg.db, keys = {r_keys}, columns = {r_cols}, keytype = "{keytype}")
78
+ cat(toJSON(res, pretty = TRUE))
79
+ """
80
+
81
+ result = run_r_command(script)
82
+ return result
83
+
84
+ @mcp.tool()
85
+ def org_hs_eg_db_keytypes() -> Dict[str, Any]:
86
+ """
87
+ List all available types of identifiers (keytypes) that can be used as input for queries.
88
+ Common types include ENTREZID, SYMBOL, ENSEMBL, and UNIPROT.
89
+ """
90
+ script = """
91
+ res <- keytypes(org.hs.eg.db)
92
+ cat(toJSON(res))
93
+ """
94
+ return run_r_command(script)
95
+
96
+ @mcp.tool()
97
+ def org_hs_eg_db_columns() -> Dict[str, Any]:
98
+ """
99
+ List all available annotation columns that can be retrieved from the database.
100
+ """
101
+ script = """
102
+ res <- columns(org.hs.eg.db)
103
+ cat(toJSON(res))
104
+ """
105
+ return run_r_command(script)
106
+
107
+ @mcp.tool()
108
+ def org_hs_eg_db_map_symbol_to_entrez(
109
+ symbols: List[str]
110
+ ) -> Dict[str, Any]:
111
+ """
112
+ A convenience tool to quickly map Human Gene Symbols to Entrez IDs.
113
+
114
+ Args:
115
+ symbols: List of gene symbols (e.g., ["TP53", "APOE"]).
116
+ """
117
+ if not symbols:
118
+ return {"error": "No symbols provided."}
119
+
120
+ r_keys = 'c("' + '","'.join(symbols) + '")'
121
+ script = f"""
122
+ res <- select(org.hs.eg.db, keys = {r_keys}, columns = c("ENTREZID"), keytype = "SYMBOL")
123
+ cat(toJSON(res, pretty = TRUE))
124
+ """
125
+ return run_r_command(script)
126
+
127
+ @mcp.tool()
128
+ def org_hs_eg_db_get_keys(
129
+ keytype: str = "SYMBOL",
130
+ pattern: str = "",
131
+ limit: int = 100
132
+ ) -> Dict[str, Any]:
133
+ """
134
+ Retrieve a list of all valid keys of a specific type, optionally filtered by a pattern.
135
+
136
+ Args:
137
+ keytype: The type of keys to retrieve (e.g., "SYMBOL", "ENSEMBL").
138
+ pattern: A string pattern to filter keys (uses grep-style matching).
139
+ limit: Maximum number of keys to return to prevent overwhelming output.
140
+ """
141
+ if limit <= 0:
142
+ limit = 100
143
+
144
+ script = f"""
145
+ all_keys <- keys(org.hs.eg.db, keytype = "{keytype}")
146
+ if ("{pattern}" != "") {{
147
+ all_keys <- all_keys[grep("{pattern}", all_keys)]
148
+ }}
149
+ res <- head(all_keys, {limit})
150
+ cat(toJSON(res))
151
+ """
152
+ return run_r_command(script)
153
+
154
+ @mcp.tool()
155
+ def org_hs_eg_db_metadata() -> Dict[str, Any]:
156
+ """
157
+ Get metadata about the org.hs.eg.db package, including version, organism, and data sources.
158
+ """
159
+ script = """
160
+ res <- metadata(org.hs.eg.db)
161
+ cat(toJSON(res, pretty = TRUE))
162
+ """
163
+ return run_r_command(script)
164
+
165
+ @mcp.tool()
166
+ def org_hs_eg_db_map_ids(
167
+ ids: List[str],
168
+ from_type: str,
169
+ to_type: str
170
+ ) -> Dict[str, Any]:
171
+ """
172
+ Generic tool to map identifiers from one type to another.
173
+
174
+ Args:
175
+ ids: List of input identifiers.
176
+ from_type: The source identifier type (e.g., "ENSEMBL").
177
+ to_type: The target identifier type (e.g., "SYMBOL").
178
+ """
179
+ if not ids:
180
+ return {"error": "No IDs provided."}
181
+
182
+ r_keys = 'c("' + '","'.join(ids) + '")'
183
+ script = f"""
184
+ res <- select(org.hs.eg.db, keys = {r_keys}, columns = c("{to_type}"), keytype = "{from_type}")
185
+ cat(toJSON(res, pretty = TRUE))
186
+ """
187
+ return run_r_command(script)
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/app/bioconductor-org.hs.eg.db_shim_server.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/app/bioconductor-org.hs.eg.db_server.py')
11
+ SERVER_NAME = 'biosci_bioconductor_org_hs_eg_db'
12
+
13
+
14
+ class _ShimMCP:
15
+ @staticmethod
16
+ def tool():
17
+ def _decorator(fn):
18
+ return fn
19
+ return _decorator
20
+
21
+
22
+ def _load_functions():
23
+ code = SOURCE_SERVER.read_text(encoding="utf-8")
24
+ tree = ast.parse(code, filename=str(SOURCE_SERVER))
25
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
26
+ namespace = {
27
+ "__name__": "__mcp_source__",
28
+ "mcp": _ShimMCP(),
29
+ }
30
+ exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace)
31
+ loaded = []
32
+ for name in function_names:
33
+ fn = namespace.get(name)
34
+ if callable(fn):
35
+ loaded.append(fn)
36
+ return loaded
37
+
38
+
39
+ mcp = FastMCP(SERVER_NAME)
40
+ for _fn in _load_functions():
41
+ mcp.tool()(_fn)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ mcp.run(transport="stdio")
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-bioconductor-org.hs.eg.db:
5
+ build: .
6
+ image: mcp-bioconductor-org.hs.eg.db:latest
7
+ container_name: mcp-bioconductor-org.hs.eg.db
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=bioconductor-org.hs.eg.db
12
+ volumes:
13
+ - ./workspace:/app/workspace
14
+ - ./output:/app/output
15
+ restart: unless-stopped
16
+ healthcheck:
17
+ test: ["CMD", "python", "-c", "import sys; sys.exit(0)"]
18
+ interval: 30s
19
+ timeout: 10s
20
+ retries: 3
21
+ start_period: 5s
22
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/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-org.hs.eg.db
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-org.hs.eg.db/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-phemd/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-phemd via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bioconductor-phemd -y && conda clean -a
15
+
16
+ # Install Python dependencies
17
+ RUN pip install uv
18
+ RUN uv pip install --system fastmcp
19
+
20
+ # Create app directory
21
+ WORKDIR /app
22
+
23
+ # Copy your MCP server
24
+ COPY bioconductor-phemd_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-phemd_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-phemd_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-phemd/app/bioconductor-phemd_server.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import logging
3
+ from pathlib import Path
4
+ from typing import Optional, List, Dict, Any
5
+
6
+ # The mcp.tool decorator is dynamically supplied by the MCP server environment.
7
+ # It is not included here directly.
8
+ # from mcp import tool as mcp_tool
9
+
10
+ class mcp:
11
+ """A dummy class for local development and type hinting."""
12
+ @staticmethod
13
+ def tool(func):
14
+ return func
15
+
16
+ @mcp.tool
17
+ def rscript(
18
+ file: Optional[Path] = None,
19
+ expressions: Optional[List[str]] = None,
20
+ script_args: Optional[List[str]] = None,
21
+ verbose: bool = False,
22
+ default_packages: Optional[str] = None,
23
+ vanilla: bool = False,
24
+ save: bool = False,
25
+ restore: bool = False,
26
+ no_environ: bool = False,
27
+ no_site_file: bool = False,
28
+ no_init_file: bool = False,
29
+ ) -> Dict[str, Any]:
30
+ """
31
+ Executes an R script or R expressions using the Rscript command-line tool.
32
+
33
+ This tool serves as a wrapper for Rscript, allowing execution of R code either
34
+ from a script file or directly from one or more string expressions. It provides
35
+ comprehensive control over the R session environment.
36
+
37
+ Args:
38
+ file: Path to the R script file to be executed. Mutually exclusive with 'expressions'.
39
+ expressions: A list of R expressions to execute. Mutually exclusive with 'file'.
40
+ script_args: A list of arguments to be passed to the R script itself.
41
+ verbose: If True, enables verbose output, printing progress information.
42
+ default_packages: A comma-separated string of R package names to be loaded by default.
43
+ vanilla: If True, runs R in a "vanilla" session. This is a shortcut for enabling
44
+ --no-save, --no-restore, --no-site-file, --no-init-file, and --no-environ.
45
+ If set to True, it overrides the individual save, restore, and init file flags.
46
+ save: If True, the workspace is saved at the end of the session. Ignored if 'vanilla' is True.
47
+ restore: If True, previously saved objects are restored at startup. Ignored if 'vanilla' is True.
48
+ no_environ: If True, site and user environment files are not read. Ignored if 'vanilla' is True.
49
+ no_site_file: If True, the site-wide Rprofile is not read. Ignored if 'vanilla' is True.
50
+ no_init_file: If True, the user's R profile is not read. Ignored if 'vanilla' is True.
51
+
52
+ Returns:
53
+ A dictionary containing the executed command, stdout, stderr, and a list of output files.
54
+ """
55
+ # 1. Input Validation
56
+ if not file and not expressions:
57
+ raise ValueError("Either an R script 'file' or a list of 'expressions' must be provided.")
58
+ if file and expressions:
59
+ raise ValueError("The 'file' and 'expressions' parameters are mutually exclusive.")
60
+
61
+ if file:
62
+ if not file.is_file():
63
+ raise FileNotFoundError(f"Input R script file not found: {file}")
64
+
65
+ # 2. Command Construction
66
+ cmd = ["Rscript"]
67
+
68
+ # The --vanilla flag is a shortcut that takes precedence over individual session flags.
69
+ if vanilla:
70
+ cmd.append("--vanilla")
71
+ else:
72
+ if save:
73
+ cmd.append("--save")
74
+ if restore:
75
+ cmd.append("--restore")
76
+ if no_environ:
77
+ cmd.append("--no-environ")
78
+ if no_site_file:
79
+ cmd.append("--no-site-file")
80
+ if no_init_file:
81
+ cmd.append("--no-init-file")
82
+
83
+ if verbose:
84
+ cmd.append("--verbose")
85
+
86
+ if default_packages:
87
+ # Basic validation for comma-separated list format
88
+ if not all(pkg.strip() for pkg in default_packages.split(',')):
89
+ raise ValueError("'default_packages' must be a non-empty, comma-separated string.")
90
+ cmd.extend(["--default-packages", default_packages])
91
+
92
+ # Add the primary execution target: either expressions or a file
93
+ if expressions:
94
+ for expr in expressions:
95
+ cmd.extend(["-e", expr])
96
+ elif file:
97
+ cmd.append(str(file))
98
+
99
+ # Add any arguments intended for the R script itself
100
+ if script_args:
101
+ cmd.extend(script_args)
102
+
103
+ # 3. Subprocess Execution
104
+ command_executed = " ".join(cmd)
105
+ logging.info(f"Executing command: {command_executed}")
106
+
107
+ try:
108
+ result = subprocess.run(
109
+ cmd,
110
+ capture_output=True,
111
+ text=True,
112
+ check=True,
113
+ )
114
+ stdout = result.stdout
115
+ stderr = result.stderr
116
+ except FileNotFoundError:
117
+ # This error occurs if 'Rscript' is not in the system's PATH
118
+ return {
119
+ "command_executed": command_executed,
120
+ "stdout": "",
121
+ "stderr": "Error: 'Rscript' command not found. Please ensure R is installed and in your system's PATH.",
122
+ "output_files": []
123
+ }
124
+ except subprocess.CalledProcessError as e:
125
+ logging.error(f"Rscript execution failed with exit code {e.returncode}")
126
+ return {
127
+ "command_executed": command_executed,
128
+ "stdout": e.stdout,
129
+ "stderr": e.stderr,
130
+ "output_files": []
131
+ }
132
+
133
+ # 4. Structured Result Return
134
+ # Rscript itself does not have a defined output file; any file creation is determined
135
+ # by the R code being executed. Therefore, output_files is returned as an empty list.
136
+ return {
137
+ "command_executed": command_executed,
138
+ "stdout": stdout,
139
+ "stderr": stderr,
140
+ "output_files": []
141
+ }
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-phemd/app/bioconductor-phemd_shim_server.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-phemd/app/bioconductor-phemd_server.py')
11
+ SERVER_NAME = 'biosci_bioconductor_phemd'
12
+
13
+
14
+ class _ShimMCP:
15
+ @staticmethod
16
+ def tool():
17
+ def _decorator(fn):
18
+ return fn
19
+ return _decorator
20
+
21
+
22
+ def _load_functions():
23
+ code = SOURCE_SERVER.read_text(encoding="utf-8")
24
+ tree = ast.parse(code, filename=str(SOURCE_SERVER))
25
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
26
+ namespace = {
27
+ "__name__": "__mcp_source__",
28
+ "mcp": _ShimMCP(),
29
+ }
30
+ exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace)
31
+ loaded = []
32
+ for name in function_names:
33
+ fn = namespace.get(name)
34
+ if callable(fn):
35
+ loaded.append(fn)
36
+ return loaded
37
+
38
+
39
+ mcp = FastMCP(SERVER_NAME)
40
+ for _fn in _load_functions():
41
+ mcp.tool()(_fn)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ mcp.run(transport="stdio")
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-phemd/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-bioconductor-phemd:
5
+ build: .
6
+ image: mcp-bioconductor-phemd:latest
7
+ container_name: mcp-bioconductor-phemd
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=bioconductor-phemd
12
+ volumes:
13
+ - ./workspace:/app/workspace
14
+ - ./output:/app/output
15
+ restart: unless-stopped
16
+ healthcheck:
17
+ test: ["CMD", "python", "-c", "import sys; sys.exit(0)"]
18
+ interval: 30s
19
+ timeout: 10s
20
+ retries: 3
21
+ start_period: 5s
22
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-phemd/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-phemd
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-phemd/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/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-preprocesscore via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bioconductor-preprocesscore -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-preprocesscore_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-preprocesscore_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-preprocesscore_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/app/bioconductor-preprocesscore_server.py ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import os
3
+ from pathlib import Path
4
+ from typing import Optional, List
5
+ import tempfile
6
+
7
+ def run_r_command(script_content: str):
8
+ """Helper to execute R code and handle errors."""
9
+ with tempfile.NamedTemporaryFile(mode='w', suffix='.R', delete=False) as tmp:
10
+ tmp.write("library(preprocessCore)\n")
11
+ tmp.write(script_content)
12
+ tmp_path = tmp.name
13
+
14
+ try:
15
+ result = subprocess.run(
16
+ ["Rscript", tmp_path],
17
+ capture_output=True,
18
+ text=True,
19
+ check=True
20
+ )
21
+ return result.stdout, result.stderr
22
+ except subprocess.CalledProcessError as e:
23
+ raise RuntimeError(f"R execution failed: {e.stderr}\nStdout: {e.stdout}")
24
+ finally:
25
+ if os.path.exists(tmp_path):
26
+ os.remove(tmp_path)
27
+
28
+ @mcp.tool()
29
+ def preprocesscore_normalize_quantiles(
30
+ input_file: str,
31
+ output_file: str,
32
+ keep_names: bool = True,
33
+ sep: str = ",",
34
+ header: bool = True
35
+ ):
36
+ """
37
+ Perform Quantile Normalization on a numeric matrix.
38
+
39
+ Args:
40
+ input_file: Path to the input CSV/TSV file containing the matrix.
41
+ output_file: Path where the normalized matrix will be saved.
42
+ keep_names: Whether to preserve row and column names in the output.
43
+ sep: Delimiter used in the input file (e.g., ',' or '\t').
44
+ header: Whether the input file has a header row.
45
+ """
46
+ input_path = Path(input_file)
47
+ output_path = Path(output_file)
48
+
49
+ if not input_path.exists():
50
+ return {"error": f"Input file {input_file} not found."}
51
+
52
+ r_script = f"""
53
+ data <- as.matrix(read.table("{input_path}", header={str(header).upper()}, sep="{sep}"))
54
+ normalized_data <- normalize.quantiles(data, keep.names={str(keep_names).upper()})
55
+ write.table(normalized_data, "{output_path}", sep="{sep}", col.names={str(header).upper()}, row.names=TRUE, quote=FALSE)
56
+ """
57
+
58
+ try:
59
+ stdout, stderr = run_r_command(r_script)
60
+ return {
61
+ "command_executed": "normalize.quantiles",
62
+ "stdout": stdout,
63
+ "stderr": stderr,
64
+ "output_files": [str(output_path)]
65
+ }
66
+ except Exception as e:
67
+ return {"error": str(e)}
68
+
69
+ @mcp.tool()
70
+ def preprocesscore_normalize_quantiles_robust(
71
+ input_file: str,
72
+ output_file: str,
73
+ remove_extreme: str = "both",
74
+ n_remove: int = 1,
75
+ use_log2: bool = False,
76
+ sep: str = ",",
77
+ header: bool = True
78
+ ):
79
+ """
80
+ Perform Robust Quantile Normalization.
81
+
82
+ Args:
83
+ input_file: Path to the input CSV/TSV file.
84
+ output_file: Path for the output file.
85
+ remove_extreme: How to remove outliers: 'none', 'left', 'right', or 'both'.
86
+ n_remove: Number of extreme values to remove.
87
+ use_log2: Whether to apply log2 transformation before normalization.
88
+ sep: Delimiter used in the input file.
89
+ header: Whether the input file has a header row.
90
+ """
91
+ input_path = Path(input_file)
92
+ output_path = Path(output_file)
93
+
94
+ if not input_path.exists():
95
+ return {"error": f"Input file {input_file} not found."}
96
+
97
+ if remove_extreme not in ["none", "left", "right", "both"]:
98
+ return {"error": "remove_extreme must be one of: none, left, right, both"}
99
+
100
+ r_script = f"""
101
+ data <- as.matrix(read.table("{input_path}", header={str(header).upper()}, sep="{sep}"))
102
+ normalized_data <- normalize.quantiles.robust(
103
+ data,
104
+ remove.extreme="{remove_extreme}",
105
+ n.remove={n_remove},
106
+ use.log2={str(use_log2).upper()}
107
+ )
108
+ write.table(normalized_data, "{output_path}", sep="{sep}", col.names={str(header).upper()}, row.names=TRUE, quote=FALSE)
109
+ """
110
+
111
+ try:
112
+ stdout, stderr = run_r_command(r_script)
113
+ return {
114
+ "command_executed": "normalize.quantiles.robust",
115
+ "stdout": stdout,
116
+ "stderr": stderr,
117
+ "output_files": [str(output_path)]
118
+ }
119
+ except Exception as e:
120
+ return {"error": str(e)}
121
+
122
+ @mcp.tool()
123
+ def preprocesscore_background_correct(
124
+ input_file: str,
125
+ output_file: str,
126
+ method: str = "rma",
127
+ sep: str = ",",
128
+ header: bool = True
129
+ ):
130
+ """
131
+ Perform background correction on a matrix of intensities.
132
+
133
+ Args:
134
+ input_file: Path to the input CSV/TSV file.
135
+ output_file: Path for the output file.
136
+ method: Correction method (typically 'rma').
137
+ sep: Delimiter used in the input file.
138
+ header: Whether the input file has a header row.
139
+ """
140
+ input_path = Path(input_file)
141
+ output_path = Path(output_file)
142
+
143
+ if not input_path.exists():
144
+ return {"error": f"Input file {input_file} not found."}
145
+
146
+ r_script = f"""
147
+ data <- as.matrix(read.table("{input_path}", header={str(header).upper()}, sep="{sep}"))
148
+ corrected_data <- background.correct(data, method="{method}")
149
+ write.table(corrected_data, "{output_path}", sep="{sep}", col.names={str(header).upper()}, row.names=TRUE, quote=FALSE)
150
+ """
151
+
152
+ try:
153
+ stdout, stderr = run_r_command(r_script)
154
+ return {
155
+ "command_executed": f"background.correct(method='{method}')",
156
+ "stdout": stdout,
157
+ "stderr": stderr,
158
+ "output_files": [str(output_path)]
159
+ }
160
+ except Exception as e:
161
+ return {"error": str(e)}
162
+
163
+ @mcp.tool()
164
+ def preprocesscore_sub_col_summarize_median_polish(
165
+ input_file: str,
166
+ output_file: str,
167
+ group_labels: List[int],
168
+ sep: str = ",",
169
+ header: bool = True
170
+ ):
171
+ """
172
+ Summarize columns of a matrix using Median Polish based on group labels.
173
+
174
+ Args:
175
+ input_file: Path to the input CSV/TSV file.
176
+ output_file: Path for the output file.
177
+ group_labels: A list of integers representing the group for each column (e.g., [1, 1, 2, 2]).
178
+ sep: Delimiter used in the input file.
179
+ header: Whether the input file has a header row.
180
+ """
181
+ input_path = Path(input_file)
182
+ output_path = Path(output_file)
183
+
184
+ if not input_path.exists():
185
+ return {"error": f"Input file {input_file} not found."}
186
+
187
+ # Convert Python list to R vector string
188
+ r_groups = f"c({','.join(map(str, group_labels))})"
189
+
190
+ r_script = f"""
191
+ data <- as.matrix(read.table("{input_path}", header={str(header).upper()}, sep="{sep}"))
192
+ groups <- as.integer({r_groups})
193
+ summarized <- subColSummarizeMedianPolish(data, groups)
194
+ write.table(summarized, "{output_path}", sep="{sep}", col.names=NA, quote=FALSE)
195
+ """
196
+
197
+ try:
198
+ stdout, stderr = run_r_command(r_script)
199
+ return {
200
+ "command_executed": "subColSummarizeMedianPolish",
201
+ "stdout": stdout,
202
+ "stderr": stderr,
203
+ "output_files": [str(output_path)]
204
+ }
205
+ except Exception as e:
206
+ return {"error": str(e)}
207
+
208
+ @mcp.tool()
209
+ def preprocesscore_sub_col_summarize_log_avg(
210
+ input_file: str,
211
+ output_file: str,
212
+ group_labels: List[int],
213
+ sep: str = ",",
214
+ header: bool = True
215
+ ):
216
+ """
217
+ Summarize columns of a matrix using Log-Average based on group labels.
218
+
219
+ Args:
220
+ input_file: Path to the input CSV/TSV file.
221
+ output_file: Path for the output file.
222
+ group_labels: A list of integers representing the group for each column.
223
+ """
224
+ input_path = Path(input_file)
225
+ output_path = Path(output_file)
226
+
227
+ if not input_path.exists():
228
+ return {"error": f"Input file {input_file} not found."}
229
+
230
+ r_groups = f"c({','.join(map(str, group_labels))})"
231
+
232
+ r_script = f"""
233
+ data <- as.matrix(read.table("{input_path}", header={str(header).upper()}, sep="{sep}"))
234
+ groups <- as.integer({r_groups})
235
+ summarized <- subColSummarizeLogAvg(data, groups)
236
+ write.table(summarized, "{output_path}", sep="{sep}", col.names=NA, quote=FALSE)
237
+ """
238
+
239
+ try:
240
+ stdout, stderr = run_r_command(r_script)
241
+ return {
242
+ "command_executed": "subColSummarizeLogAvg",
243
+ "stdout": stdout,
244
+ "stderr": stderr,
245
+ "output_files": [str(output_path)]
246
+ }
247
+ except Exception as e:
248
+ return {"error": str(e)}
249
+
250
+ @mcp.tool()
251
+ def preprocesscore_sub_col_summarize_log_median(
252
+ input_file: str,
253
+ output_file: str,
254
+ group_labels: List[int],
255
+ sep: str = ",",
256
+ header: bool = True
257
+ ):
258
+ """
259
+ Summarize columns of a matrix using Log-Median based on group labels.
260
+
261
+ Args:
262
+ input_file: Path to the input CSV/TSV file.
263
+ output_file: Path for the output file.
264
+ group_labels: A list of integers representing the group for each column.
265
+ """
266
+ input_path = Path(input_file)
267
+ output_path = Path(output_file)
268
+
269
+ if not input_path.exists():
270
+ return {"error": f"Input file {input_file} not found."}
271
+
272
+ r_groups = f"c({','.join(map(str, group_labels))})"
273
+
274
+ r_script = f"""
275
+ data <- as.matrix(read.table("{input_path}", header={str(header).upper()}, sep="{sep}"))
276
+ groups <- as.integer({r_groups})
277
+ summarized <- subColSummarizeLogMedian(data, groups)
278
+ write.table(summarized, "{output_path}", sep="{sep}", col.names=NA, quote=FALSE)
279
+ """
280
+
281
+ try:
282
+ stdout, stderr = run_r_command(r_script)
283
+ return {
284
+ "command_executed": "subColSummarizeLogMedian",
285
+ "stdout": stdout,
286
+ "stderr": stderr,
287
+ "output_files": [str(output_path)]
288
+ }
289
+ except Exception as e:
290
+ return {"error": str(e)}
291
+
292
+ @mcp.tool()
293
+ def preprocesscore_sub_col_summarize_biweight_midavg(
294
+ input_file: str,
295
+ output_file: str,
296
+ group_labels: List[int],
297
+ sep: str = ",",
298
+ header: bool = True
299
+ ):
300
+ """
301
+ Summarize columns of a matrix using Biweight Mid-average based on group labels.
302
+
303
+ Args:
304
+ input_file: Path to the input CSV/TSV file.
305
+ output_file: Path for the output file.
306
+ group_labels: A list of integers representing the group for each column.
307
+ """
308
+ input_path = Path(input_file)
309
+ output_path = Path(output_file)
310
+
311
+ if not input_path.exists():
312
+ return {"error": f"Input file {input_file} not found."}
313
+
314
+ r_groups = f"c({','.join(map(str, group_labels))})"
315
+
316
+ r_script = f"""
317
+ data <- as.matrix(read.table("{input_path}", header={str(header).upper()}, sep="{sep}"))
318
+ groups <- as.integer({r_groups})
319
+ summarized <- subColSummarizeBiweightMidavg(data, groups)
320
+ write.table(summarized, "{output_path}", sep="{sep}", col.names=NA, quote=FALSE)
321
+ """
322
+
323
+ try:
324
+ stdout, stderr = run_r_command(r_script)
325
+ return {
326
+ "command_executed": "subColSummarizeBiweightMidavg",
327
+ "stdout": stdout,
328
+ "stderr": stderr,
329
+ "output_files": [str(output_path)]
330
+ }
331
+ except Exception as e:
332
+ return {"error": str(e)}
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/app/bioconductor-preprocesscore_shim_server.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/app/bioconductor-preprocesscore_server.py')
11
+ SERVER_NAME = 'biosci_bioconductor_preprocesscore'
12
+
13
+
14
+ class _ShimMCP:
15
+ @staticmethod
16
+ def tool():
17
+ def _decorator(fn):
18
+ return fn
19
+ return _decorator
20
+
21
+
22
+ def _load_functions():
23
+ code = SOURCE_SERVER.read_text(encoding="utf-8")
24
+ tree = ast.parse(code, filename=str(SOURCE_SERVER))
25
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
26
+ namespace = {
27
+ "__name__": "__mcp_source__",
28
+ "mcp": _ShimMCP(),
29
+ }
30
+ exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace)
31
+ loaded = []
32
+ for name in function_names:
33
+ fn = namespace.get(name)
34
+ if callable(fn):
35
+ loaded.append(fn)
36
+ return loaded
37
+
38
+
39
+ mcp = FastMCP(SERVER_NAME)
40
+ for _fn in _load_functions():
41
+ mcp.tool()(_fn)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ mcp.run(transport="stdio")
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-bioconductor-preprocesscore:
5
+ build: .
6
+ image: mcp-bioconductor-preprocesscore:latest
7
+ container_name: mcp-bioconductor-preprocesscore
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=bioconductor-preprocesscore
12
+ volumes:
13
+ - ./workspace:/app/workspace
14
+ - ./output:/app/output
15
+ restart: unless-stopped
16
+ healthcheck:
17
+ test: ["CMD", "python", "-c", "import sys; sys.exit(0)"]
18
+ interval: 30s
19
+ timeout: 10s
20
+ retries: 3
21
+ start_period: 5s
22
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/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-preprocesscore
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-preprocesscore/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-proteomicsannotationhubdata/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-proteomicsannotationhubdata via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bioconductor-proteomicsannotationhubdata -y && conda clean -a
15
+
16
+ # Install Python dependencies
17
+ RUN pip install uv
18
+ RUN uv pip install --system fastmcp
19
+
20
+ # Create app directory
21
+ WORKDIR /app
22
+
23
+ # Copy your MCP server
24
+ COPY bioconductor-proteomicsannotationhubdata_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-proteomicsannotationhubdata_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-proteomicsannotationhubdata_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-proteomicsannotationhubdata/app/bioconductor-proteomicsannotationhubdata_server.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ from pathlib import Path
3
+ from typing import Optional, List, Dict, Any
4
+
5
+ # MCP decorator placeholder
6
+ def tool(func):
7
+ """A dummy decorator to stand in for the real mcp.tool decorator."""
8
+ return func
9
+
10
+ mcp = type('mcp', (), {'tool': tool})
11
+
12
+ @mcp.tool
13
+ def proteomicsannotationhubdata_rscript(
14
+ script_file: Optional[Path] = None,
15
+ expressions: Optional[List[str]] = None,
16
+ verbose: bool = False,
17
+ default_packages: Optional[str] = None,
18
+ save: bool = False,
19
+ no_environ: bool = False,
20
+ no_site_file: bool = False,
21
+ no_init_file: bool = False,
22
+ restore: bool = False,
23
+ vanilla: bool = False,
24
+ script_args: Optional[List[str]] = None,
25
+ ) -> Dict[str, Any]:
26
+ """
27
+ Executes an R script using the Rscript command-line interface.
28
+
29
+ This tool serves as a generic wrapper for Rscript, enabling the execution of R code
30
+ that can leverage Bioconductor packages like proteomicsannotationhubdata.
31
+ It allows running R code from a file or directly from string expressions.
32
+
33
+ Args:
34
+ script_file: Path to the R script file to be executed. Mutually exclusive with 'expressions'.
35
+ expressions: A list of R expressions to execute. Mutually exclusive with 'script_file'.
36
+ verbose: If True, enables verbose output, printing information on progress (--verbose).
37
+ default_packages: A comma-separated list of packages to load by default (e.g., "utils,graphics").
38
+ save: If True, the workspace will be saved at the end of the session (--save).
39
+ no_environ: If True, site and user environment files will not be read (--no-environ).
40
+ no_site_file: If True, the site-wide Rprofile will not be read (--no-site-file).
41
+ no_init_file: If True, the user's R profile will not be read (--no-init-file).
42
+ restore: If True, previously saved objects will be restored at startup (--restore).
43
+ vanilla: If True, combines --no-save, --no-restore, --no-site-file, --no-init-file, and --no-environ.
44
+ script_args: A list of arguments to be passed to the R script itself.
45
+
46
+ Returns:
47
+ A dictionary containing the executed command, stdout, stderr, and a list of output files.
48
+ Note: This wrapper cannot automatically detect output files generated by the R script.
49
+ """
50
+ # 1. Input Validation
51
+ if script_file and expressions:
52
+ raise ValueError("Cannot specify both 'script_file' and 'expressions'. They are mutually exclusive.")
53
+ if not script_file and not expressions:
54
+ raise ValueError("Must specify either 'script_file' or 'expressions' to execute.")
55
+
56
+ if script_file:
57
+ if not script_file.is_file():
58
+ raise FileNotFoundError(f"The specified script file does not exist: {script_file}")
59
+
60
+ # 2. Command Construction
61
+ command = ["Rscript"]
62
+
63
+ if verbose:
64
+ command.append("--verbose")
65
+ if default_packages:
66
+ command.extend(["--default-packages", default_packages])
67
+ if save:
68
+ command.append("--save")
69
+ if no_environ:
70
+ command.append("--no-environ")
71
+ if no_site_file:
72
+ command.append("--no-site-file")
73
+ if no_init_file:
74
+ command.append("--no-init-file")
75
+ if restore:
76
+ command.append("--restore")
77
+ if vanilla:
78
+ command.append("--vanilla")
79
+
80
+ if expressions:
81
+ for expr in expressions:
82
+ command.extend(["-e", expr])
83
+ elif script_file:
84
+ command.append(str(script_file))
85
+
86
+ if script_args:
87
+ command.extend(script_args)
88
+
89
+ command_str = " ".join(command)
90
+
91
+ # 3. Subprocess Execution and Error Handling
92
+ try:
93
+ result = subprocess.run(
94
+ command,
95
+ check=True,
96
+ capture_output=True,
97
+ text=True,
98
+ )
99
+ return {
100
+ "command_executed": command_str,
101
+ "stdout": result.stdout,
102
+ "stderr": result.stderr,
103
+ "output_files": []
104
+ }
105
+ except FileNotFoundError:
106
+ # This error occurs if 'Rscript' is not in the system's PATH
107
+ return {
108
+ "command_executed": command_str,
109
+ "stdout": "",
110
+ "stderr": "Error: 'Rscript' command not found. Make sure R is installed and in your system's PATH.",
111
+ "output_files": []
112
+ }
113
+ except subprocess.CalledProcessError as e:
114
+ # This error occurs if the R script returns a non-zero exit code
115
+ return {
116
+ "command_executed": command_str,
117
+ "stdout": e.stdout or "",
118
+ "stderr": e.stderr or "",
119
+ "output_files": []
120
+ }
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-proteomicsannotationhubdata/app/bioconductor-proteomicsannotationhubdata_shim_server.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-proteomicsannotationhubdata/app/bioconductor-proteomicsannotationhubdata_server.py')
11
+ SERVER_NAME = 'biosci_bioconductor_proteomicsannotationhubdata'
12
+
13
+
14
+ class _ShimMCP:
15
+ @staticmethod
16
+ def tool():
17
+ def _decorator(fn):
18
+ return fn
19
+ return _decorator
20
+
21
+
22
+ def _load_functions():
23
+ code = SOURCE_SERVER.read_text(encoding="utf-8")
24
+ tree = ast.parse(code, filename=str(SOURCE_SERVER))
25
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
26
+ namespace = {
27
+ "__name__": "__mcp_source__",
28
+ "mcp": _ShimMCP(),
29
+ }
30
+ exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace)
31
+ loaded = []
32
+ for name in function_names:
33
+ fn = namespace.get(name)
34
+ if callable(fn):
35
+ loaded.append(fn)
36
+ return loaded
37
+
38
+
39
+ mcp = FastMCP(SERVER_NAME)
40
+ for _fn in _load_functions():
41
+ mcp.tool()(_fn)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ mcp.run(transport="stdio")
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-proteomicsannotationhubdata/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-bioconductor-proteomicsannotationhubdata:
5
+ build: .
6
+ image: mcp-bioconductor-proteomicsannotationhubdata:latest
7
+ container_name: mcp-bioconductor-proteomicsannotationhubdata
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=bioconductor-proteomicsannotationhubdata
12
+ volumes:
13
+ - ./workspace:/app/workspace
14
+ - ./output:/app/output
15
+ restart: unless-stopped
16
+ healthcheck:
17
+ test: ["CMD", "python", "-c", "import sys; sys.exit(0)"]
18
+ interval: 30s
19
+ timeout: 10s
20
+ retries: 3
21
+ start_period: 5s
22
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-proteomicsannotationhubdata/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-proteomicsannotationhubdata
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-proteomicsannotationhubdata/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-protgenerics/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-protgenerics via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bioconductor-protgenerics -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-protgenerics_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-protgenerics_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-protgenerics_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_help_txt/mcp_bioconductor-protgenerics/app/bioconductor-protgenerics_server.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ from pathlib import Path
3
+ from typing import List, Optional
4
+ import mcp
5
+
6
+ @mcp.tool(
7
+ name="protgenerics_run_r_script",
8
+ description="Executes a user-provided R script in an environment with bioconductor-protgenerics."
9
+ )
10
+ def run_r_script(
11
+ script_path: Path,
12
+ args: Optional[List[str]] = None,
13
+ ) -> dict:
14
+ """
15
+ Executes a given R script using the 'Rscript' command.
16
+
17
+ This tool serves as a generic executor for R scripts within an environment
18
+ where the 'bioconductor-protgenerics' package is expected to be available.
19
+ The 'bioconductor-protgenerics' package itself does not provide a direct
20
+ command-line interface; it is a library of S4 generic functions for
21
+ proteomics analysis, intended to be used within R scripts by other packages.
22
+
23
+ Therefore, instead of wrapping non-existent subcommands, this tool allows
24
+ you to run your own R script that utilizes the functionality provided by
25
+ 'bioconductor-protgenerics' or packages that depend on it.
26
+
27
+ Args:
28
+ script_path: Path to the R script to be executed.
29
+ args: A list of optional command-line arguments to pass to the R script.
30
+
31
+ Returns:
32
+ A dictionary containing the execution details, including the command,
33
+ stdout, stderr, and return code.
34
+ """
35
+ # 1. Input validation
36
+ if not script_path.is_file():
37
+ raise FileNotFoundError(f"The specified R script was not found: {script_path}")
38
+
39
+ if args is None:
40
+ args = []
41
+
42
+ # 2. Command construction
43
+ command = ["Rscript", str(script_path)] + args
44
+ command_str = " ".join(command)
45
+
46
+ # 3. Subprocess execution and error handling
47
+ try:
48
+ process = subprocess.run(
49
+ command,
50
+ capture_output=True,
51
+ text=True,
52
+ check=True,
53
+ encoding='utf-8'
54
+ )
55
+ stdout = process.stdout
56
+ stderr = process.stderr
57
+ return_code = process.returncode
58
+
59
+ except FileNotFoundError:
60
+ # This error occurs if 'Rscript' is not in the system's PATH
61
+ return {
62
+ "command_executed": command_str,
63
+ "stdout": "",
64
+ "stderr": "Error: 'Rscript' command not found. Please ensure R is installed and in your system's PATH.",
65
+ "return_code": -1,
66
+ "output_files": []
67
+ }
68
+ except subprocess.CalledProcessError as e:
69
+ # This error occurs if the R script itself fails (returns a non-zero exit code)
70
+ return {
71
+ "command_executed": command_str,
72
+ "stdout": e.stdout,
73
+ "stderr": e.stderr,
74
+ "return_code": e.returncode,
75
+ "output_files": []
76
+ }
77
+
78
+ # 4. Structured result return
79
+ return {
80
+ "command_executed": command_str,
81
+ "stdout": stdout,
82
+ "stderr": stderr,
83
+ "return_code": return_code,
84
+ "output_files": [] # Output files must be managed by the R script itself and their paths known beforehand.
85
+ }
BioScientist/agent_system/toolbase/mcp_batch_from_help_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_help_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_help_txt/mcp_bioconductor-protgenerics/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ mcp==1.27.0