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

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

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dnacopy/requirements.txt +2 -0
  2. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/Dockerfile +40 -0
  3. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/app/bioconductor-dose_server.py +736 -0
  4. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/app/bioconductor-dose_shim_server.py +45 -0
  5. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/app/requirements.txt +1 -0
  6. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/docker-compose.yml +22 -0
  7. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/environment.yaml +10 -0
  8. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/requirements.txt +2 -0
  9. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ebseq/requirements.txt +2 -0
  10. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/Dockerfile +40 -0
  11. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/app/bioconductor-edger_server.py +236 -0
  12. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/app/bioconductor-edger_shim_server.py +45 -0
  13. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/app/requirements.txt +1 -0
  14. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/docker-compose.yml +22 -0
  15. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/environment.yaml +10 -0
  16. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/requirements.txt +2 -0
  17. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/Dockerfile +40 -0
  18. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/app/bioconductor-ensembldb_server.py +433 -0
  19. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/app/bioconductor-ensembldb_shim_server.py +45 -0
  20. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/app/requirements.txt +1 -0
  21. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/docker-compose.yml +22 -0
  22. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/environment.yaml +10 -0
  23. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/requirements.txt +2 -0
  24. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/Dockerfile +40 -0
  25. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/app/bioconductor-erma_server.py +108 -0
  26. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/app/bioconductor-erma_shim_server.py +45 -0
  27. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/app/requirements.txt +1 -0
  28. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/docker-compose.yml +22 -0
  29. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/environment.yaml +10 -0
  30. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/requirements.txt +2 -0
  31. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/Dockerfile +40 -0
  32. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/app/bioconductor-escher_server.py +279 -0
  33. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/app/bioconductor-escher_shim_server.py +45 -0
  34. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/app/requirements.txt +1 -0
  35. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/docker-compose.yml +22 -0
  36. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/environment.yaml +10 -0
  37. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/requirements.txt +2 -0
  38. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/Dockerfile +40 -0
  39. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/app/bioconductor-experimentsubset_server.py +178 -0
  40. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/app/bioconductor-experimentsubset_shim_server.py +45 -0
  41. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/app/requirements.txt +1 -0
  42. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/docker-compose.yml +22 -0
  43. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/environment.yaml +10 -0
  44. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/requirements.txt +2 -0
  45. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/Dockerfile +40 -0
  46. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/app/bioconductor-fgsea_server.py +421 -0
  47. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/app/bioconductor-fgsea_shim_server.py +45 -0
  48. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/app/requirements.txt +1 -0
  49. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/docker-compose.yml +22 -0
  50. BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/environment.yaml +10 -0
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dnacopy/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/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-dose via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bioconductor-dose -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-dose_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-dose_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-dose_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/app/bioconductor-dose_server.py ADDED
@@ -0,0 +1,736 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import tempfile
3
+ import shutil
4
+ from pathlib import Path
5
+ from typing import Optional, Literal, List
6
+ import logging
7
+
8
+ # Set up logging
9
+ logging.basicConfig(level=logging.INFO)
10
+ log = logging.getLogger(__name__)
11
+
12
+ # Mock the mcp.tool decorator for standalone execution
13
+ class mcp:
14
+ def tool(func):
15
+ return func
16
+
17
+ # Define a common type for p-value adjustment methods
18
+ PAdjustMethod = Literal["holm", "hochberg", "hommel", "bonferroni", "BH", "BY", "fdr", "none"]
19
+
20
+ @mcp.tool
21
+ def enrich_do(
22
+ gene_list_file: Path,
23
+ organism_db: str,
24
+ output_prefix: str,
25
+ key_type: str = "ENTREZID",
26
+ pvalue_cutoff: float = 0.05,
27
+ qvalue_cutoff: float = 0.2,
28
+ p_adjust_method: PAdjustMethod = "BH",
29
+ universe_file: Optional[Path] = None,
30
+ min_gssize: int = 10,
31
+ max_gssize: int = 500,
32
+ readable: bool = False,
33
+ ) -> dict:
34
+ """
35
+ Performs Disease Ontology (DO) enrichment analysis on a given gene list.
36
+
37
+ This tool requires an R environment with 'DOSE', 'clusterProfiler', 'enrichplot',
38
+ and the specified organism database (e.g., 'org.Hs.eg.db') installed.
39
+
40
+ Args:
41
+ gene_list_file: Path to a file containing a list of gene IDs, one per line.
42
+ organism_db: Name of the Bioconductor organism annotation package (e.g., "org.Hs.eg.db").
43
+ output_prefix: Prefix for all output files (e.g., 'my_analysis/do_enrichment').
44
+ key_type: The type of gene identifier in the input file (e.g., "ENTREZID", "SYMBOL", "ENSEMBL").
45
+ pvalue_cutoff: Cutoff for p-value significance.
46
+ qvalue_cutoff: Cutoff for q-value (FDR) significance.
47
+ p_adjust_method: Method for p-value adjustment.
48
+ universe_file: Optional path to a file containing background gene IDs.
49
+ min_gssize: Minimum size of the gene sets to be considered.
50
+ max_gssize: Maximum size of the gene sets to be considered.
51
+ readable: If True, maps gene IDs to gene symbols in the output.
52
+
53
+ Returns:
54
+ A dictionary containing the executed command, stdout, stderr, and paths to output files.
55
+ """
56
+ # --- Input Validation ---
57
+ if not gene_list_file.is_file():
58
+ raise FileNotFoundError(f"Gene list file not found: {gene_list_file}")
59
+ if universe_file and not universe_file.is_file():
60
+ raise FileNotFoundError(f"Universe file not found: {universe_file}")
61
+ if min_gssize < 0 or max_gssize < 0 or min_gssize > max_gssize:
62
+ raise ValueError("Invalid min_gssize or max_gssize.")
63
+ if not shutil.which("Rscript"):
64
+ raise RuntimeError("Rscript not found in PATH. Please ensure R is installed and accessible.")
65
+
66
+ output_dir = Path(output_prefix).parent
67
+ output_dir.mkdir(parents=True, exist_ok=True)
68
+
69
+ output_files = {
70
+ "results_table": Path(f"{output_prefix}_results.csv"),
71
+ "dotplot": Path(f"{output_prefix}_dotplot.png"),
72
+ "cnetplot": Path(f"{output_prefix}_cnetplot.png"),
73
+ }
74
+
75
+ r_script_content = f"""
76
+ # Load required libraries
77
+ suppressPackageStartupMessages(library(DOSE))
78
+ suppressPackageStartupMessages(library(clusterProfiler))
79
+ suppressPackageStartupMessages(library(enrichplot))
80
+ suppressPackageStartupMessages(library(ggplot2))
81
+
82
+ # Check if organism DB is installed, if not, stop with an error
83
+ if (!requireNamespace("{organism_db}", quietly = TRUE)) {{
84
+ stop("Required organism database '{organism_db}' is not installed. Please install it from Bioconductor.", call. = FALSE)
85
+ }}
86
+ library({organism_db}, character.only = TRUE)
87
+
88
+ # Read gene list
89
+ genes <- read.table("{gene_list_file.resolve()}", header = FALSE, stringsAsFactors = FALSE)$V1
90
+
91
+ # Read universe if provided
92
+ universe_genes <- NULL
93
+ if (!is.null("{universe_file}")) {{
94
+ universe_genes <- read.table("{str(universe_file.resolve()) if universe_file else ''}", header = FALSE, stringsAsFactors = FALSE)$V1
95
+ }}
96
+
97
+ # Run enrichment analysis
98
+ edo <- enrichDO(
99
+ gene = genes,
100
+ OrgDb = {organism_db},
101
+ keyType = "{key_type}",
102
+ ont = "DO",
103
+ pvalueCutoff = {pvalue_cutoff},
104
+ pAdjustMethod = "{p_adjust_method}",
105
+ universe = universe_genes,
106
+ minGSSize = {min_gssize},
107
+ maxGSSize = {max_gssize},
108
+ qvalueCutoff = {qvalue_cutoff},
109
+ readable = {"TRUE" if readable else "FALSE"}
110
+ )
111
+
112
+ # Save results if any were found
113
+ if (!is.null(edo) && nrow(as.data.frame(edo)) > 0) {{
114
+ write.csv(as.data.frame(edo), file = "{output_files['results_table'].resolve()}", row.names = FALSE)
115
+
116
+ # Generate and save plots
117
+ p1 <- dotplot(edo, showCategory=30)
118
+ ggsave(p1, filename="{output_files['dotplot'].resolve()}", width=10, height=8)
119
+
120
+ # Cnetplot requires converting gene IDs if readable is TRUE
121
+ edo_plot <- if ("{readable}" == "TRUE") setReadable(edo, OrgDb = {organism_db}, keyType="{key_type}") else edo
122
+ p2 <- cnetplot(edo_plot, categorySize="pvalue")
123
+ ggsave(p2, filename="{output_files['cnetplot'].resolve()}", width=12, height=10)
124
+
125
+ cat("Analysis complete. Results and plots saved.\\n")
126
+ }} else {{
127
+ cat("No significant enrichment found.\\n")
128
+ # Create an empty results file to indicate completion
129
+ file.create("{output_files['results_table'].resolve()}")
130
+ }}
131
+ """
132
+
133
+ with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_r_script:
134
+ tmp_r_script.write(r_script_content)
135
+ r_script_path = tmp_r_script.name
136
+
137
+ command = ["Rscript", r_script_path]
138
+ command_executed = " ".join(command)
139
+ log.info(f"Executing command: {command_executed}")
140
+
141
+ try:
142
+ process = subprocess.run(
143
+ command,
144
+ capture_output=True,
145
+ text=True,
146
+ check=True,
147
+ )
148
+ # Clean up temporary file
149
+ Path(r_script_path).unlink()
150
+
151
+ # Filter out non-existent files if no results were found
152
+ final_output_files = {k: str(v) for k, v in output_files.items() if v.exists()}
153
+
154
+ return {
155
+ "command_executed": command_executed,
156
+ "stdout": process.stdout,
157
+ "stderr": process.stderr,
158
+ "output_files": final_output_files,
159
+ }
160
+ except subprocess.CalledProcessError as e:
161
+ # Clean up temporary file
162
+ Path(r_script_path).unlink()
163
+ log.error(f"R script execution failed:\nSTDOUT: {e.stdout}\nSTDERR: {e.stderr}")
164
+ raise RuntimeError(f"R script failed with exit code {e.returncode}:\n{e.stderr}") from e
165
+
166
+
167
+ @mcp.tool
168
+ def gse_do(
169
+ ranked_gene_list_file: Path,
170
+ organism_db: str,
171
+ output_prefix: str,
172
+ key_type: str = "ENTREZID",
173
+ n_permutations: int = 1000,
174
+ min_gssize: int = 10,
175
+ max_gssize: int = 500,
176
+ pvalue_cutoff: float = 0.05,
177
+ p_adjust_method: PAdjustMethod = "BH",
178
+ verbose: bool = True,
179
+ seed: bool = False,
180
+ ) -> dict:
181
+ """
182
+ Performs Gene Set Enrichment Analysis (GSEA) on Disease Ontology (DO).
183
+
184
+ This tool requires an R environment with 'DOSE', 'clusterProfiler', 'enrichplot',
185
+ and the specified organism database (e.g., 'org.Hs.eg.db') installed.
186
+
187
+ Args:
188
+ ranked_gene_list_file: Path to a two-column file (GeneID, Score/FoldChange) without a header.
189
+ organism_db: Name of the Bioconductor organism annotation package (e.g., "org.Hs.eg.db").
190
+ output_prefix: Prefix for all output files.
191
+ key_type: The type of gene identifier in the input file.
192
+ n_permutations: Number of permutations for GSEA.
193
+ min_gssize: Minimum size of the gene sets to be considered.
194
+ max_gssize: Maximum size of the gene sets to be considered.
195
+ pvalue_cutoff: Cutoff for p-value significance.
196
+ p_adjust_method: Method for p-value adjustment.
197
+ verbose: If True, prints progress messages.
198
+ seed: If True, sets a random seed for reproducibility.
199
+
200
+ Returns:
201
+ A dictionary containing the executed command, stdout, stderr, and paths to output files.
202
+ """
203
+ # --- Input Validation ---
204
+ if not ranked_gene_list_file.is_file():
205
+ raise FileNotFoundError(f"Ranked gene list file not found: {ranked_gene_list_file}")
206
+ if n_permutations <= 0:
207
+ raise ValueError("Number of permutations must be positive.")
208
+ if not shutil.which("Rscript"):
209
+ raise RuntimeError("Rscript not found in PATH. Please ensure R is installed and accessible.")
210
+
211
+ output_dir = Path(output_prefix).parent
212
+ output_dir.mkdir(parents=True, exist_ok=True)
213
+
214
+ output_files = {
215
+ "results_table": Path(f"{output_prefix}_results.csv"),
216
+ "gseaplot": Path(f"{output_prefix}_gseaplot.png"),
217
+ "ridgeplot": Path(f"{output_prefix}_ridgeplot.png"),
218
+ }
219
+
220
+ r_script_content = f"""
221
+ suppressPackageStartupMessages(library(DOSE))
222
+ suppressPackageStartupMessages(library(clusterProfiler))
223
+ suppressPackageStartupMessages(library(enrichplot))
224
+ suppressPackageStartupMessages(library(ggplot2))
225
+
226
+ if (!requireNamespace("{organism_db}", quietly = TRUE)) {{
227
+ stop("Required organism database '{organism_db}' is not installed.", call. = FALSE)
228
+ }}
229
+ library({organism_db}, character.only = TRUE)
230
+
231
+ # Read and prepare ranked gene list
232
+ df <- read.table("{ranked_gene_list_file.resolve()}", header = FALSE, col.names = c("ID", "Score"))
233
+ geneList <- df$Score
234
+ names(geneList) <- as.character(df$ID)
235
+ geneList <- sort(geneList, decreasing = TRUE)
236
+
237
+ # Run GSEA
238
+ gse <- gseDO(
239
+ geneList = geneList,
240
+ OrgDb = {organism_db},
241
+ keyType = "{key_type}",
242
+ nPerm = {n_permutations},
243
+ minGSSize = {min_gssize},
244
+ maxGSSize = {max_gssize},
245
+ pvalueCutoff = {pvalue_cutoff},
246
+ pAdjustMethod = "{p_adjust_method}",
247
+ verbose = {"TRUE" if verbose else "FALSE"},
248
+ seed = {"TRUE" if seed else "FALSE"}
249
+ )
250
+
251
+ if (!is.null(gse) && nrow(as.data.frame(gse)) > 0) {{
252
+ write.csv(as.data.frame(gse), file = "{output_files['results_table'].resolve()}", row.names = FALSE)
253
+
254
+ # Generate and save plots
255
+ # Get the top term ID for the GSEA plot
256
+ top_term_id <- as.data.frame(gse)[1, "ID"]
257
+ p1 <- gseaplot(gse, geneSetID = top_term_id, title = gse[top_term_id, "Description"])
258
+ ggsave(p1, filename="{output_files['gseaplot'].resolve()}", width=10, height=8)
259
+
260
+ p2 <- ridgeplot(gse)
261
+ ggsave(p2, filename="{output_files['ridgeplot'].resolve()}", width=12, height=10)
262
+
263
+ cat("GSEA complete. Results and plots saved.\\n")
264
+ }} else {{
265
+ cat("No significant GSEA results found.\\n")
266
+ file.create("{output_files['results_table'].resolve()}")
267
+ }}
268
+ """
269
+
270
+ with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_r_script:
271
+ tmp_r_script.write(r_script_content)
272
+ r_script_path = tmp_r_script.name
273
+
274
+ command = ["Rscript", r_script_path]
275
+ command_executed = " ".join(command)
276
+ log.info(f"Executing command: {command_executed}")
277
+
278
+ try:
279
+ process = subprocess.run(
280
+ command,
281
+ capture_output=True,
282
+ text=True,
283
+ check=True,
284
+ )
285
+ Path(r_script_path).unlink()
286
+ final_output_files = {k: str(v) for k, v in output_files.items() if v.exists()}
287
+ return {
288
+ "command_executed": command_executed,
289
+ "stdout": process.stdout,
290
+ "stderr": process.stderr,
291
+ "output_files": final_output_files,
292
+ }
293
+ except subprocess.CalledProcessError as e:
294
+ Path(r_script_path).unlink()
295
+ log.error(f"R script execution failed:\nSTDOUT: {e.stdout}\nSTDERR: {e.stderr}")
296
+ raise RuntimeError(f"R script failed with exit code {e.returncode}:\n{e.stderr}") from e
297
+
298
+
299
+ @mcp.tool
300
+ def enrich_ncg(
301
+ gene_list_file: Path,
302
+ output_prefix: str,
303
+ pvalue_cutoff: float = 0.05,
304
+ qvalue_cutoff: float = 0.2,
305
+ p_adjust_method: PAdjustMethod = "BH",
306
+ universe_file: Optional[Path] = None,
307
+ min_gssize: int = 10,
308
+ max_gssize: int = 500,
309
+ readable: bool = False,
310
+ ) -> dict:
311
+ """
312
+ Performs Network of Cancer Genes (NCG) enrichment analysis.
313
+
314
+ This tool requires an R environment with 'DOSE' and 'clusterProfiler' installed.
315
+ It uses built-in NCG data, so an organism DB is not required. Gene IDs must be Entrez IDs.
316
+
317
+ Args:
318
+ gene_list_file: Path to a file containing a list of Entrez gene IDs, one per line.
319
+ output_prefix: Prefix for all output files.
320
+ pvalue_cutoff: Cutoff for p-value significance.
321
+ qvalue_cutoff: Cutoff for q-value (FDR) significance.
322
+ p_adjust_method: Method for p-value adjustment.
323
+ universe_file: Optional path to a file containing background gene IDs.
324
+ min_gssize: Minimum size of the gene sets to be considered.
325
+ max_gssize: Maximum size of the gene sets to be considered.
326
+ readable: If True, maps gene IDs to gene symbols. Requires 'org.Hs.eg.db'.
327
+
328
+ Returns:
329
+ A dictionary containing the executed command, stdout, stderr, and paths to output files.
330
+ """
331
+ # --- Input Validation ---
332
+ if not gene_list_file.is_file():
333
+ raise FileNotFoundError(f"Gene list file not found: {gene_list_file}")
334
+ if universe_file and not universe_file.is_file():
335
+ raise FileNotFoundError(f"Universe file not found: {universe_file}")
336
+ if not shutil.which("Rscript"):
337
+ raise RuntimeError("Rscript not found in PATH. Please ensure R is installed and accessible.")
338
+
339
+ output_dir = Path(output_prefix).parent
340
+ output_dir.mkdir(parents=True, exist_ok=True)
341
+
342
+ output_files = {
343
+ "results_table": Path(f"{output_prefix}_results.csv"),
344
+ "dotplot": Path(f"{output_prefix}_dotplot.png"),
345
+ }
346
+
347
+ readable_setup = ""
348
+ if readable:
349
+ readable_setup = """
350
+ if (!requireNamespace("org.Hs.eg.db", quietly = TRUE)) {
351
+ stop("The 'readable=TRUE' option requires 'org.Hs.eg.db'. Please install it from Bioconductor.", call. = FALSE)
352
+ }
353
+ library(org.Hs.eg.db)
354
+ """
355
+
356
+ r_script_content = f"""
357
+ suppressPackageStartupMessages(library(DOSE))
358
+ suppressPackageStartupMessages(library(clusterProfiler))
359
+ suppressPackageStartupMessages(library(enrichplot))
360
+ suppressPackageStartupMessages(library(ggplot2))
361
+ {readable_setup}
362
+
363
+ genes <- read.table("{gene_list_file.resolve()}", header = FALSE, stringsAsFactors = FALSE)$V1
364
+
365
+ universe_genes <- NULL
366
+ if (!is.null("{universe_file}")) {{
367
+ universe_genes <- read.table("{str(universe_file.resolve()) if universe_file else ''}", header = FALSE, stringsAsFactors = FALSE)$V1
368
+ }}
369
+
370
+ encg <- enrichNCG(
371
+ gene = genes,
372
+ pvalueCutoff = {pvalue_cutoff},
373
+ pAdjustMethod = "{p_adjust_method}",
374
+ universe = universe_genes,
375
+ minGSSize = {min_gssize},
376
+ maxGSSize = {max_gssize},
377
+ qvalueCutoff = {qvalue_cutoff},
378
+ readable = {"TRUE" if readable else "FALSE"}
379
+ )
380
+
381
+ if (!is.null(encg) && nrow(as.data.frame(encg)) > 0) {{
382
+ write.csv(as.data.frame(encg), file = "{output_files['results_table'].resolve()}", row.names = FALSE)
383
+ p1 <- dotplot(encg, showCategory=30)
384
+ ggsave(p1, filename="{output_files['dotplot'].resolve()}", width=10, height=8)
385
+ cat("NCG enrichment complete.\\n")
386
+ }} else {{
387
+ cat("No significant NCG enrichment found.\\n")
388
+ file.create("{output_files['results_table'].resolve()}")
389
+ }}
390
+ """
391
+
392
+ with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_r_script:
393
+ tmp_r_script.write(r_script_content)
394
+ r_script_path = tmp_r_script.name
395
+
396
+ command = ["Rscript", r_script_path]
397
+ command_executed = " ".join(command)
398
+ log.info(f"Executing command: {command_executed}")
399
+
400
+ try:
401
+ process = subprocess.run(command, capture_output=True, text=True, check=True)
402
+ Path(r_script_path).unlink()
403
+ final_output_files = {k: str(v) for k, v in output_files.items() if v.exists()}
404
+ return {
405
+ "command_executed": command_executed,
406
+ "stdout": process.stdout,
407
+ "stderr": process.stderr,
408
+ "output_files": final_output_files,
409
+ }
410
+ except subprocess.CalledProcessError as e:
411
+ Path(r_script_path).unlink()
412
+ log.error(f"R script execution failed:\nSTDOUT: {e.stdout}\nSTDERR: {e.stderr}")
413
+ raise RuntimeError(f"R script failed with exit code {e.returncode}:\n{e.stderr}") from e
414
+
415
+
416
+ @mcp.tool
417
+ def gse_ncg(
418
+ ranked_gene_list_file: Path,
419
+ output_prefix: str,
420
+ n_permutations: int = 1000,
421
+ min_gssize: int = 10,
422
+ max_gssize: int = 500,
423
+ pvalue_cutoff: float = 0.05,
424
+ p_adjust_method: PAdjustMethod = "BH",
425
+ verbose: bool = True,
426
+ seed: bool = False,
427
+ ) -> dict:
428
+ """
429
+ Performs Gene Set Enrichment Analysis (GSEA) on Network of Cancer Genes (NCG).
430
+
431
+ This tool requires an R environment with 'DOSE' and 'clusterProfiler' installed.
432
+ Gene IDs must be Entrez IDs.
433
+
434
+ Args:
435
+ ranked_gene_list_file: Path to a two-column file (EntrezID, Score/FoldChange) without a header.
436
+ output_prefix: Prefix for all output files.
437
+ n_permutations: Number of permutations for GSEA.
438
+ min_gssize: Minimum size of the gene sets to be considered.
439
+ max_gssize: Maximum size of the gene sets to be considered.
440
+ pvalue_cutoff: Cutoff for p-value significance.
441
+ p_adjust_method: Method for p-value adjustment.
442
+ verbose: If True, prints progress messages.
443
+ seed: If True, sets a random seed for reproducibility.
444
+
445
+ Returns:
446
+ A dictionary containing the executed command, stdout, stderr, and paths to output files.
447
+ """
448
+ # --- Input Validation ---
449
+ if not ranked_gene_list_file.is_file():
450
+ raise FileNotFoundError(f"Ranked gene list file not found: {ranked_gene_list_file}")
451
+ if not shutil.which("Rscript"):
452
+ raise RuntimeError("Rscript not found in PATH. Please ensure R is installed and accessible.")
453
+
454
+ output_dir = Path(output_prefix).parent
455
+ output_dir.mkdir(parents=True, exist_ok=True)
456
+
457
+ output_files = {
458
+ "results_table": Path(f"{output_prefix}_results.csv"),
459
+ "ridgeplot": Path(f"{output_prefix}_ridgeplot.png"),
460
+ }
461
+
462
+ r_script_content = f"""
463
+ suppressPackageStartupMessages(library(DOSE))
464
+ suppressPackageStartupMessages(library(clusterProfiler))
465
+ suppressPackageStartupMessages(library(enrichplot))
466
+ suppressPackageStartupMessages(library(ggplot2))
467
+
468
+ df <- read.table("{ranked_gene_list_file.resolve()}", header = FALSE, col.names = c("ID", "Score"))
469
+ geneList <- df$Score
470
+ names(geneList) <- as.character(df$ID)
471
+ geneList <- sort(geneList, decreasing = TRUE)
472
+
473
+ gse <- gseNCG(
474
+ geneList = geneList,
475
+ nPerm = {n_permutations},
476
+ minGSSize = {min_gssize},
477
+ maxGSSize = {max_gssize},
478
+ pvalueCutoff = {pvalue_cutoff},
479
+ pAdjustMethod = "{p_adjust_method}",
480
+ verbose = {"TRUE" if verbose else "FALSE"},
481
+ seed = {"TRUE" if seed else "FALSE"}
482
+ )
483
+
484
+ if (!is.null(gse) && nrow(as.data.frame(gse)) > 0) {{
485
+ write.csv(as.data.frame(gse), file = "{output_files['results_table'].resolve()}", row.names = FALSE)
486
+ p1 <- ridgeplot(gse)
487
+ ggsave(p1, filename="{output_files['ridgeplot'].resolve()}", width=12, height=10)
488
+ cat("NCG GSEA complete.\\n")
489
+ }} else {{
490
+ cat("No significant NCG GSEA results found.\\n")
491
+ file.create("{output_files['results_table'].resolve()}")
492
+ }}
493
+ """
494
+
495
+ with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_r_script:
496
+ tmp_r_script.write(r_script_content)
497
+ r_script_path = tmp_r_script.name
498
+
499
+ command = ["Rscript", r_script_path]
500
+ command_executed = " ".join(command)
501
+ log.info(f"Executing command: {command_executed}")
502
+
503
+ try:
504
+ process = subprocess.run(command, capture_output=True, text=True, check=True)
505
+ Path(r_script_path).unlink()
506
+ final_output_files = {k: str(v) for k, v in output_files.items() if v.exists()}
507
+ return {
508
+ "command_executed": command_executed,
509
+ "stdout": process.stdout,
510
+ "stderr": process.stderr,
511
+ "output_files": final_output_files,
512
+ }
513
+ except subprocess.CalledProcessError as e:
514
+ Path(r_script_path).unlink()
515
+ log.error(f"R script execution failed:\nSTDOUT: {e.stdout}\nSTDERR: {e.stderr}")
516
+ raise RuntimeError(f"R script failed with exit code {e.returncode}:\n{e.stderr}") from e
517
+
518
+
519
+ @mcp.tool
520
+ def enrich_dgn(
521
+ gene_list_file: Path,
522
+ output_prefix: str,
523
+ pvalue_cutoff: float = 0.05,
524
+ qvalue_cutoff: float = 0.2,
525
+ p_adjust_method: PAdjustMethod = "BH",
526
+ universe_file: Optional[Path] = None,
527
+ min_gssize: int = 10,
528
+ max_gssize: int = 500,
529
+ readable: bool = False,
530
+ ) -> dict:
531
+ """
532
+ Performs DisGeNET enrichment analysis.
533
+
534
+ This tool requires an R environment with 'DOSE' and 'clusterProfiler' installed.
535
+ Gene IDs must be Entrez IDs.
536
+
537
+ Args:
538
+ gene_list_file: Path to a file containing a list of Entrez gene IDs, one per line.
539
+ output_prefix: Prefix for all output files.
540
+ pvalue_cutoff: Cutoff for p-value significance.
541
+ qvalue_cutoff: Cutoff for q-value (FDR) significance.
542
+ p_adjust_method: Method for p-value adjustment.
543
+ universe_file: Optional path to a file containing background gene IDs.
544
+ min_gssize: Minimum size of the gene sets to be considered.
545
+ max_gssize: Maximum size of the gene sets to be considered.
546
+ readable: If True, maps gene IDs to gene symbols. Requires 'org.Hs.eg.db'.
547
+
548
+ Returns:
549
+ A dictionary containing the executed command, stdout, stderr, and paths to output files.
550
+ """
551
+ # --- Input Validation ---
552
+ if not gene_list_file.is_file():
553
+ raise FileNotFoundError(f"Gene list file not found: {gene_list_file}")
554
+ if universe_file and not universe_file.is_file():
555
+ raise FileNotFoundError(f"Universe file not found: {universe_file}")
556
+ if not shutil.which("Rscript"):
557
+ raise RuntimeError("Rscript not found in PATH. Please ensure R is installed and accessible.")
558
+
559
+ output_dir = Path(output_prefix).parent
560
+ output_dir.mkdir(parents=True, exist_ok=True)
561
+
562
+ output_files = {
563
+ "results_table": Path(f"{output_prefix}_results.csv"),
564
+ "dotplot": Path(f"{output_prefix}_dotplot.png"),
565
+ }
566
+
567
+ readable_setup = ""
568
+ if readable:
569
+ readable_setup = """
570
+ if (!requireNamespace("org.Hs.eg.db", quietly = TRUE)) {
571
+ stop("The 'readable=TRUE' option requires 'org.Hs.eg.db'. Please install it from Bioconductor.", call. = FALSE)
572
+ }
573
+ library(org.Hs.eg.db)
574
+ """
575
+
576
+ r_script_content = f"""
577
+ suppressPackageStartupMessages(library(DOSE))
578
+ suppressPackageStartupMessages(library(clusterProfiler))
579
+ suppressPackageStartupMessages(library(enrichplot))
580
+ suppressPackageStartupMessages(library(ggplot2))
581
+ {readable_setup}
582
+
583
+ genes <- read.table("{gene_list_file.resolve()}", header = FALSE, stringsAsFactors = FALSE)$V1
584
+
585
+ universe_genes <- NULL
586
+ if (!is.null("{universe_file}")) {{
587
+ universe_genes <- read.table("{str(universe_file.resolve()) if universe_file else ''}", header = FALSE, stringsAsFactors = FALSE)$V1
588
+ }}
589
+
590
+ edgn <- enrichDGN(
591
+ gene = genes,
592
+ pvalueCutoff = {pvalue_cutoff},
593
+ pAdjustMethod = "{p_adjust_method}",
594
+ universe = universe_genes,
595
+ minGSSize = {min_gssize},
596
+ maxGSSize = {max_gssize},
597
+ qvalueCutoff = {qvalue_cutoff},
598
+ readable = {"TRUE" if readable else "FALSE"}
599
+ )
600
+
601
+ if (!is.null(edgn) && nrow(as.data.frame(edgn)) > 0) {{
602
+ write.csv(as.data.frame(edgn), file = "{output_files['results_table'].resolve()}", row.names = FALSE)
603
+ p1 <- dotplot(edgn, showCategory=30)
604
+ ggsave(p1, filename="{output_files['dotplot'].resolve()}", width=10, height=8)
605
+ cat("DisGeNET enrichment complete.\\n")
606
+ }} else {{
607
+ cat("No significant DisGeNET enrichment found.\\n")
608
+ file.create("{output_files['results_table'].resolve()}")
609
+ }}
610
+ """
611
+
612
+ with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_r_script:
613
+ tmp_r_script.write(r_script_content)
614
+ r_script_path = tmp_r_script.name
615
+
616
+ command = ["Rscript", r_script_path]
617
+ command_executed = " ".join(command)
618
+ log.info(f"Executing command: {command_executed}")
619
+
620
+ try:
621
+ process = subprocess.run(command, capture_output=True, text=True, check=True)
622
+ Path(r_script_path).unlink()
623
+ final_output_files = {k: str(v) for k, v in output_files.items() if v.exists()}
624
+ return {
625
+ "command_executed": command_executed,
626
+ "stdout": process.stdout,
627
+ "stderr": process.stderr,
628
+ "output_files": final_output_files,
629
+ }
630
+ except subprocess.CalledProcessError as e:
631
+ Path(r_script_path).unlink()
632
+ log.error(f"R script execution failed:\nSTDOUT: {e.stdout}\nSTDERR: {e.stderr}")
633
+ raise RuntimeError(f"R script failed with exit code {e.returncode}:\n{e.stderr}") from e
634
+
635
+
636
+ @mcp.tool
637
+ def gse_dgn(
638
+ ranked_gene_list_file: Path,
639
+ output_prefix: str,
640
+ n_permutations: int = 1000,
641
+ min_gssize: int = 10,
642
+ max_gssize: int = 500,
643
+ pvalue_cutoff: float = 0.05,
644
+ p_adjust_method: PAdjustMethod = "BH",
645
+ verbose: bool = True,
646
+ seed: bool = False,
647
+ ) -> dict:
648
+ """
649
+ Performs Gene Set Enrichment Analysis (GSEA) on DisGeNET.
650
+
651
+ This tool requires an R environment with 'DOSE' and 'clusterProfiler' installed.
652
+ Gene IDs must be Entrez IDs.
653
+
654
+ Args:
655
+ ranked_gene_list_file: Path to a two-column file (EntrezID, Score/FoldChange) without a header.
656
+ output_prefix: Prefix for all output files.
657
+ n_permutations: Number of permutations for GSEA.
658
+ min_gssize: Minimum size of the gene sets to be considered.
659
+ max_gssize: Maximum size of the gene sets to be considered.
660
+ pvalue_cutoff: Cutoff for p-value significance.
661
+ p_adjust_method: Method for p-value adjustment.
662
+ verbose: If True, prints progress messages.
663
+ seed: If True, sets a random seed for reproducibility.
664
+
665
+ Returns:
666
+ A dictionary containing the executed command, stdout, stderr, and paths to output files.
667
+ """
668
+ # --- Input Validation ---
669
+ if not ranked_gene_list_file.is_file():
670
+ raise FileNotFoundError(f"Ranked gene list file not found: {ranked_gene_list_file}")
671
+ if not shutil.which("Rscript"):
672
+ raise RuntimeError("Rscript not found in PATH. Please ensure R is installed and accessible.")
673
+
674
+ output_dir = Path(output_prefix).parent
675
+ output_dir.mkdir(parents=True, exist_ok=True)
676
+
677
+ output_files = {
678
+ "results_table": Path(f"{output_prefix}_results.csv"),
679
+ "ridgeplot": Path(f"{output_prefix}_ridgeplot.png"),
680
+ }
681
+
682
+ r_script_content = f"""
683
+ suppressPackageStartupMessages(library(DOSE))
684
+ suppressPackageStartupMessages(library(clusterProfiler))
685
+ suppressPackageStartupMessages(library(enrichplot))
686
+ suppressPackageStartupMessages(library(ggplot2))
687
+
688
+ df <- read.table("{ranked_gene_list_file.resolve()}", header = FALSE, col.names = c("ID", "Score"))
689
+ geneList <- df$Score
690
+ names(geneList) <- as.character(df$ID)
691
+ geneList <- sort(geneList, decreasing = TRUE)
692
+
693
+ gse <- gseDGN(
694
+ geneList = geneList,
695
+ nPerm = {n_permutations},
696
+ minGSSize = {min_gssize},
697
+ maxGSSize = {max_gssize},
698
+ pvalueCutoff = {pvalue_cutoff},
699
+ pAdjustMethod = "{p_adjust_method}",
700
+ verbose = {"TRUE" if verbose else "FALSE"},
701
+ seed = {"TRUE" if seed else "FALSE"}
702
+ )
703
+
704
+ if (!is.null(gse) && nrow(as.data.frame(gse)) > 0) {{
705
+ write.csv(as.data.frame(gse), file = "{output_files['results_table'].resolve()}", row.names = FALSE)
706
+ p1 <- ridgeplot(gse)
707
+ ggsave(p1, filename="{output_files['ridgeplot'].resolve()}", width=12, height=10)
708
+ cat("DisGeNET GSEA complete.\\n")
709
+ }} else {{
710
+ cat("No significant DisGeNET GSEA results found.\\n")
711
+ file.create("{output_files['results_table'].resolve()}")
712
+ }}
713
+ """
714
+
715
+ with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False) as tmp_r_script:
716
+ tmp_r_script.write(r_script_content)
717
+ r_script_path = tmp_r_script.name
718
+
719
+ command = ["Rscript", r_script_path]
720
+ command_executed = " ".join(command)
721
+ log.info(f"Executing command: {command_executed}")
722
+
723
+ try:
724
+ process = subprocess.run(command, capture_output=True, text=True, check=True)
725
+ Path(r_script_path).unlink()
726
+ final_output_files = {k: str(v) for k, v in output_files.items() if v.exists()}
727
+ return {
728
+ "command_executed": command_executed,
729
+ "stdout": process.stdout,
730
+ "stderr": process.stderr,
731
+ "output_files": final_output_files,
732
+ }
733
+ except subprocess.CalledProcessError as e:
734
+ Path(r_script_path).unlink()
735
+ log.error(f"R script execution failed:\nSTDOUT: {e.stdout}\nSTDERR: {e.stderr}")
736
+ raise RuntimeError(f"R script failed with exit code {e.returncode}:\n{e.stderr}") from e
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/app/bioconductor-dose_shim_server.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/app/bioconductor-dose_server.py')
11
+ SERVER_NAME = 'biosci_bioconductor_dose'
12
+
13
+
14
+ class _ShimMCP:
15
+ @staticmethod
16
+ def tool():
17
+ def _decorator(fn):
18
+ return fn
19
+ return _decorator
20
+
21
+
22
+ def _load_functions():
23
+ code = SOURCE_SERVER.read_text(encoding="utf-8")
24
+ tree = ast.parse(code, filename=str(SOURCE_SERVER))
25
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
26
+ namespace = {
27
+ "__name__": "__mcp_source__",
28
+ "mcp": _ShimMCP(),
29
+ }
30
+ exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace)
31
+ loaded = []
32
+ for name in function_names:
33
+ fn = namespace.get(name)
34
+ if callable(fn):
35
+ loaded.append(fn)
36
+ return loaded
37
+
38
+
39
+ mcp = FastMCP(SERVER_NAME)
40
+ for _fn in _load_functions():
41
+ mcp.tool()(_fn)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ mcp.run(transport="stdio")
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-bioconductor-dose:
5
+ build: .
6
+ image: mcp-bioconductor-dose:latest
7
+ container_name: mcp-bioconductor-dose
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=bioconductor-dose
12
+ volumes:
13
+ - ./workspace:/app/workspace
14
+ - ./output:/app/output
15
+ restart: unless-stopped
16
+ healthcheck:
17
+ test: ["CMD", "python", "-c", "import sys; sys.exit(0)"]
18
+ interval: 30s
19
+ timeout: 10s
20
+ retries: 3
21
+ start_period: 5s
22
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/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-dose
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-dose/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ebseq/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/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-edger via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bioconductor-edger -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-edger_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-edger_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-edger_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/app/bioconductor-edger_server.py ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import tempfile
3
+ from pathlib import Path
4
+ from typing import Optional
5
+
6
+ # Assume @mcp.tool() is defined in the execution environment.
7
+ # No import is needed as per the instructions.
8
+
9
+
10
+ @mcp.tool()
11
+ def run_edger_de(
12
+ counts_file: Path,
13
+ samples_file: Path,
14
+ output_file: Path,
15
+ contrast: str,
16
+ group_column: str,
17
+ gene_id_column: Optional[str] = None,
18
+ min_cpm: float = 1.0,
19
+ min_samples_fraction: float = 0.5,
20
+ normalization_method: str = "TMM",
21
+ test_method: str = "glmQLFTest",
22
+ fdr_cutoff: float = 0.05,
23
+ r_executable: str = "Rscript",
24
+ ) -> dict:
25
+ """
26
+ Performs differential expression analysis on RNA-seq count data using edgeR.
27
+
28
+ This tool wraps a standard edgeR workflow, including data loading, filtering of
29
+ lowly-expressed genes, TMM normalization, dispersion estimation, model fitting,
30
+ and hypothesis testing using either the quasi-likelihood F-test (glmQLFTest),
31
+ the likelihood ratio test (glmLRT), or the exact test.
32
+
33
+ Args:
34
+ counts_file: Path to the input count matrix file (tab-separated).
35
+ Rows should be genes and columns should be samples.
36
+ samples_file: Path to the sample metadata file (tab-separated).
37
+ Must contain a column mapping samples to experimental groups.
38
+ The first column should contain sample names matching the
39
+ count matrix headers.
40
+ output_file: Path for the output results table (tab-separated).
41
+ contrast: The contrast to be tested, in the format 'GroupA-GroupB'.
42
+ group_column: The name of the column in the samples_file that contains
43
+ the experimental group information.
44
+ gene_id_column: The name of the column in the counts_file that contains
45
+ gene identifiers. If not provided, the first column is used.
46
+ min_cpm: The minimum counts-per-million (CPM) a gene must have to be
47
+ considered expressed. Used for filtering.
48
+ min_samples_fraction: The minimum fraction of samples within the smallest
49
+ group where a gene must have a CPM > min_cpm to be kept.
50
+ normalization_method: Normalization method to be used.
51
+ Options: "TMM", "TMMwsp", "RLE", "upperquartile", "none".
52
+ test_method: The statistical test to use for differential expression.
53
+ Options: "glmQLFTest", "glmLRT", "exactTest".
54
+ fdr_cutoff: The false discovery rate (FDR) threshold for reporting results.
55
+ r_executable: The command to execute Rscript. Defaults to 'Rscript'.
56
+
57
+ Returns:
58
+ A dictionary containing the executed command, stdout, stderr, and a list
59
+ of output file paths.
60
+ """
61
+ # --- 1. Input Validation ---
62
+ if not counts_file.is_file():
63
+ raise FileNotFoundError(f"Counts file not found: {counts_file}")
64
+ if not samples_file.is_file():
65
+ raise FileNotFoundError(f"Samples metadata file not found: {samples_file}")
66
+
67
+ output_file.parent.mkdir(parents=True, exist_ok=True)
68
+
69
+ allowed_norm = ["TMM", "TMMwsp", "RLE", "upperquartile", "none"]
70
+ if normalization_method not in allowed_norm:
71
+ raise ValueError(
72
+ f"Invalid normalization_method '{normalization_method}'. Must be one of {allowed_norm}"
73
+ )
74
+
75
+ allowed_tests = ["glmQLFTest", "glmLRT", "exactTest"]
76
+ if test_method not in allowed_tests:
77
+ raise ValueError(
78
+ f"Invalid test_method '{test_method}'. Must be one of {allowed_tests}"
79
+ )
80
+
81
+ if not (0 <= fdr_cutoff <= 1):
82
+ raise ValueError("fdr_cutoff must be between 0 and 1.")
83
+ if not (0 <= min_samples_fraction <= 1):
84
+ raise ValueError("min_samples_fraction must be between 0 and 1.")
85
+ if min_cpm < 0:
86
+ raise ValueError("min_cpm must be non-negative.")
87
+
88
+ if "-" not in contrast or len(contrast.split("-")) != 2:
89
+ raise ValueError("Contrast must be in the format 'GroupA-GroupB'.")
90
+
91
+ # --- 2. Generate R Script ---
92
+ r_script_content = f"""
93
+ # Load necessary library
94
+ if (!requireNamespace("edgeR", quietly = TRUE)) {{
95
+ stop("The 'edgeR' package is not installed. Please install it from Bioconductor.")
96
+ }}
97
+ library(edgeR)
98
+
99
+ # --- Arguments from Python ---
100
+ counts_file_path <- "{counts_file.resolve()}"
101
+ samples_file_path <- "{samples_file.resolve()}"
102
+ output_file_path <- "{output_file.resolve()}"
103
+ group_col <- "{group_column}"
104
+ contrast_str <- "{contrast}"
105
+ gene_id_col <- {f'"{gene_id_column}"' if gene_id_column else '1'}
106
+ min_cpm_val <- {min_cpm}
107
+ min_samples_frac <- {min_samples_fraction}
108
+ norm_method <- "{normalization_method}"
109
+ test_method <- "{test_method}"
110
+ fdr_val <- {fdr_cutoff}
111
+
112
+ # --- Data Loading ---
113
+ cat("Reading counts data from:", counts_file_path, "\\n")
114
+ counts_data <- read.delim(counts_file_path, row.names = gene_id_col, check.names = FALSE, stringsAsFactors = FALSE)
115
+
116
+ cat("Reading sample metadata from:", samples_file_path, "\\n")
117
+ sample_info <- read.delim(samples_file_path, row.names = 1, check.names = FALSE, stringsAsFactors = FALSE)
118
+
119
+ # Ensure sample order matches between counts and metadata
120
+ if (!all(colnames(counts_data) %in% rownames(sample_info))) {{
121
+ stop("Mismatch: Some column names in the counts file are not present as row names in the samples file.")
122
+ }}
123
+ sample_info <- sample_info[colnames(counts_data), , drop = FALSE]
124
+
125
+ # --- DGEList Object Creation ---
126
+ cat("Creating DGEList object...\\n")
127
+ group <- factor(sample_info[[group_col]])
128
+ dge <- DGEList(counts = counts_data, group = group)
129
+
130
+ # --- Filtering ---
131
+ cat("Filtering low-expressed genes...\\n")
132
+ min_samples_in_smallest_group <- min(table(group))
133
+ min_samples <- floor(min_samples_frac * min_samples_in_smallest_group)
134
+ if (min_samples < 1) {{
135
+ min_samples <- 1 # At least one sample
136
+ }}
137
+ cat("Keeping genes with CPM >", min_cpm_val, "in at least", min_samples, "samples.\\n")
138
+ keep <- rowSums(cpm(dge) > min_cpm_val) >= min_samples
139
+ dge <- dge[keep, , keep.lib.sizes = FALSE]
140
+
141
+ # --- Normalization ---
142
+ cat("Calculating normalization factors using method:", norm_method, "\\n")
143
+ dge <- calcNormFactors(dge, method = norm_method)
144
+
145
+ # --- Model Fitting and Testing ---
146
+ if (test_method == "exactTest") {{
147
+ if (nlevels(group) != 2) {{
148
+ stop("exactTest can only be used for two-group comparisons.")
149
+ }}
150
+ cat("Estimating dispersion for exactTest...\\n")
151
+ dge <- estimateDisp(dge)
152
+
153
+ cat("Performing exact test...\\n")
154
+ et <- exactTest(dge)
155
+
156
+ cat("Extracting top tags...\\n")
157
+ results_table <- topTags(et, n = Inf, adjust.method = "BH", sort.by = "PValue")$table
158
+
159
+ }} else {{ # GLM approach
160
+ cat("Setting up design matrix...\\n")
161
+ design <- model.matrix(~ 0 + group)
162
+ colnames(design) <- make.names(levels(group))
163
+
164
+ cat("Estimating GLM dispersions...\\n")
165
+ dge <- estimateDisp(dge, design, robust=TRUE)
166
+
167
+ if (test_method == "glmLRT") {{
168
+ cat("Fitting GLM model (glmLRT)...\\n")
169
+ fit <- glmFit(dge, design)
170
+
171
+ cat("Performing Likelihood Ratio Test...\\n")
172
+ contr <- makeContrasts(contrasts = contrast_str, levels = design)
173
+ lrt <- glmLRT(fit, contrast = contr)
174
+
175
+ cat("Extracting top tags...\\n")
176
+ results_table <- topTags(lrt, n = Inf, adjust.method = "BH", sort.by = "PValue")$table
177
+
178
+ }} else {{ # glmQLFTest is the default
179
+ cat("Fitting GLM model (glmQLFTest)...\\n")
180
+ fit <- glmQLFit(dge, design, robust=TRUE)
181
+
182
+ cat("Performing Quasi-Likelihood F-Test...\\n")
183
+ contr <- makeContrasts(contrasts = contrast_str, levels = design)
184
+ qlf <- glmQLFTest(fit, contrast = contr)
185
+
186
+ cat("Extracting top tags...\\n")
187
+ results_table <- topTags(qlf, n = Inf, adjust.method = "BH", sort.by = "PValue")$table
188
+ }}
189
+ }}
190
+
191
+ # Add gene IDs back as a column for clarity
192
+ results_table <- cbind(GeneID = rownames(results_table), results_table)
193
+
194
+ # --- Writing Output ---
195
+ cat("Writing results with FDR <", fdr_val, "to:", output_file_path, "\\n")
196
+ final_results <- subset(results_table, FDR < fdr_val)
197
+ write.table(final_results, file = output_file_path, sep = "\\t", quote = FALSE, row.names = FALSE)
198
+
199
+ cat("edgeR analysis complete.\\n")
200
+ """
201
+
202
+ # --- 3. Subprocess Execution ---
203
+ with tempfile.NamedTemporaryFile(
204
+ mode="w", delete=False, suffix=".R", encoding="utf-8"
205
+ ) as r_script_file:
206
+ r_script_file.write(r_script_content)
207
+ r_script_path = r_script_file.name
208
+
209
+ command = [r_executable, r_script_path]
210
+ command_str = " ".join(map(str, command))
211
+
212
+ try:
213
+ result = subprocess.run(
214
+ command, capture_output=True, text=True, check=True, encoding="utf-8"
215
+ )
216
+ return {
217
+ "command_executed": command_str,
218
+ "stdout": result.stdout,
219
+ "stderr": result.stderr,
220
+ "output_files": [str(output_file.resolve())],
221
+ }
222
+ except FileNotFoundError:
223
+ raise RuntimeError(
224
+ f"Rscript executable not found at '{r_executable}'. Please ensure R is installed and in your system's PATH."
225
+ )
226
+ except subprocess.CalledProcessError as e:
227
+ error_message = (
228
+ f"edgeR R script failed with exit code {e.returncode}.\n"
229
+ f"COMMAND: {command_str}\n"
230
+ f"STDOUT:\n{e.stdout}\n"
231
+ f"STDERR:\n{e.stderr}\n"
232
+ )
233
+ raise RuntimeError(error_message)
234
+ finally:
235
+ # Ensure temporary file is always cleaned up
236
+ Path(r_script_path).unlink()
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/app/bioconductor-edger_shim_server.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/app/bioconductor-edger_server.py')
11
+ SERVER_NAME = 'biosci_bioconductor_edger'
12
+
13
+
14
+ class _ShimMCP:
15
+ @staticmethod
16
+ def tool():
17
+ def _decorator(fn):
18
+ return fn
19
+ return _decorator
20
+
21
+
22
+ def _load_functions():
23
+ code = SOURCE_SERVER.read_text(encoding="utf-8")
24
+ tree = ast.parse(code, filename=str(SOURCE_SERVER))
25
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
26
+ namespace = {
27
+ "__name__": "__mcp_source__",
28
+ "mcp": _ShimMCP(),
29
+ }
30
+ exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace)
31
+ loaded = []
32
+ for name in function_names:
33
+ fn = namespace.get(name)
34
+ if callable(fn):
35
+ loaded.append(fn)
36
+ return loaded
37
+
38
+
39
+ mcp = FastMCP(SERVER_NAME)
40
+ for _fn in _load_functions():
41
+ mcp.tool()(_fn)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ mcp.run(transport="stdio")
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-bioconductor-edger:
5
+ build: .
6
+ image: mcp-bioconductor-edger:latest
7
+ container_name: mcp-bioconductor-edger
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=bioconductor-edger
12
+ volumes:
13
+ - ./workspace:/app/workspace
14
+ - ./output:/app/output
15
+ restart: unless-stopped
16
+ healthcheck:
17
+ test: ["CMD", "python", "-c", "import sys; sys.exit(0)"]
18
+ interval: 30s
19
+ timeout: 10s
20
+ retries: 3
21
+ start_period: 5s
22
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/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-edger
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-edger/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/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-ensembldb via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bioconductor-ensembldb -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-ensembldb_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-ensembldb_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-ensembldb_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/app/bioconductor-ensembldb_server.py ADDED
@@ -0,0 +1,433 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import tempfile
3
+ import textwrap
4
+ from pathlib import Path
5
+ from typing import Optional, List, Dict, Any
6
+
7
+ # Assume mcp.tool is imported from a framework library
8
+ class mcp:
9
+ def tool(func):
10
+ return func
11
+
12
+ def _run_r_script(r_script_content: str, args: List[str]) -> Dict[str, Any]:
13
+ """
14
+ A helper function to execute an R script using Rscript, handling errors.
15
+
16
+ This function requires that R and the required Bioconductor packages
17
+ (e.g., ensembldb, AnnotationFilter) are installed in the execution environment.
18
+
19
+ Args:
20
+ r_script_content: A string containing the R code to execute.
21
+ args: A list of command-line arguments for the R script.
22
+
23
+ Returns:
24
+ A dictionary containing the executed command, stdout, and stderr.
25
+
26
+ Raises:
27
+ RuntimeError: If Rscript is not found in the system's PATH.
28
+ subprocess.CalledProcessError: If the R script execution fails.
29
+ """
30
+ try:
31
+ with tempfile.NamedTemporaryFile(mode='w', suffix=".R", delete=False, encoding='utf-8') as tmp_script:
32
+ script_path = Path(tmp_script.name)
33
+ tmp_script.write(r_script_content)
34
+
35
+ command = ["Rscript", str(script_path)] + args
36
+
37
+ process = subprocess.run(
38
+ command,
39
+ check=True,
40
+ capture_output=True,
41
+ text=True,
42
+ encoding='utf-8'
43
+ )
44
+ return {
45
+ "command_executed": " ".join(command),
46
+ "stdout": process.stdout,
47
+ "stderr": process.stderr
48
+ }
49
+ except FileNotFoundError:
50
+ raise RuntimeError("Rscript not found. Please ensure R is installed and in your PATH.")
51
+ except subprocess.CalledProcessError as e:
52
+ error_message = (
53
+ f"R script execution failed with exit code {e.returncode}.\n"
54
+ f"Command: {' '.join(e.cmd)}\n"
55
+ f"Stdout: {e.stdout}\n"
56
+ f"Stderr: {e.stderr}"
57
+ )
58
+ # Re-raise with a more informative stderr
59
+ raise subprocess.CalledProcessError(e.returncode, e.cmd, output=e.stdout, stderr=error_message)
60
+ finally:
61
+ if 'script_path' in locals() and script_path.exists():
62
+ script_path.unlink()
63
+
64
+ @mcp.tool
65
+ def create_ensdb_from_gtf(
66
+ gtf_file: Path,
67
+ output_db: Path,
68
+ organism: str,
69
+ genome_version: str,
70
+ ensembl_version: str,
71
+ ) -> Dict[str, Any]:
72
+ """
73
+ Creates an EnsemblDB SQLite database from a GTF file.
74
+
75
+ This tool wraps the `ensDbFromGtf` function from the R/Bioconductor
76
+ package 'ensembldb'. It requires R and the 'ensembldb' package to be
77
+ installed in the environment.
78
+
79
+ Args:
80
+ gtf_file: Path to the input GTF file.
81
+ output_db: Path for the output SQLite database file.
82
+ organism: Name of the organism (e.g., 'Homo_sapiens').
83
+ genome_version: Genome build version (e.g., 'GRCh38').
84
+ ensembl_version: Ensembl release version (e.g., '104').
85
+
86
+ Returns:
87
+ A dictionary containing the command executed, stdout, stderr,
88
+ and a list of output files.
89
+ """
90
+ # Input validation
91
+ if not gtf_file.is_file():
92
+ raise FileNotFoundError(f"Input GTF file not found: {gtf_file}")
93
+ if not output_db.parent.is_dir():
94
+ raise NotADirectoryError(f"Output directory does not exist: {output_db.parent}")
95
+ if not all([organism, genome_version, ensembl_version]):
96
+ raise ValueError("organism, genome_version, and ensembl_version must be non-empty strings.")
97
+
98
+ r_script = textwrap.dedent("""
99
+ library("ensembldb")
100
+ args <- commandArgs(trailingOnly = TRUE)
101
+ ensDbFromGtf(
102
+ gtf = args[1],
103
+ outfile = args[2],
104
+ organism = args[3],
105
+ genomeVersion = args[4],
106
+ version = args[5]
107
+ )
108
+ """)
109
+
110
+ args = [
111
+ str(gtf_file),
112
+ str(output_db),
113
+ organism,
114
+ genome_version,
115
+ ensembl_version
116
+ ]
117
+
118
+ result = _run_r_script(r_script, args)
119
+ result["output_files"] = [str(output_db)]
120
+ return result
121
+
122
+ @mcp.tool
123
+ def create_ensdb_from_gff(
124
+ gff_file: Path,
125
+ output_db: Path,
126
+ organism: str,
127
+ genome_version: str,
128
+ ensembl_version: str,
129
+ ) -> Dict[str, Any]:
130
+ """
131
+ Creates an EnsemblDB SQLite database from a GFF3 file.
132
+
133
+ This tool wraps the `ensDbFromGff` function from the R/Bioconductor
134
+ package 'ensembldb'. It requires R and the 'ensembldb' package to be
135
+ installed in the environment.
136
+
137
+ Args:
138
+ gff_file: Path to the input GFF3 file.
139
+ output_db: Path for the output SQLite database file.
140
+ organism: Name of the organism (e.g., 'Homo_sapiens').
141
+ genome_version: Genome build version (e.g., 'GRCh38').
142
+ ensembl_version: Ensembl release version (e.g., '104').
143
+
144
+ Returns:
145
+ A dictionary containing the command executed, stdout, stderr,
146
+ and a list of output files.
147
+ """
148
+ # Input validation
149
+ if not gff_file.is_file():
150
+ raise FileNotFoundError(f"Input GFF file not found: {gff_file}")
151
+ if not output_db.parent.is_dir():
152
+ raise NotADirectoryError(f"Output directory does not exist: {output_db.parent}")
153
+ if not all([organism, genome_version, ensembl_version]):
154
+ raise ValueError("organism, genome_version, and ensembl_version must be non-empty strings.")
155
+
156
+ r_script = textwrap.dedent("""
157
+ library("ensembldb")
158
+ args <- commandArgs(trailingOnly = TRUE)
159
+ ensDbFromGff(
160
+ gff = args[1],
161
+ outfile = args[2],
162
+ organism = args[3],
163
+ genomeVersion = args[4],
164
+ version = args[5]
165
+ )
166
+ """)
167
+
168
+ args = [
169
+ str(gff_file),
170
+ str(output_db),
171
+ organism,
172
+ genome_version,
173
+ ensembl_version
174
+ ]
175
+
176
+ result = _run_r_script(r_script, args)
177
+ result["output_files"] = [str(output_db)]
178
+ return result
179
+
180
+ def _build_query_script(query_function: str, extra_r_code: str = "") -> str:
181
+ """Helper to generate the R script for various query types."""
182
+ return textwrap.dedent(f"""
183
+ library("ensembldb")
184
+ library("AnnotationFilter")
185
+
186
+ args <- commandArgs(trailingOnly = TRUE)
187
+
188
+ parse_args <- function(args) {{
189
+ params <- list()
190
+ for (arg in args) {{
191
+ if (startsWith(arg, "--")) {{
192
+ parts <- strsplit(substring(arg, 3), "=", fixed = TRUE)[[1]]
193
+ key <- parts[1]
194
+ value <- if (length(parts) > 1) parts[2] else TRUE
195
+ params[[key]] <- value
196
+ }}
197
+ }}
198
+ return(params)
199
+ }}
200
+
201
+ params <- parse_args(args)
202
+
203
+ if (is.null(params$db) || is.null(params$outfile)) {{
204
+ stop("Both --db and --outfile arguments are required.")
205
+ }}
206
+
207
+ edb <- EnsDb(params$db)
208
+
209
+ filter_list <- list()
210
+ if (!is.null(params$filter_gene_id)) {{
211
+ filter_list <- c(filter_list, GeneIdFilter(params$filter_gene_id))
212
+ }}
213
+ if (!is.null(params$filter_gene_biotype)) {{
214
+ filter_list <- c(filter_list, GeneBiotypeFilter(params$filter_gene_biotype))
215
+ }}
216
+ if (!is.null(params$filter_seq_name)) {{
217
+ filter_list <- c(filter_list, SeqNameFilter(params$filter_seq_name))
218
+ }}
219
+ if (!is.null(params$filter_tx_id)) {{
220
+ filter_list <- c(filter_list, TxIdFilter(params$filter_tx_id))
221
+ }}
222
+ if (!is.null(params$filter_tx_biotype)) {{
223
+ filter_list <- c(filter_list, TxBiotypeFilter(params$filter_tx_biotype))
224
+ }}
225
+ if (!is.null(params$filter_exon_id)) {{
226
+ filter_list <- c(filter_list, ExonIdFilter(params$filter_exon_id))
227
+ }}
228
+
229
+ final_filter <- NULL
230
+ if (length(filter_list) > 0) {{
231
+ final_filter <- AnnotationFilterList(filter_list, logicOp = "&")
232
+ }}
233
+
234
+ {extra_r_code}
235
+
236
+ results <- {query_function}(edb, filter = final_filter)
237
+
238
+ write.table(as.data.frame(results), file = params$outfile, sep = "\t", row.names = FALSE, quote = FALSE)
239
+
240
+ cat("Successfully wrote query results to:", params$outfile, "\n")
241
+ """)
242
+
243
+ @mcp.tool
244
+ def query_genes(
245
+ db_file: Path,
246
+ output_tsv: Path,
247
+ filter_gene_id: Optional[str] = None,
248
+ filter_gene_biotype: Optional[str] = None,
249
+ filter_seq_name: Optional[str] = None,
250
+ ) -> Dict[str, Any]:
251
+ """
252
+ Queries gene information from an EnsemblDB SQLite database.
253
+
254
+ This tool wraps the `genes` function from 'ensembldb'. It requires R,
255
+ 'ensembldb', and 'AnnotationFilter' packages.
256
+
257
+ Args:
258
+ db_file: Path to the input EnsemblDB SQLite file.
259
+ output_tsv: Path for the output TSV file.
260
+ filter_gene_id: Optional filter by Ensembl gene ID.
261
+ filter_gene_biotype: Optional filter by gene biotype (e.g., 'protein_coding').
262
+ filter_seq_name: Optional filter by sequence/chromosome name (e.g., 'X').
263
+
264
+ Returns:
265
+ A dictionary containing the command executed, stdout, stderr,
266
+ and a list of output files.
267
+ """
268
+ if not db_file.is_file():
269
+ raise FileNotFoundError(f"Input database file not found: {db_file}")
270
+ if not output_tsv.parent.is_dir():
271
+ raise NotADirectoryError(f"Output directory does not exist: {output_tsv.parent}")
272
+
273
+ r_script = _build_query_script("genes")
274
+
275
+ args = [f"--db={db_file}", f"--outfile={output_tsv}"]
276
+ if filter_gene_id:
277
+ args.append(f"--filter_gene_id={filter_gene_id}")
278
+ if filter_gene_biotype:
279
+ args.append(f"--filter_gene_biotype={filter_gene_biotype}")
280
+ if filter_seq_name:
281
+ args.append(f"--filter_seq_name={filter_seq_name}")
282
+
283
+ result = _run_r_script(r_script, args)
284
+ result["output_files"] = [str(output_tsv)]
285
+ return result
286
+
287
+ @mcp.tool
288
+ def query_transcripts(
289
+ db_file: Path,
290
+ output_tsv: Path,
291
+ filter_gene_id: Optional[str] = None,
292
+ filter_tx_id: Optional[str] = None,
293
+ filter_tx_biotype: Optional[str] = None,
294
+ ) -> Dict[str, Any]:
295
+ """
296
+ Queries transcript information from an EnsemblDB SQLite database.
297
+
298
+ This tool wraps the `transcripts` function from 'ensembldb'. It requires R,
299
+ 'ensembldb', and 'AnnotationFilter' packages.
300
+
301
+ Args:
302
+ db_file: Path to the input EnsemblDB SQLite file.
303
+ output_tsv: Path for the output TSV file.
304
+ filter_gene_id: Optional filter by Ensembl gene ID.
305
+ filter_tx_id: Optional filter by Ensembl transcript ID.
306
+ filter_tx_biotype: Optional filter by transcript biotype (e.g., 'protein_coding').
307
+
308
+ Returns:
309
+ A dictionary containing the command executed, stdout, stderr,
310
+ and a list of output files.
311
+ """
312
+ if not db_file.is_file():
313
+ raise FileNotFoundError(f"Input database file not found: {db_file}")
314
+ if not output_tsv.parent.is_dir():
315
+ raise NotADirectoryError(f"Output directory does not exist: {output_tsv.parent}")
316
+
317
+ r_script = _build_query_script("transcripts")
318
+
319
+ args = [f"--db={db_file}", f"--outfile={output_tsv}"]
320
+ if filter_gene_id:
321
+ args.append(f"--filter_gene_id={filter_gene_id}")
322
+ if filter_tx_id:
323
+ args.append(f"--filter_tx_id={filter_tx_id}")
324
+ if filter_tx_biotype:
325
+ args.append(f"--filter_tx_biotype={filter_tx_biotype}")
326
+
327
+ result = _run_r_script(r_script, args)
328
+ result["output_files"] = [str(output_tsv)]
329
+ return result
330
+
331
+ @mcp.tool
332
+ def query_exons(
333
+ db_file: Path,
334
+ output_tsv: Path,
335
+ filter_gene_id: Optional[str] = None,
336
+ filter_tx_id: Optional[str] = None,
337
+ filter_exon_id: Optional[str] = None,
338
+ ) -> Dict[str, Any]:
339
+ """
340
+ Queries exon information from an EnsemblDB SQLite database.
341
+
342
+ This tool wraps the `exons` function from 'ensembldb'. It requires R,
343
+ 'ensembldb', and 'AnnotationFilter' packages.
344
+
345
+ Args:
346
+ db_file: Path to the input EnsemblDB SQLite file.
347
+ output_tsv: Path for the output TSV file.
348
+ filter_gene_id: Optional filter by Ensembl gene ID.
349
+ filter_tx_id: Optional filter by Ensembl transcript ID.
350
+ filter_exon_id: Optional filter by Ensembl exon ID.
351
+
352
+ Returns:
353
+ A dictionary containing the command executed, stdout, stderr,
354
+ and a list of output files.
355
+ """
356
+ if not db_file.is_file():
357
+ raise FileNotFoundError(f"Input database file not found: {db_file}")
358
+ if not output_tsv.parent.is_dir():
359
+ raise NotADirectoryError(f"Output directory does not exist: {output_tsv.parent}")
360
+
361
+ r_script = _build_query_script("exons")
362
+
363
+ args = [f"--db={db_file}", f"--outfile={output_tsv}"]
364
+ if filter_gene_id:
365
+ args.append(f"--filter_gene_id={filter_gene_id}")
366
+ if filter_tx_id:
367
+ args.append(f"--filter_tx_id={filter_tx_id}")
368
+ if filter_exon_id:
369
+ args.append(f"--filter_exon_id={filter_exon_id}")
370
+
371
+ result = _run_r_script(r_script, args)
372
+ result["output_files"] = [str(output_tsv)]
373
+ return result
374
+
375
+ @mcp.tool
376
+ def query_promoters(
377
+ db_file: Path,
378
+ output_tsv: Path,
379
+ upstream: int = 2000,
380
+ downstream: int = 200,
381
+ filter_gene_id: Optional[str] = None,
382
+ filter_tx_id: Optional[str] = None,
383
+ ) -> Dict[str, Any]:
384
+ """
385
+ Extracts promoter regions for transcripts from an EnsemblDB.
386
+
387
+ This tool wraps the `promoters` function from 'ensembldb'. It requires R,
388
+ 'ensembldb', and 'AnnotationFilter' packages.
389
+
390
+ Args:
391
+ db_file: Path to the input EnsemblDB SQLite file.
392
+ output_tsv: Path for the output TSV file.
393
+ upstream: The number of bases upstream of the TSS to include.
394
+ downstream: The number of bases downstream of the TSS to include.
395
+ filter_gene_id: Optional filter by Ensembl gene ID.
396
+ filter_tx_id: Optional filter by Ensembl transcript ID.
397
+
398
+ Returns:
399
+ A dictionary containing the command executed, stdout, stderr,
400
+ and a list of output files.
401
+ """
402
+ if not db_file.is_file():
403
+ raise FileNotFoundError(f"Input database file not found: {db_file}")
404
+ if not output_tsv.parent.is_dir():
405
+ raise NotADirectoryError(f"Output directory does not exist: {output_tsv.parent}")
406
+ if upstream < 0 or downstream < 0:
407
+ raise ValueError("upstream and downstream values must be non-negative.")
408
+
409
+ # The 'promoters' function takes upstream/downstream as direct arguments,
410
+ # so we modify the R script generation slightly.
411
+ extra_r_code = textwrap.dedent(f"""
412
+ up <- as.numeric(params$upstream)
413
+ down <- as.numeric(params$downstream)
414
+ results <- promoters(edb, upstream = up, downstream = down, filter = final_filter)
415
+ """)
416
+
417
+ # We remove the final `results <- ...` line from the base template
418
+ base_script = _build_query_script("", extra_r_code)
419
+
420
+ args = [
421
+ f"--db={db_file}",
422
+ f"--outfile={output_tsv}",
423
+ f"--upstream={upstream}",
424
+ f"--downstream={downstream}"
425
+ ]
426
+ if filter_gene_id:
427
+ args.append(f"--filter_gene_id={filter_gene_id}")
428
+ if filter_tx_id:
429
+ args.append(f"--filter_tx_id={filter_tx_id}")
430
+
431
+ result = _run_r_script(base_script, args)
432
+ result["output_files"] = [str(output_tsv)]
433
+ return result
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/app/bioconductor-ensembldb_shim_server.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/app/bioconductor-ensembldb_server.py')
11
+ SERVER_NAME = 'biosci_bioconductor_ensembldb'
12
+
13
+
14
+ class _ShimMCP:
15
+ @staticmethod
16
+ def tool():
17
+ def _decorator(fn):
18
+ return fn
19
+ return _decorator
20
+
21
+
22
+ def _load_functions():
23
+ code = SOURCE_SERVER.read_text(encoding="utf-8")
24
+ tree = ast.parse(code, filename=str(SOURCE_SERVER))
25
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
26
+ namespace = {
27
+ "__name__": "__mcp_source__",
28
+ "mcp": _ShimMCP(),
29
+ }
30
+ exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace)
31
+ loaded = []
32
+ for name in function_names:
33
+ fn = namespace.get(name)
34
+ if callable(fn):
35
+ loaded.append(fn)
36
+ return loaded
37
+
38
+
39
+ mcp = FastMCP(SERVER_NAME)
40
+ for _fn in _load_functions():
41
+ mcp.tool()(_fn)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ mcp.run(transport="stdio")
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-bioconductor-ensembldb:
5
+ build: .
6
+ image: mcp-bioconductor-ensembldb:latest
7
+ container_name: mcp-bioconductor-ensembldb
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=bioconductor-ensembldb
12
+ volumes:
13
+ - ./workspace:/app/workspace
14
+ - ./output:/app/output
15
+ restart: unless-stopped
16
+ healthcheck:
17
+ test: ["CMD", "python", "-c", "import sys; sys.exit(0)"]
18
+ interval: 30s
19
+ timeout: 10s
20
+ retries: 3
21
+ start_period: 5s
22
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/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-ensembldb
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-ensembldb/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/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-erma via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bioconductor-erma -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-erma_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-erma_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-erma_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/app/bioconductor-erma_server.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import logging
3
+ from pathlib import Path
4
+ from typing import List, Optional
5
+
6
+ # Configure basic logging
7
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
8
+
9
+ # This is a placeholder for the MCP decorator.
10
+ # In a real MCP environment, this would be provided by the MCP framework.
11
+ class mcp:
12
+ @staticmethod
13
+ def tool():
14
+ def decorator(func):
15
+ return func
16
+ return decorator
17
+
18
+ @mcp.tool()
19
+ def run_erma_script(
20
+ script_path: Path,
21
+ output_dir: Path,
22
+ args: Optional[List[str]] = None,
23
+ ):
24
+ """
25
+ Executes a user-provided R script in an environment with bioconductor-erma.
26
+
27
+ The 'bioconductor-erma' package is an R library for epigenomic data analysis
28
+ and does not provide a direct command-line interface. This tool serves as a
29
+ generic wrapper to execute R scripts that utilize the 'erma' library. The
30
+ user's script is responsible for implementing the analysis logic and writing
31
+ any output files to the specified directory.
32
+
33
+ Args:
34
+ script_path: The path to the R script to be executed.
35
+ output_dir: The path to the directory where the R script is expected to
36
+ write its output files. This directory will be created if it
37
+ does not exist.
38
+ args: An optional list of command-line arguments to be passed to the
39
+ R script.
40
+ """
41
+ # 1. Input Validation
42
+ if not script_path.is_file():
43
+ raise FileNotFoundError(f"The specified R script does not exist: {script_path}")
44
+
45
+ # 2. File Path Handling
46
+ try:
47
+ output_dir.mkdir(parents=True, exist_ok=True)
48
+ except OSError as e:
49
+ logging.error(f"Failed to create output directory {output_dir}: {e}")
50
+ raise
51
+
52
+ # 3. Command Construction
53
+ command = ["Rscript", "--vanilla", str(script_path)]
54
+ if args:
55
+ command.extend([str(arg) for arg in args])
56
+
57
+ command_executed = " ".join(command)
58
+ logging.info(f"Executing command: {command_executed}")
59
+
60
+ # 4. Subprocess Execution and Error Handling
61
+ try:
62
+ result = subprocess.run(
63
+ command,
64
+ capture_output=True,
65
+ text=True,
66
+ check=True,
67
+ cwd=output_dir, # Execute the script from the output directory
68
+ )
69
+ stdout = result.stdout
70
+ stderr = result.stderr
71
+ logging.info("R script executed successfully.")
72
+
73
+ except FileNotFoundError:
74
+ error_message = "Error: 'Rscript' command not found. Please ensure R is installed and accessible in the system's PATH."
75
+ logging.error(error_message)
76
+ return {
77
+ "command_executed": command_executed,
78
+ "stdout": "",
79
+ "stderr": error_message,
80
+ "output_files": []
81
+ }
82
+
83
+ except subprocess.CalledProcessError as e:
84
+ logging.error(f"R script failed with exit code {e.returncode}.")
85
+ logging.error(f"STDOUT: {e.stdout}")
86
+ logging.error(f"STDERR: {e.stderr}")
87
+ return {
88
+ "command_executed": command_executed,
89
+ "stdout": e.stdout,
90
+ "stderr": e.stderr,
91
+ "output_files": []
92
+ }
93
+
94
+ # 5. Structured Result Return
95
+ try:
96
+ output_files = [str(f) for f in output_dir.iterdir() if f.is_file()]
97
+ except OSError as e:
98
+ logging.error(f"Error listing output files in {output_dir}: {e}")
99
+ # Append this error to stderr to inform the user about the issue
100
+ stderr += f"\n[MCP Wrapper Error] Could not list output files: {e}"
101
+ output_files = []
102
+
103
+ return {
104
+ "command_executed": command_executed,
105
+ "stdout": stdout,
106
+ "stderr": stderr,
107
+ "output_files": output_files
108
+ }
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/app/bioconductor-erma_shim_server.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/app/bioconductor-erma_server.py')
11
+ SERVER_NAME = 'biosci_bioconductor_erma'
12
+
13
+
14
+ class _ShimMCP:
15
+ @staticmethod
16
+ def tool():
17
+ def _decorator(fn):
18
+ return fn
19
+ return _decorator
20
+
21
+
22
+ def _load_functions():
23
+ code = SOURCE_SERVER.read_text(encoding="utf-8")
24
+ tree = ast.parse(code, filename=str(SOURCE_SERVER))
25
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
26
+ namespace = {
27
+ "__name__": "__mcp_source__",
28
+ "mcp": _ShimMCP(),
29
+ }
30
+ exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace)
31
+ loaded = []
32
+ for name in function_names:
33
+ fn = namespace.get(name)
34
+ if callable(fn):
35
+ loaded.append(fn)
36
+ return loaded
37
+
38
+
39
+ mcp = FastMCP(SERVER_NAME)
40
+ for _fn in _load_functions():
41
+ mcp.tool()(_fn)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ mcp.run(transport="stdio")
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-bioconductor-erma:
5
+ build: .
6
+ image: mcp-bioconductor-erma:latest
7
+ container_name: mcp-bioconductor-erma
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=bioconductor-erma
12
+ volumes:
13
+ - ./workspace:/app/workspace
14
+ - ./output:/app/output
15
+ restart: unless-stopped
16
+ healthcheck:
17
+ test: ["CMD", "python", "-c", "import sys; sys.exit(0)"]
18
+ interval: 30s
19
+ timeout: 10s
20
+ retries: 3
21
+ start_period: 5s
22
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/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-erma
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-erma/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/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-escher via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bioconductor-escher -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-escher_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-escher_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-escher_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/app/bioconductor-escher_server.py ADDED
@@ -0,0 +1,279 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import tempfile
3
+ from pathlib import Path
4
+ from typing import List, Optional
5
+
6
+ # MCP-decorated functions for the 'escher' command-line tool.
7
+ # Note: This implementation is for the Python 'escher' package, which provides a
8
+ # command-line interface. The 'bioconductor-escher' package is an R wrapper
9
+ # and does not have a corresponding command-line tool. It is assumed the
10
+ # Python tool was the intended target.
11
+
12
+
13
+ @mcp.tool()
14
+ def escher_convert(
15
+ input_files: List[Path],
16
+ output: Optional[Path] = None,
17
+ format: Optional[str] = None,
18
+ ):
19
+ """
20
+ Converts Escher maps (JSON) to SVG or PNG formats.
21
+
22
+ This tool wraps the 'escher convert' command.
23
+
24
+ Args:
25
+ input_files: A list of one or more Escher map files (JSON) to convert.
26
+ output: The output file or directory. If not provided, output is saved
27
+ next to the input files. If multiple inputs are given, this must
28
+ be a directory.
29
+ format: The output format ('svg' or 'png'). Overrides the output file
30
+ extension. Defaults to 'svg' if not determinable from output path.
31
+ """
32
+ # Input validation
33
+ if not input_files:
34
+ raise ValueError("At least one input file must be provided.")
35
+ for file_path in input_files:
36
+ if not file_path.is_file():
37
+ raise FileNotFoundError(f"Input file not found: {file_path}")
38
+
39
+ if format and format not in ["svg", "png"]:
40
+ raise ValueError("Invalid format. Must be 'svg' or 'png'.")
41
+
42
+ if len(input_files) > 1 and output and output.is_file():
43
+ raise ValueError(
44
+ "When multiple input files are provided, the output path must be a directory, not a file."
45
+ )
46
+
47
+ command = ["escher", "convert"]
48
+ command.extend(["--input", *[str(p) for p in input_files]])
49
+
50
+ output_format = "svg"
51
+ if format:
52
+ command.extend(["--format", format])
53
+ output_format = format
54
+ elif output and output.suffix in [".svg", ".png"]:
55
+ output_format = output.suffix[1:]
56
+
57
+ output_paths = []
58
+ if output:
59
+ command.extend(["--output", str(output)])
60
+ # Check if output is intended to be a directory
61
+ if output.is_dir() or (len(input_files) > 1) or (not output.suffix):
62
+ output.mkdir(parents=True, exist_ok=True)
63
+ for in_file in input_files:
64
+ output_paths.append(output / f"{in_file.stem}.{output_format}")
65
+ else:
66
+ # Output is a file
67
+ output.parent.mkdir(parents=True, exist_ok=True)
68
+ output_paths.append(output)
69
+ else:
70
+ # No output specified, save next to input
71
+ for in_file in input_files:
72
+ output_paths.append(in_file.with_suffix(f".{output_format}"))
73
+
74
+ try:
75
+ process = subprocess.run(
76
+ command,
77
+ check=True,
78
+ capture_output=True,
79
+ text=True,
80
+ )
81
+ return {
82
+ "command_executed": " ".join(command),
83
+ "stdout": process.stdout,
84
+ "stderr": process.stderr,
85
+ "output_files": [str(p) for p in output_paths if p.exists()],
86
+ }
87
+ except FileNotFoundError:
88
+ raise RuntimeError(
89
+ "Error: 'escher' command not found. Please ensure the escher package is installed and in your PATH."
90
+ )
91
+ except subprocess.CalledProcessError as e:
92
+ return {
93
+ "command_executed": " ".join(command),
94
+ "stdout": e.stdout,
95
+ "stderr": e.stderr,
96
+ "output_files": [],
97
+ }
98
+
99
+
100
+ @mcp.tool()
101
+ def escher_clear_cache():
102
+ """
103
+ Clears the Escher cache of downloaded maps and models.
104
+
105
+ This tool wraps the 'escher clear-cache' command.
106
+ """
107
+ command = ["escher", "clear-cache"]
108
+
109
+ try:
110
+ process = subprocess.run(
111
+ command,
112
+ check=True,
113
+ capture_output=True,
114
+ text=True,
115
+ )
116
+ return {
117
+ "command_executed": " ".join(command),
118
+ "stdout": process.stdout,
119
+ "stderr": process.stderr,
120
+ }
121
+ except FileNotFoundError:
122
+ raise RuntimeError(
123
+ "Error: 'escher' command not found. Please ensure the escher package is installed and in your PATH."
124
+ )
125
+ except subprocess.CalledProcessError as e:
126
+ return {
127
+ "command_executed": " ".join(command),
128
+ "stdout": e.stdout,
129
+ "stderr": e.stderr,
130
+ }
131
+
132
+
133
+ @mcp.tool()
134
+ def escher_run(
135
+ port: int = 7778,
136
+ host: str = "127.0.0.1",
137
+ no_cache: bool = False,
138
+ timeout: int = 30,
139
+ ):
140
+ """
141
+ Runs a new Escher server.
142
+
143
+ Warning: This command starts a long-running server process. The 'timeout'
144
+ parameter is used to terminate the server after a specified duration.
145
+ This tool is primarily for interactive use and may have limited utility
146
+ in an automated MCP environment. The --no-browser flag is always used.
147
+
148
+ Args:
149
+ port: The port to run the server on.
150
+ host: The host for the server.
151
+ no_cache: If True, do not cache Escher resources.
152
+ timeout: The maximum time in seconds to run the server before terminating.
153
+ """
154
+ if timeout <= 0:
155
+ raise ValueError("Timeout must be a positive integer.")
156
+
157
+ command = ["escher", "run", "--no-browser"]
158
+ command.extend(["--port", str(port)])
159
+ command.extend(["--host", host])
160
+ if no_cache:
161
+ command.append("--no-cache")
162
+
163
+ try:
164
+ process = subprocess.run(
165
+ command, capture_output=True, text=True, timeout=timeout
166
+ )
167
+ # This block is unlikely to be reached as the server runs indefinitely
168
+ return {
169
+ "command_executed": " ".join(command),
170
+ "stdout": process.stdout,
171
+ "stderr": process.stderr,
172
+ }
173
+ except FileNotFoundError:
174
+ raise RuntimeError(
175
+ "Error: 'escher' command not found. Please ensure the escher package is installed and in your PATH."
176
+ )
177
+ except subprocess.TimeoutExpired as e:
178
+ # This is the expected outcome for this tool in an MCP environment
179
+ return {
180
+ "command_executed": " ".join(command),
181
+ "stdout": e.stdout or "",
182
+ "stderr": e.stderr or f"Process terminated after {timeout}s timeout.",
183
+ }
184
+ except subprocess.CalledProcessError as e:
185
+ return {
186
+ "command_executed": " ".join(command),
187
+ "stdout": e.stdout,
188
+ "stderr": e.stderr,
189
+ }
190
+
191
+
192
+ @mcp.tool()
193
+ def escher_launch(
194
+ map_name: Optional[str] = None,
195
+ map_json: Optional[Path] = None,
196
+ model_name: Optional[str] = None,
197
+ model_json: Optional[Path] = None,
198
+ port: int = 7779,
199
+ host: str = "127.0.0.1",
200
+ no_cache: bool = False,
201
+ never_ask_before_quit: bool = False,
202
+ timeout: int = 30,
203
+ ):
204
+ """
205
+ Launches an Escher instance in a server, optionally loading a map/model.
206
+
207
+ Warning: This command starts a long-running server process. The 'timeout'
208
+ parameter is used to terminate the server after a specified duration.
209
+ This tool is primarily for interactive use and may have limited utility
210
+ in an automated MCP environment. The --no-browser flag is always used.
211
+
212
+ Args:
213
+ map_name: The name of the map to load from the Escher server.
214
+ map_json: A local JSON file for the map.
215
+ model_name: The name of the model to load from the Escher server.
216
+ model_json: A local JSON file for the model.
217
+ port: The port to run the server on.
218
+ host: The host for the server.
219
+ no_cache: If True, do not cache Escher resources.
220
+ never_ask_before_quit: If True, never ask "Are you sure you want to quit?".
221
+ timeout: The maximum time in seconds to run the server before terminating.
222
+ """
223
+ # Input validation
224
+ if map_name and map_json:
225
+ raise ValueError("'map_name' and 'map_json' are mutually exclusive.")
226
+ if model_name and model_json:
227
+ raise ValueError("'model_name' and 'model_json' are mutually exclusive.")
228
+ if map_json and not map_json.is_file():
229
+ raise FileNotFoundError(f"Map JSON file not found: {map_json}")
230
+ if model_json and not model_json.is_file():
231
+ raise FileNotFoundError(f"Model JSON file not found: {model_json}")
232
+ if timeout <= 0:
233
+ raise ValueError("Timeout must be a positive integer.")
234
+
235
+ command = ["escher", "launch", "--no-browser"]
236
+
237
+ if map_name:
238
+ command.extend(["--map_name", map_name])
239
+ if map_json:
240
+ command.extend(["--map_json", str(map_json)])
241
+ if model_name:
242
+ command.extend(["--model_name", model_name])
243
+ if model_json:
244
+ command.extend(["--model_json", str(model_json)])
245
+
246
+ command.extend(["--port", str(port)])
247
+ command.extend(["--host", host])
248
+
249
+ if no_cache:
250
+ command.append("--no-cache")
251
+ if never_ask_before_quit:
252
+ command.append("--never_ask_before_quit")
253
+
254
+ try:
255
+ process = subprocess.run(
256
+ command, capture_output=True, text=True, timeout=timeout
257
+ )
258
+ return {
259
+ "command_executed": " ".join(command),
260
+ "stdout": process.stdout,
261
+ "stderr": process.stderr,
262
+ }
263
+ except FileNotFoundError:
264
+ raise RuntimeError(
265
+ "Error: 'escher' command not found. Please ensure the escher package is installed and in your PATH."
266
+ )
267
+ except subprocess.TimeoutExpired as e:
268
+ # This is the expected outcome for this tool in an MCP environment
269
+ return {
270
+ "command_executed": " ".join(command),
271
+ "stdout": e.stdout or "",
272
+ "stderr": e.stderr or f"Process terminated after {timeout}s timeout.",
273
+ }
274
+ except subprocess.CalledProcessError as e:
275
+ return {
276
+ "command_executed": " ".join(command),
277
+ "stdout": e.stdout,
278
+ "stderr": e.stderr,
279
+ }
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/app/bioconductor-escher_shim_server.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/app/bioconductor-escher_server.py')
11
+ SERVER_NAME = 'biosci_bioconductor_escher'
12
+
13
+
14
+ class _ShimMCP:
15
+ @staticmethod
16
+ def tool():
17
+ def _decorator(fn):
18
+ return fn
19
+ return _decorator
20
+
21
+
22
+ def _load_functions():
23
+ code = SOURCE_SERVER.read_text(encoding="utf-8")
24
+ tree = ast.parse(code, filename=str(SOURCE_SERVER))
25
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
26
+ namespace = {
27
+ "__name__": "__mcp_source__",
28
+ "mcp": _ShimMCP(),
29
+ }
30
+ exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace)
31
+ loaded = []
32
+ for name in function_names:
33
+ fn = namespace.get(name)
34
+ if callable(fn):
35
+ loaded.append(fn)
36
+ return loaded
37
+
38
+
39
+ mcp = FastMCP(SERVER_NAME)
40
+ for _fn in _load_functions():
41
+ mcp.tool()(_fn)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ mcp.run(transport="stdio")
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-bioconductor-escher:
5
+ build: .
6
+ image: mcp-bioconductor-escher:latest
7
+ container_name: mcp-bioconductor-escher
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=bioconductor-escher
12
+ volumes:
13
+ - ./workspace:/app/workspace
14
+ - ./output:/app/output
15
+ restart: unless-stopped
16
+ healthcheck:
17
+ test: ["CMD", "python", "-c", "import sys; sys.exit(0)"]
18
+ interval: 30s
19
+ timeout: 10s
20
+ retries: 3
21
+ start_period: 5s
22
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/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-escher
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-escher/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/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-experimentsubset via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bioconductor-experimentsubset -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-experimentsubset_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-experimentsubset_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-experimentsubset_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/app/bioconductor-experimentsubset_server.py ADDED
@@ -0,0 +1,178 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import tempfile
3
+ from pathlib import Path
4
+ from typing import Optional, Dict, List
5
+
6
+ # This is a placeholder for the MCP decorator.
7
+ # In a real MCP environment, this would be provided by the MCP framework.
8
+ def mcp_tool_placeholder(*args, **kwargs):
9
+ def decorator(func):
10
+ return func
11
+ return decorator
12
+
13
+ mcp = type('mcp', (), {'tool': mcp_tool_placeholder})
14
+
15
+
16
+ @mcp.tool()
17
+ def manage_experiment_subset(
18
+ input_rds: Path,
19
+ output_rds: Path,
20
+ subset_name: str = "mcp_subset",
21
+ row_subset: Optional[str] = None,
22
+ col_subset: Optional[str] = None,
23
+ row_subset_file: Optional[Path] = None,
24
+ col_subset_file: Optional[Path] = None,
25
+ ) -> Dict[str, any]:
26
+ """
27
+ Provides a command-line interface to the R/Bioconductor 'ExperimentSubset' package.
28
+
29
+ This tool subsets a Bioconductor experiment object (e.g., SummarizedExperiment,
30
+ SingleCellExperiment) stored in an RDS file based on provided row (e.g., genes)
31
+ or column (e.g., cells) identifiers.
32
+
33
+ Args:
34
+ input_rds: Path to the input RDS file containing a Bioconductor experiment object.
35
+ output_rds: Path to save the output subsetted RDS file.
36
+ subset_name: A name to assign to the created subset.
37
+ row_subset: A comma-separated string of row names to include in the subset.
38
+ col_subset: A comma-separated string of column names to include in the subset.
39
+ row_subset_file: Path to a file containing row names to include (one per line).
40
+ col_subset_file: Path to a file containing column names to include (one per line).
41
+
42
+ Returns:
43
+ A dictionary containing the execution command, stdout, stderr, and a list of output files.
44
+ """
45
+ # --- Input Validation ---
46
+ if not input_rds.exists():
47
+ raise FileNotFoundError(f"Input file not found: {input_rds}")
48
+
49
+ if row_subset and row_subset_file:
50
+ raise ValueError("Cannot specify both 'row_subset' and 'row_subset_file'.")
51
+
52
+ if col_subset and col_subset_file:
53
+ raise ValueError("Cannot specify both 'col_subset' and 'col_subset_file'.")
54
+
55
+ if not any([row_subset, col_subset, row_subset_file, col_subset_file]):
56
+ raise ValueError("At least one subsetting criterion must be provided "
57
+ "('row_subset', 'col_subset', 'row_subset_file', or 'col_subset_file').")
58
+
59
+ if not output_rds.parent.exists():
60
+ output_rds.parent.mkdir(parents=True, exist_ok=True)
61
+
62
+ # --- R Script Generation ---
63
+ r_script_content = f"""
64
+ # Load required libraries
65
+ if (!require("optparse", quietly = TRUE)) install.packages("optparse", repos = "http://cran.us.r-project.org")
66
+ if (!require("ExperimentSubset", quietly = TRUE)) {{
67
+ if (!require("BiocManager", quietly = TRUE)) install.packages("BiocManager", repos = "http://cran.us.r-project.org")
68
+ BiocManager::install("ExperimentSubset", update=FALSE)
69
+ }}
70
+ library(optparse)
71
+ library(ExperimentSubset)
72
+
73
+ # Define and parse command-line options
74
+ option_list <- list(
75
+ make_option(c("-i", "--input"), type="character", help="Input RDS file path"),
76
+ make_option(c("-o", "--output"), type="character", help="Output RDS file path"),
77
+ make_option(c("-n", "--name"), type="character", default="mcp_subset", help="Name for the subset"),
78
+ make_option(c("-r", "--rows"), type="character", default=NULL, help="Comma-separated row names"),
79
+ make_option(c("-c", "--cols"), type="character", default=NULL, help="Comma-separated column names"),
80
+ make_option(c("--row_file"), type="character", default=NULL, help="File with row names"),
81
+ make_option(c("--col_file"), type="character", default=NULL, help="File with column names")
82
+ )
83
+
84
+ opt_parser <- OptionParser(option_list=option_list)
85
+ opt <- parse_args(opt_parser)
86
+
87
+ if (is.null(opt$input) || is.null(opt$output)) {{
88
+ print_help(opt_parser)
89
+ stop("Input and output files must be supplied.", call.=FALSE)
90
+ }}
91
+
92
+ # Load the experiment object
93
+ cat("Loading input RDS file:", opt$input, "\\n")
94
+ exp_obj <- readRDS(opt$input)
95
+
96
+ # Create ExperimentSubset object
97
+ es <- ExperimentSubset(exp_obj)
98
+
99
+ # Determine row and column subsets
100
+ row_indices <- NULL
101
+ if (!is.null(opt$rows)) {{
102
+ row_indices <- trimws(strsplit(opt$rows, ",")[[1]])
103
+ }} else if (!is.null(opt$row_file)) {{
104
+ row_indices <- readLines(opt$row_file)
105
+ }}
106
+
107
+ col_indices <- NULL
108
+ if (!is.null(opt$cols)) {{
109
+ col_indices <- trimws(strsplit(opt$cols, ",")[[1]])
110
+ }} else if (!is.null(opt$col_file)) {{
111
+ col_indices <- readLines(opt$col_file)
112
+ }}
113
+
114
+ # Create the subset using the subsetData function
115
+ cat("Creating subset '", opt$name, "'...\\n", sep="")
116
+ es <- subsetData(es, subsetName = opt$name, rows = row_indices, cols = col_indices)
117
+
118
+ # Retrieve the actual subsetted object from the container
119
+ subset_obj <- getSubset(es, subsetName = opt$name)
120
+
121
+ # Save the subsetted object
122
+ cat("Saving subsetted object to:", opt$output, "\\n")
123
+ saveRDS(subset_obj, file = opt$output)
124
+
125
+ cat("Successfully created subset.\\n")
126
+ """
127
+
128
+ # --- Subprocess Execution ---
129
+ cmd: List[str] = []
130
+ try:
131
+ with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix=".R") as r_script_file:
132
+ r_script_file.write(r_script_content)
133
+ r_script_path = r_script_file.name
134
+
135
+ cmd = [
136
+ "Rscript", r_script_path,
137
+ "--input", str(input_rds),
138
+ "--output", str(output_rds),
139
+ "--name", subset_name
140
+ ]
141
+
142
+ if row_subset:
143
+ cmd.extend(["--rows", row_subset])
144
+ if col_subset:
145
+ cmd.extend(["--cols", col_subset])
146
+ if row_subset_file:
147
+ cmd.extend(["--row_file", str(row_subset_file)])
148
+ if col_subset_file:
149
+ cmd.extend(["--col_file", str(col_subset_file)])
150
+
151
+ result = subprocess.run(
152
+ cmd,
153
+ capture_output=True,
154
+ text=True,
155
+ check=True
156
+ )
157
+
158
+ return {
159
+ "command_executed": " ".join(cmd),
160
+ "stdout": result.stdout,
161
+ "stderr": result.stderr,
162
+ "output_files": [str(output_rds)]
163
+ }
164
+
165
+ except FileNotFoundError:
166
+ raise RuntimeError("Rscript not found. Please ensure R is installed and in your system's PATH.")
167
+ except subprocess.CalledProcessError as e:
168
+ return {
169
+ "command_executed": " ".join(cmd),
170
+ "stdout": e.stdout,
171
+ "stderr": e.stderr,
172
+ "error": "R script execution failed.",
173
+ "return_code": e.returncode
174
+ }
175
+ finally:
176
+ # Clean up the temporary R script
177
+ if 'r_script_path' in locals() and Path(r_script_path).exists():
178
+ Path(r_script_path).unlink()
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/app/bioconductor-experimentsubset_shim_server.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/app/bioconductor-experimentsubset_server.py')
11
+ SERVER_NAME = 'biosci_bioconductor_experimentsubset'
12
+
13
+
14
+ class _ShimMCP:
15
+ @staticmethod
16
+ def tool():
17
+ def _decorator(fn):
18
+ return fn
19
+ return _decorator
20
+
21
+
22
+ def _load_functions():
23
+ code = SOURCE_SERVER.read_text(encoding="utf-8")
24
+ tree = ast.parse(code, filename=str(SOURCE_SERVER))
25
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
26
+ namespace = {
27
+ "__name__": "__mcp_source__",
28
+ "mcp": _ShimMCP(),
29
+ }
30
+ exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace)
31
+ loaded = []
32
+ for name in function_names:
33
+ fn = namespace.get(name)
34
+ if callable(fn):
35
+ loaded.append(fn)
36
+ return loaded
37
+
38
+
39
+ mcp = FastMCP(SERVER_NAME)
40
+ for _fn in _load_functions():
41
+ mcp.tool()(_fn)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ mcp.run(transport="stdio")
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-bioconductor-experimentsubset:
5
+ build: .
6
+ image: mcp-bioconductor-experimentsubset:latest
7
+ container_name: mcp-bioconductor-experimentsubset
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=bioconductor-experimentsubset
12
+ volumes:
13
+ - ./workspace:/app/workspace
14
+ - ./output:/app/output
15
+ restart: unless-stopped
16
+ healthcheck:
17
+ test: ["CMD", "python", "-c", "import sys; sys.exit(0)"]
18
+ interval: 30s
19
+ timeout: 10s
20
+ retries: 3
21
+ start_period: 5s
22
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/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-experimentsubset
9
+ - python=3.10
10
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-experimentsubset/requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ fastmcp
2
+ mcp
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/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-fgsea via conda (e.g., from bioconda)
14
+ RUN conda install -c bioconda bioconductor-fgsea -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-fgsea_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-fgsea_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-fgsea_server.py"]
40
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/app/bioconductor-fgsea_server.py ADDED
@@ -0,0 +1,421 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import subprocess
2
+ import tempfile
3
+ from pathlib import Path
4
+ from typing import Optional
5
+
6
+ # This is a dummy decorator for development.
7
+ # In a real MCP environment, 'mcp' would be an imported module.
8
+ class MCP:
9
+ def tool(self):
10
+ def decorator(f):
11
+ return f
12
+ return decorator
13
+ mcp = MCP()
14
+
15
+ R_DEPENDENCIES_NOTE = """
16
+ NOTE: This tool requires R to be installed and in the system's PATH.
17
+ It also requires the following R packages to be installed:
18
+ - BiocManager
19
+ - fgsea (from Bioconductor)
20
+ - data.table
21
+ - argparse
22
+ - ggplot2
23
+ - grid
24
+ You can install them in R with:
25
+ install.packages(c("data.table", "argparse", "ggplot2"))
26
+ if (!require("BiocManager", quietly = TRUE))
27
+ install.packages("BiocManager")
28
+ BiocManager::install("fgsea")
29
+ """
30
+
31
+ @mcp.tool()
32
+ def fgsea_run(
33
+ pathways_file: Path,
34
+ stats_file: Path,
35
+ min_size: int = 1,
36
+ max_size: Optional[int] = None,
37
+ eps: float = 1e-10,
38
+ score_type: str = "std",
39
+ n_proc: int = 0,
40
+ gsea_param: float = 1.0,
41
+ n_perm_simple: int = 1000,
42
+ abs_eps: Optional[float] = None,
43
+ seed: int = 42,
44
+ ) -> dict:
45
+ """
46
+ Runs Fast Gene Set Enrichment Analysis (fgsea).
47
+
48
+ This tool performs GSEA using the fgsea R package. It requires a pathways file
49
+ in GMT format and a file with pre-ranked gene-level statistics. The stats
50
+ file must be a two-column TSV/CSV with no header, containing gene IDs in the
51
+ first column and numeric stats in the second.
52
+
53
+ Args:
54
+ pathways_file: Path to the pathways file in GMT format.
55
+ stats_file: Path to the gene-level stats file (2-column, no header).
56
+ min_size: Minimal size of a pathway to be considered.
57
+ max_size: Maximal size of a pathway to be considered.
58
+ eps: Boundary for calculating p-values.
59
+ score_type: Type of score for multilevel GSEA ('std', 'pos', 'neg').
60
+ n_proc: Number of processors to use. 0 means automatic detection.
61
+ gsea_param: GSEA parameter (enrichment score weight).
62
+ n_perm_simple: Number of permutations for fgseaSimple.
63
+ abs_eps: Absolute epsilon for p-value calculation.
64
+ seed: Random seed for reproducibility.
65
+
66
+ Returns:
67
+ A dictionary containing the execution command, stdout, stderr, and
68
+ a path to the resulting TSV file.
69
+ """
70
+ # --- Input Validation ---
71
+ if not pathways_file.is_file():
72
+ raise FileNotFoundError(f"Pathways file not found: {pathways_file}")
73
+ if not stats_file.is_file():
74
+ raise FileNotFoundError(f"Stats file not found: {stats_file}")
75
+
76
+ if min_size < 0:
77
+ raise ValueError("min_size must be a non-negative integer.")
78
+ if max_size is not None and max_size < min_size:
79
+ raise ValueError("max_size must be greater than or equal to min_size.")
80
+ if eps <= 0:
81
+ raise ValueError("eps must be a positive float.")
82
+ if score_type not in ["std", "pos", "neg"]:
83
+ raise ValueError("score_type must be one of 'std', 'pos', or 'neg'.")
84
+ if n_proc < 0:
85
+ raise ValueError("n_proc must be a non-negative integer.")
86
+ if n_perm_simple <= 0:
87
+ raise ValueError("n_perm_simple must be a positive integer.")
88
+ if abs_eps is not None and abs_eps <= 0:
89
+ raise ValueError("abs_eps must be a positive float if provided.")
90
+
91
+ # --- R Script Definition ---
92
+ r_script_content = """
93
+ #!/usr/bin/env Rscript
94
+ library(argparse)
95
+ library(fgsea)
96
+ library(data.table)
97
+
98
+ parser <- ArgumentParser(description="Run fgsea analysis")
99
+ parser$add_argument("--pathways", type="character", required=TRUE)
100
+ parser$add_argument("--stats", type="character", required=TRUE)
101
+ parser$add_argument("--output", type="character", required=TRUE)
102
+ parser$add_argument("--minSize", type="integer", default=1)
103
+ parser$add_argument("--maxSize", type="integer", default=NULL)
104
+ parser$add_argument("--eps", type="double", default=1e-10)
105
+ parser$add_argument("--scoreType", type="character", default="std", choices=c("std", "pos", "neg"))
106
+ parser$add_argument("--nproc", type="integer", default=0)
107
+ parser$add_argument("--gseaParam", type="double", default=1.0)
108
+ parser$add_argument("--nPermSimple", type="integer", default=1000)
109
+ parser$add_argument("--absEps", type="double", default=NULL)
110
+ parser$add_argument("--seed", type="integer", default=42)
111
+ args <- parser$parse_args()
112
+
113
+ set.seed(args$seed)
114
+
115
+ pathways <- gmtPathways(args$pathways)
116
+
117
+ stats_df <- fread(args$stats, header=FALSE)
118
+ if (ncol(stats_df) != 2) {
119
+ stop("Stats file must have exactly two columns (gene, stat) with no header.")
120
+ }
121
+ stats <- setNames(stats_df[[2]], stats_df[[1]])
122
+ stats <- stats[!is.na(stats)]
123
+ stats <- sort(stats, decreasing=TRUE)
124
+
125
+ maxSize <- if (is.null(args$maxSize)) Inf else args$maxSize
126
+
127
+ fgseaRes <- fgsea(
128
+ pathways = pathways,
129
+ stats = stats,
130
+ minSize = args$minSize,
131
+ maxSize = maxSize,
132
+ eps = args$eps,
133
+ scoreType = args$scoreType,
134
+ nproc = args$nproc,
135
+ gseaParam = args$gseaParam,
136
+ nPermSimple = args$nPermSimple,
137
+ absEps = args$absEps
138
+ )
139
+
140
+ fwrite(fgseaRes, file=args$output, sep="\\t", quote=FALSE, row.names=FALSE)
141
+ cat("fgsea analysis completed successfully.\\n")
142
+ """
143
+
144
+ with tempfile.TemporaryDirectory() as temp_dir:
145
+ temp_path = Path(temp_dir)
146
+ r_script_path = temp_path / "run_fgsea.R"
147
+ r_script_path.write_text(r_script_content)
148
+
149
+ output_file = temp_path / "fgsea_results.tsv"
150
+
151
+ cmd = [
152
+ "Rscript", str(r_script_path),
153
+ "--pathways", str(pathways_file.resolve()),
154
+ "--stats", str(stats_file.resolve()),
155
+ "--output", str(output_file.resolve()),
156
+ "--minSize", str(min_size),
157
+ "--eps", str(eps),
158
+ "--scoreType", score_type,
159
+ "--nproc", str(n_proc),
160
+ "--gseaParam", str(gsea_param),
161
+ "--nPermSimple", str(n_perm_simple),
162
+ "--seed", str(seed),
163
+ ]
164
+
165
+ if max_size is not None:
166
+ cmd.extend(["--maxSize", str(max_size)])
167
+ if abs_eps is not None:
168
+ cmd.extend(["--absEps", str(abs_eps)])
169
+
170
+ # --- Subprocess Execution ---
171
+ try:
172
+ process = subprocess.run(
173
+ cmd, check=True, capture_output=True, text=True
174
+ )
175
+ except FileNotFoundError:
176
+ raise RuntimeError(f"Rscript not found. Please ensure R is installed and in your PATH. {R_DEPENDENCIES_NOTE}")
177
+ except subprocess.CalledProcessError as e:
178
+ error_message = (
179
+ f"fgsea execution failed with return code {e.returncode}.\n"
180
+ f"Command: {' '.join(cmd)}\n"
181
+ f"Stdout: {e.stdout}\n"
182
+ f"Stderr: {e.stderr}\n"
183
+ f"{R_DEPENDENCIES_NOTE}"
184
+ )
185
+ raise RuntimeError(error_message) from e
186
+
187
+ # --- Structured Result Return ---
188
+ return {
189
+ "command_executed": " ".join(cmd),
190
+ "stdout": process.stdout,
191
+ "stderr": process.stderr,
192
+ "output_files": {"results_table": str(output_file)}
193
+ }
194
+
195
+ @mcp.tool()
196
+ def fgsea_plot_enrichment(
197
+ pathways_file: Path,
198
+ stats_file: Path,
199
+ pathway_name: str,
200
+ gsea_param: float = 1.0,
201
+ ) -> dict:
202
+ """
203
+ Plots the GSEA enrichment score profile for a specific pathway.
204
+
205
+ Args:
206
+ pathways_file: Path to the pathways file in GMT format.
207
+ stats_file: Path to the gene-level stats file (2-column, no header).
208
+ pathway_name: Name of the specific pathway to plot.
209
+ gsea_param: GSEA parameter (enrichment score weight).
210
+
211
+ Returns:
212
+ A dictionary containing the execution command, stdout, stderr, and
213
+ a path to the resulting PDF plot.
214
+ """
215
+ # --- Input Validation ---
216
+ if not pathways_file.is_file():
217
+ raise FileNotFoundError(f"Pathways file not found: {pathways_file}")
218
+ if not stats_file.is_file():
219
+ raise FileNotFoundError(f"Stats file not found: {stats_file}")
220
+ if not pathway_name:
221
+ raise ValueError("pathway_name cannot be empty.")
222
+
223
+ # --- R Script Definition ---
224
+ r_script_content = """
225
+ #!/usr/bin/env Rscript
226
+ library(argparse)
227
+ library(fgsea)
228
+ library(data.table)
229
+ library(ggplot2)
230
+
231
+ parser <- ArgumentParser(description="Plot fgsea enrichment score")
232
+ parser$add_argument("--pathways", type="character", required=TRUE)
233
+ parser$add_argument("--stats", type="character", required=TRUE)
234
+ parser$add_argument("--pathway_name", type="character", required=TRUE)
235
+ parser$add_argument("--output", type="character", required=TRUE)
236
+ parser$add_argument("--gseaParam", type="double", default=1.0)
237
+ args <- parser$parse_args()
238
+
239
+ pathways <- gmtPathways(args$pathways)
240
+ stats_df <- fread(args$stats, header=FALSE)
241
+ if (ncol(stats_df) != 2) {
242
+ stop("Stats file must have exactly two columns (gene, stat) with no header.")
243
+ }
244
+ stats <- setNames(stats_df[[2]], stats_df[[1]])
245
+ stats <- stats[!is.na(stats)]
246
+
247
+ if (!args$pathway_name %in% names(pathways)) {
248
+ stop(paste("Pathway '", args$pathway_name, "' not found in the pathways file.", sep=""))
249
+ }
250
+ selected_pathway <- pathways[[args$pathway_name]]
251
+
252
+ p <- plotEnrichment(pathway=selected_pathway, stats=stats, gseaParam=args$gseaParam) +
253
+ labs(title=args$pathway_name)
254
+
255
+ ggsave(args$output, plot=p, device="pdf")
256
+ cat("Enrichment plot saved to", args$output, "\\n")
257
+ """
258
+
259
+ with tempfile.TemporaryDirectory() as temp_dir:
260
+ temp_path = Path(temp_dir)
261
+ r_script_path = temp_path / "plot_enrichment.R"
262
+ r_script_path.write_text(r_script_content)
263
+
264
+ safe_pathway_name = "".join(c for c in pathway_name if c.isalnum() or c in ('_', '-')).rstrip()
265
+ output_plot_file = temp_path / f"enrichment_plot_{safe_pathway_name}.pdf"
266
+
267
+ cmd = [
268
+ "Rscript", str(r_script_path),
269
+ "--pathways", str(pathways_file.resolve()),
270
+ "--stats", str(stats_file.resolve()),
271
+ "--pathway_name", pathway_name,
272
+ "--output", str(output_plot_file.resolve()),
273
+ "--gseaParam", str(gsea_param),
274
+ ]
275
+
276
+ # --- Subprocess Execution ---
277
+ try:
278
+ process = subprocess.run(
279
+ cmd, check=True, capture_output=True, text=True
280
+ )
281
+ except FileNotFoundError:
282
+ raise RuntimeError(f"Rscript not found. Please ensure R is installed and in your PATH. {R_DEPENDENCIES_NOTE}")
283
+ except subprocess.CalledProcessError as e:
284
+ error_message = (
285
+ f"fgsea plot enrichment failed with return code {e.returncode}.\n"
286
+ f"Command: {' '.join(cmd)}\n"
287
+ f"Stdout: {e.stdout}\n"
288
+ f"Stderr: {e.stderr}\n"
289
+ f"{R_DEPENDENCIES_NOTE}"
290
+ )
291
+ raise RuntimeError(error_message) from e
292
+
293
+ # --- Structured Result Return ---
294
+ return {
295
+ "command_executed": " ".join(cmd),
296
+ "stdout": process.stdout,
297
+ "stderr": process.stderr,
298
+ "output_files": {"enrichment_plot": str(output_plot_file)}
299
+ }
300
+
301
+ @mcp.tool()
302
+ def fgsea_plot_gsea_table(
303
+ pathways_file: Path,
304
+ stats_file: Path,
305
+ fgsea_results_file: Path,
306
+ top_n: int = 10,
307
+ gsea_param: float = 1.0,
308
+ ) -> dict:
309
+ """
310
+ Plots a table of top GSEA results.
311
+
312
+ Args:
313
+ pathways_file: Path to the pathways file in GMT format.
314
+ stats_file: Path to the gene-level stats file (2-column, no header).
315
+ fgsea_results_file: Path to the results TSV from a previous fgsea_run.
316
+ top_n: Number of top pathways (both up- and down-regulated) to plot.
317
+ gsea_param: GSEA parameter (enrichment score weight).
318
+
319
+ Returns:
320
+ A dictionary containing the execution command, stdout, stderr, and
321
+ a path to the resulting PDF plot.
322
+ """
323
+ # --- Input Validation ---
324
+ if not pathways_file.is_file():
325
+ raise FileNotFoundError(f"Pathways file not found: {pathways_file}")
326
+ if not stats_file.is_file():
327
+ raise FileNotFoundError(f"Stats file not found: {stats_file}")
328
+ if not fgsea_results_file.is_file():
329
+ raise FileNotFoundError(f"fgsea results file not found: {fgsea_results_file}")
330
+ if top_n <= 0:
331
+ raise ValueError("top_n must be a positive integer.")
332
+
333
+ # --- R Script Definition ---
334
+ r_script_content = """
335
+ #!/usr/bin/env Rscript
336
+ library(argparse)
337
+ library(fgsea)
338
+ library(data.table)
339
+ library(grid)
340
+
341
+ parser <- ArgumentParser(description="Plot fgsea results table")
342
+ parser$add_argument("--pathways", type="character", required=TRUE)
343
+ parser$add_argument("--stats", type="character", required=TRUE)
344
+ parser$add_argument("--results", type="character", required=TRUE)
345
+ parser$add_argument("--output", type="character", required=TRUE)
346
+ parser$add_argument("--top_n", type="integer", default=10)
347
+ parser$add_argument("--gseaParam", type="double", default=1.0)
348
+ args <- parser$parse_args()
349
+
350
+ pathways <- gmtPathways(args$pathways)
351
+ stats_df <- fread(args$stats, header=FALSE)
352
+ if (ncol(stats_df) != 2) {
353
+ stop("Stats file must have exactly two columns (gene, stat) with no header.")
354
+ }
355
+ stats <- setNames(stats_df[[2]], stats_df[[1]])
356
+ stats <- stats[!is.na(stats)]
357
+ fgseaRes <- fread(args$results)
358
+
359
+ topPathwaysUp <- fgseaRes[ES > 0][head(order(pval), n=args$top_n), pathway]
360
+ topPathwaysDown <- fgseaRes[ES < 0][head(order(pval), n=args$top_n), pathway]
361
+ topPathways <- c(topPathwaysUp, rev(topPathwaysDown))
362
+
363
+ if (length(topPathways) == 0) {
364
+ stop("No significant pathways found to plot.")
365
+ }
366
+
367
+ p <- plotGseaTable(
368
+ pathways = pathways[topPathways],
369
+ stats = stats,
370
+ fgseaRes = fgseaRes,
371
+ gseaParam = args$gseaParam
372
+ )
373
+
374
+ pdf(args$output, width=10, height=max(2, 0.5 * length(topPathways)))
375
+ grid::grid.draw(p)
376
+ dev.off()
377
+
378
+ cat("GSEA table plot saved to", args$output, "\\n")
379
+ """
380
+
381
+ with tempfile.TemporaryDirectory() as temp_dir:
382
+ temp_path = Path(temp_dir)
383
+ r_script_path = temp_path / "plot_gsea_table.R"
384
+ r_script_path.write_text(r_script_content)
385
+
386
+ output_plot_file = temp_path / "gsea_table_plot.pdf"
387
+
388
+ cmd = [
389
+ "Rscript", str(r_script_path),
390
+ "--pathways", str(pathways_file.resolve()),
391
+ "--stats", str(stats_file.resolve()),
392
+ "--results", str(fgsea_results_file.resolve()),
393
+ "--output", str(output_plot_file.resolve()),
394
+ "--top_n", str(top_n),
395
+ "--gseaParam", str(gsea_param),
396
+ ]
397
+
398
+ # --- Subprocess Execution ---
399
+ try:
400
+ process = subprocess.run(
401
+ cmd, check=True, capture_output=True, text=True
402
+ )
403
+ except FileNotFoundError:
404
+ raise RuntimeError(f"Rscript not found. Please ensure R is installed and in your PATH. {R_DEPENDENCIES_NOTE}")
405
+ except subprocess.CalledProcessError as e:
406
+ error_message = (
407
+ f"fgsea plot table failed with return code {e.returncode}.\n"
408
+ f"Command: {' '.join(cmd)}\n"
409
+ f"Stdout: {e.stdout}\n"
410
+ f"Stderr: {e.stderr}\n"
411
+ f"{R_DEPENDENCIES_NOTE}"
412
+ )
413
+ raise RuntimeError(error_message) from e
414
+
415
+ # --- Structured Result Return ---
416
+ return {
417
+ "command_executed": " ".join(cmd),
418
+ "stdout": process.stdout,
419
+ "stderr": process.stderr,
420
+ "output_files": {"gsea_table_plot": str(output_plot_file)}
421
+ }
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/app/bioconductor-fgsea_shim_server.py ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ from __future__ import annotations
3
+
4
+ import ast
5
+ from pathlib import Path
6
+
7
+ from mcp.server.fastmcp import FastMCP
8
+
9
+
10
+ SOURCE_SERVER = Path('/225040511/project/BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/app/bioconductor-fgsea_server.py')
11
+ SERVER_NAME = 'biosci_bioconductor_fgsea'
12
+
13
+
14
+ class _ShimMCP:
15
+ @staticmethod
16
+ def tool():
17
+ def _decorator(fn):
18
+ return fn
19
+ return _decorator
20
+
21
+
22
+ def _load_functions():
23
+ code = SOURCE_SERVER.read_text(encoding="utf-8")
24
+ tree = ast.parse(code, filename=str(SOURCE_SERVER))
25
+ function_names = [n.name for n in tree.body if isinstance(n, ast.FunctionDef) and not n.name.startswith("_")]
26
+ namespace = {
27
+ "__name__": "__mcp_source__",
28
+ "mcp": _ShimMCP(),
29
+ }
30
+ exec(compile(code, str(SOURCE_SERVER), "exec"), namespace, namespace)
31
+ loaded = []
32
+ for name in function_names:
33
+ fn = namespace.get(name)
34
+ if callable(fn):
35
+ loaded.append(fn)
36
+ return loaded
37
+
38
+
39
+ mcp = FastMCP(SERVER_NAME)
40
+ for _fn in _load_functions():
41
+ mcp.tool()(_fn)
42
+
43
+
44
+ if __name__ == "__main__":
45
+ mcp.run(transport="stdio")
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/app/requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/docker-compose.yml ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: '3.8'
2
+
3
+ services:
4
+ mcp-bioconductor-fgsea:
5
+ build: .
6
+ image: mcp-bioconductor-fgsea:latest
7
+ container_name: mcp-bioconductor-fgsea
8
+ ports:
9
+ - "8000:8000"
10
+ environment:
11
+ - MCP_SERVER_NAME=bioconductor-fgsea
12
+ volumes:
13
+ - ./workspace:/app/workspace
14
+ - ./output:/app/output
15
+ restart: unless-stopped
16
+ healthcheck:
17
+ test: ["CMD", "python", "-c", "import sys; sys.exit(0)"]
18
+ interval: 30s
19
+ timeout: 10s
20
+ retries: 3
21
+ start_period: 5s
22
+
BioScientist/agent_system/toolbase/mcp_batch_from_manual_txt/mcp_bioconductor-fgsea/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-fgsea
9
+ - python=3.10
10
+